From d6fb49440900247199e40e600fd1e804a7eacf00 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 23:33:37 +0100 Subject: [PATCH 1/6] CultNet subscription server: a snapshot's cache sequence fences Watch; a forward that nests inside another runs after it is sent Co-Authored-By: Claude Sonnet 5.5 --- .../cultnet/cultnet-distributed-database.md | 3 +- src/GameCult.Caching/CultCache.cs | 18 ++-- src/GameCult.Networking/CultNetDatabase.cs | 13 ++- .../CultNetDatabaseSubscriptionServer.cs | 101 ++++++++++++------ .../CultNetDocumentRegistry.cs | 17 ++- .../CultNetReplicaCommitTests.cs | 99 ++++++++++++++--- 6 files changed, 190 insertions(+), 61 deletions(-) diff --git a/contracts/cultnet/cultnet-distributed-database.md b/contracts/cultnet/cultnet-distributed-database.md index 8d35fbb6..76dd22d3 100644 --- a/contracts/cultnet/cultnet-distributed-database.md +++ b/contracts/cultnet/cultnet-distributed-database.md @@ -145,7 +145,8 @@ A malformed put or delete is `message_invalid`, not a per-operation code: the pe peer that does not know them ignores them and applies each change alone. A replica that knows them applies the commit's changes as one commit, so the replica judges the result (a swap of two unique-index values) and not the state between records. A replica whose cache refuses a commit is faulted, never silent. `commitId` is opaque and valid only - within the subscription. The C# subscription server and database server tag commits; other runtimes adopt next. + within the subscription. A server that re-evaluates a subscription (C# `Reconcile`) sends its diff as one such commit, and a server + never forwards a commit that its last snapshot to the subscription already reflects. The C# subscription server and database server tag commits; other runtimes adopt next. - The C# writer sets every key of a `database_change_raw` message, nil where unset: a removed change carries `document` nil, an added or updated one `recordKey` and `schemaId` nil. The schema accepts those nils; an added or updated change still needs a document, and a removed one a `recordKey` and `schemaId`. diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index 303d3737..62fe63a1 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -2389,16 +2389,16 @@ namespace GameCult.Caching } } - public IEnumerable AllStoredDocuments + public IEnumerable AllStoredDocuments => AllStoredDocumentsWithSequence().Documents; + + // Every change whose Sequence is at or below the returned one is reflected in the returned documents. + public (IReadOnlyList Documents, long Sequence) AllStoredDocumentsWithSequence() { - get - { - lock (Gate()) - return _entries.Values - .OrderBy(entry => entry.Descriptor.SchemaName, StringComparer.Ordinal) - .ThenBy(entry => entry.Key.Value, StringComparer.Ordinal) - .ToArray(); - } + lock (Gate()) + return (_entries.Values + .OrderBy(entry => entry.Descriptor.SchemaName, StringComparer.Ordinal) + .ThenBy(entry => entry.Key.Value, StringComparer.Ordinal) + .ToArray(), _sequence); } public Observable> Watch() where T : class diff --git a/src/GameCult.Networking/CultNetDatabase.cs b/src/GameCult.Networking/CultNetDatabase.cs index abd04d01..6c4f65fa 100644 --- a/src/GameCult.Networking/CultNetDatabase.cs +++ b/src/GameCult.Networking/CultNetDatabase.cs @@ -321,13 +321,20 @@ namespace GameCult.Networking /// public sealed class CultNetDatabaseCommit { - public CultNetDatabaseCommit(string id, IReadOnlyList changes) + public CultNetDatabaseCommit(string id, long sequence, IReadOnlyList changes) { Id = id; + Sequence = sequence; Changes = changes; } public string Id { get; } + + /// + /// The cache Sequence of the commit's last change: every change of the commit is at or below it, and no change of another + /// commit lies between its first and its last. A snapshot read at a cache Sequence at or above this already reflects the commit. + /// + public long Sequence { get; } public IReadOnlyList Changes { get; } } @@ -1329,6 +1336,7 @@ namespace GameCult.Networking { _stash[change.Sequence] = new Publication(documentType, kind, change.Key, descriptor.SchemaId, shard, change.Document, change.PreviousDocument, commit); commit.Unpublished++; + commit.Sequence = change.Sequence; } } @@ -1379,7 +1387,7 @@ namespace GameCult.Networking if (change != null) commit.Published.Add(change); if (--commit.Unpublished == 0 && commit.Published.Count > 0) - finished = new CultNetDatabaseCommit(commit.Id, commit.Published.ToArray()); + finished = new CultNetDatabaseCommit(commit.Id, commit.Sequence, commit.Published.ToArray()); } if (finished != null) @@ -1551,6 +1559,7 @@ namespace GameCult.Networking public CommitGroup(string id) => Id = id; public string Id { get; } public int Unpublished { get; set; } + public long Sequence { get; set; } public List Published { get; } = new(); } diff --git a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs index 3e23cf10..54217519 100644 --- a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs +++ b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs @@ -75,22 +75,15 @@ namespace GameCult.Networking { lock (_lifecycleGate) { - if (_disposed) return; - foreach (var entry in _requests.ToArray()) + // A snapshot Reconcile takes can reflect commits Watch has not seen yet; the projection's AsOfSequence makes Watch + // drop them. Its diff is held and sent as one commit of its own, as Watch's is, for the replica to judge whole, + // and a Reconcile that arrives inside another forward waits until that one is sent. + Forward(() => { - // Reconcile can run after the cache has admitted a commit and before Watch has seen it, so its diff can carry - // changed values; it is held and sent as one commit of its own, as Watch's is, for the replica to judge whole. - var outbox = _outbox = new CommitOutbox(Guid.NewGuid().ToString("N")); - try - { - Reconcile(entry.Key, entry.Value); - } - finally - { - _outbox = null; - outbox.Send(entry.Key.Peer); - } - } + if (_disposed) return; + foreach (var entry in _requests.ToArray()) + InOutbox(Guid.NewGuid().ToString("N"), entry.Key.Peer, () => Reconcile(entry.Key, entry.Value)); + }); } } @@ -194,6 +187,7 @@ namespace GameCult.Networking var snapshot = CreateProjectedSnapshot(request, peer); foreach (var entry in snapshot.BySourceRecordKey) projection.DeliveredBySourceRecordKey[entry.Key] = entry.Value; + projection.AsOfSequence = snapshot.Sequence; SendSnapshot(peer, request, snapshot); } else @@ -317,20 +311,18 @@ namespace GameCult.Networking { lock (_lifecycleGate) { - if (_disposed || !_requests.ContainsKey(key) || !_projections.TryGetValue(key, out var projection)) - return; - // What this subscription sends for the commit is held and sent together, tagged with the commit, so the replica - // applies it as one commit and judges the result. - var outbox = _outbox = new CommitOutbox(commit.Id); - try + Forward(() => { - ForwardCommit(commit, request, key, projection, legacyRequest, peer, subscriptionId); - } - finally - { - _outbox = null; - outbox.Send(peer); - } + if (_disposed || !_requests.ContainsKey(key) || !_projections.TryGetValue(key, out var projection)) + return; + // The snapshot this subscription holds already reflects the commit. + if (commit.Sequence <= projection.AsOfSequence) + return; + // What this subscription sends for the commit is held and sent together, tagged with the commit, so the replica + // applies it as one commit and judges the result. + InOutbox(commit.Id, peer, () => + ForwardCommit(commit, request, key, projection, legacyRequest, peer, subscriptionId)); + }); } }); } @@ -430,6 +422,7 @@ namespace GameCult.Networking projection.DeliveredBySourceRecordKey.Clear(); foreach (var current in next.BySourceRecordKey) projection.DeliveredBySourceRecordKey[current.Key] = current.Value; + projection.AsOfSequence = Math.Max(projection.AsOfSequence, next.Sequence); if (projection.DemandActive != authorized) { @@ -461,7 +454,8 @@ namespace GameCult.Networking ordinalOf: (schemaId, key) => _database.LastWriteSequence(schemaId, key) ?? 0, asOf: _database.CurrentAsOf(), options: null, - rowFilter: _database.Owns); + rowFilter: _database.Owns, + out var cacheSequence); // The snapshot is one row per record key by construction, so the duplicate-key throw this // used to guard can no longer fire (docs/cultnet-selection-cut.md, S2-2); deleted rather // than tested around. @@ -473,7 +467,7 @@ namespace GameCult.Networking continue; bySourceRecordKey[sourceRecordKey] = source; } - return new ProjectedSnapshot(bySourceRecordKey, page.Edges ?? Array.Empty()); + return new ProjectedSnapshot(bySourceRecordKey, page.Edges ?? Array.Empty(), cacheSequence); } private void ApplyProjectedChange( @@ -527,7 +521,48 @@ namespace GameCult.Networking string.Equals(left.SourceRole, right.SourceRole, StringComparison.Ordinal); // The commit being forwarded, under _lifecycleGate: the change messages it produces are held here, not sent one by one. + // Set only by InOutbox; at most one is open. A forward that arrives while one is open (a DemandChanged handler, an + // authorizer or a cache write re-entering on this thread) waits in _deferred and runs after the open one is sent, so + // its older held changes are never overtaken. private CommitOutbox? _outbox; + private readonly Queue _deferred = new(); + private bool _draining; + + // Under _lifecycleGate: runs work now, or after the open outbox is sent. + private void Forward(Action work) + { + if (_outbox != null) + { + _deferred.Enqueue(work); + return; + } + work(); + if (_draining) return; + _draining = true; + try + { + while (_deferred.Count > 0) + _deferred.Dequeue()(); + } + finally + { + _draining = false; + } + } + + private void InOutbox(string commitId, ICultNetSchemaServerPeer peer, Action produce) + { + var outbox = _outbox = new CommitOutbox(commitId); + try + { + produce(); + } + finally + { + _outbox = null; + outbox.Send(peer); + } + } private void SendUpsert( ICultNetSchemaServerPeer peer, @@ -707,12 +742,15 @@ namespace GameCult.Networking public Dictionary DeliveredBySourceRecordKey { get; } = new(StringComparer.Ordinal); public bool DemandActive { get; set; } + // The cache Sequence of the newest snapshot this subscription holds; Watch drops commits at or below it. + public long AsOfSequence { get; set; } } private sealed class ProjectedSnapshot { - public ProjectedSnapshot(Dictionary bySourceRecordKey, CultNetEdge[]? edges = null) + public ProjectedSnapshot(Dictionary bySourceRecordKey, CultNetEdge[]? edges = null, long sequence = 0) { + Sequence = sequence; BySourceRecordKey = bySourceRecordKey; Documents = bySourceRecordKey.Values.ToArray(); Edges = edges ?? Array.Empty(); @@ -723,6 +761,7 @@ namespace GameCult.Networking public Dictionary BySourceRecordKey { get; } public CultNetEdge[] Edges { get; } public CultNetRawDocumentRecord[] Documents { get; } + public long Sequence { get; } } private sealed class SubscriptionKey diff --git a/src/GameCult.Networking/CultNetDocumentRegistry.cs b/src/GameCult.Networking/CultNetDocumentRegistry.cs index 5b21c9de..1a29725f 100644 --- a/src/GameCult.Networking/CultNetDocumentRegistry.cs +++ b/src/GameCult.Networking/CultNetDocumentRegistry.cs @@ -525,11 +525,24 @@ namespace GameCult.Networking Func ordinalOf, ulong asOf, CultNetDocumentMessageOptions? options, - Func? rowFilter = null) + Func? rowFilter = null) => + SelectAll(cache, selection, ordinalOf, asOf, options, rowFilter, out _); + + /// As above; is the cache Sequence the evaluated rows reflect. + internal CultNetSelectionPage SelectAll( + CultCache cache, + CultNetSelection selection, + Func ordinalOf, + ulong asOf, + CultNetDocumentMessageOptions? options, + Func? rowFilter, + out long cacheSequence) { selection = ExpandSchemaBindingAliases(selection); - var stored = cache.AllStoredDocuments; + var (documents, sequence) = cache.AllStoredDocumentsWithSequence(); + cacheSequence = sequence; + IEnumerable stored = documents; if (rowFilter != null) stored = stored.Where(entry => rowFilter(entry.Descriptor, entry.Key)); var entries = stored.ToArray(); diff --git a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs index b38592ec..784c2234 100644 --- a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs @@ -107,23 +107,27 @@ namespace GameCult.Networking.Tests public CultNetDatabase Database { get; } private readonly CultNetDatabaseSubscriptionServer _server; public void Reconcile() => _server.Reconcile(); + public CultNetDatabaseSubscriptionServer Server => _server; + public Task Subscribe(string id) => + Client.SubscribeAsync(id, schemaIds: new[] { Source.Registry.GetRequired().SchemaId }); public object Gate => typeof(CultNetDatabaseSubscriptionServer) .GetField("_lifecycleGate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(_server)!; public Replication(Action? seedSource = null, Action? seedReplica = null, - Func? authorizeRecord = null) + Func? authorizeRecord = null, + Func? authorizeRequest = null, + bool subscribe = true) { seedSource?.Invoke(Source); seedReplica?.Invoke(Replica); Database = new CultNetDatabase(Source); var wire = new LoopbackServer(); - _server = new CultNetDatabaseSubscriptionServer(wire, Database, authorizeRecord: authorizeRecord); + _server = new CultNetDatabaseSubscriptionServer(wire, Database, authorizeRecord: authorizeRecord, authorizeRequest: authorizeRequest); var documents = new CultNetDocumentRegistry(Replica.Registry) .Register(CultNetDocumentBinding.ForDocument(Replica.Registry)); Client = new CultNetDatabaseSubscriptionClient(new Client(wire, Peer), Replica, documents); Client.Faulted += Faults.Add; - Client.SubscribeAsync("items", schemaIds: new[] { Source.Registry.GetRequired().SchemaId }) - .GetAwaiter().GetResult(); + if (subscribe) Subscribe("items").GetAwaiter().GetResult(); } public ReplicaItem? ReplicaItem(string key) => Replica.Get(new CultRecordKey(key)); @@ -741,23 +745,86 @@ namespace GameCult.Networking.Tests Assert.That(run.Peer.Changes.Select(change => change.CommitCount), Is.All.EqualTo(2)); } - [Test] - public async Task ReconcilingAfterAPolicyChangeThatFollowsASwapLeavesTheReplicaIntact() + // Two commits the cache admitted and Watch has not seen (the subscription server's gate is held, so neither publisher has + // run; the test waits for the source to hold both, so the interleaving is forced, not hoped for). C1 sets a=s2, C2 sets a=s3 + // and b=s2, valid only after C1. A snapshot taken now reflects both; Watch must not replay C1 over it. + private static (Task First, Task Second) AdmitTwoCommitsBehindTheGate(Replication run) { - var hidden = new HashSet(); + var first = Task.Run(() => Stage(run.Source, ("a", "s2"))); + Assert.That(SpinWait.SpinUntil(() => run.Source.Get(new CultRecordKey("a"))!.Sku == "s2", 10_000), + "the source did not take the first commit"); + var second = Task.Run(() => Stage(run.Source, ("a", "s3"), ("b", "s2"))); + Assert.That(SpinWait.SpinUntil(() => run.Source.Get(new CultRecordKey("a"))!.Sku == "s3", 10_000), + "the source did not take the second commit"); + return (first, second); + } + + [Test] + public async Task AReconcileAheadOfTwoCommitsLeavesTheReplicaIntact() + { + using var run = new Replication(source => Stage(source, ("a", "s1"), ("b", "s9"))); + (Task First, Task Second) writes; + + lock (run.Gate) + { + writes = AdmitTwoCommitsBehindTheGate(run); + run.Reconcile(); + } + await Task.WhenAll(writes.First, writes.Second); + await Until(() => run.ReplicaItem("a")!.Sku == "s3" && run.ReplicaItem("b")!.Sku == "s2"); + await Task.Delay(100); + + Assert.That(run.ReplicaItem("a")!.Sku, Is.EqualTo("s3")); + Assert.That(run.ReplicaItem("b")!.Sku, Is.EqualTo("s2")); + Assert.That(run.Client.Fault, Is.Null); + } + + [Test] + public async Task ASubscribeSnapshotAheadOfAPendingCommitIsNotReplayed() + { + using var run = new Replication(source => Stage(source, ("a", "s1"), ("b", "s9")), subscribe: false); + (Task First, Task Second) writes; + + lock (run.Gate) + { + writes = AdmitTwoCommitsBehindTheGate(run); + run.Subscribe("late").GetAwaiter().GetResult(); + } + await Task.WhenAll(writes.First, writes.Second); + await Until(() => run.ReplicaItem("a")?.Sku == "s3" && run.ReplicaItem("b")?.Sku == "s2"); + await Task.Delay(100); + + Assert.That(run.ReplicaItem("a")!.Sku, Is.EqualTo("s3")); + Assert.That(run.ReplicaItem("b")!.Sku, Is.EqualTo("s2")); + Assert.That(run.Client.Fault, Is.Null); + } + + // A DemandChanged handler writes while Reconcile's diff is still held. The write publishes on this thread and re-enters + // Watch; its commit is newer than the diff, so it must reach the replica after the diff, not before it. + [Test] + public async Task AWriteFromADemandHandlerReachesTheReplicaAfterTheReconcileThatRaisedIt() + { + var allowed = true; + var armed = false; using var run = new Replication(source => Stage(source, ("a", "one"), ("b", "two")), - authorizeRecord: (_, _, key, _) => !hidden.Contains(key)); - hidden.Add("b"); + authorizeRequest: (_, _) => allowed); + run.Server.DemandChanged += demand => + { + if (armed && demand.Active) Stage(run.Source, ("a", "three")); + }; - Stage(run.Source, ("a", "two"), ("b", "one")); - await Until(() => run.ReplicaItem("b") == null && run.ReplicaItem("a")!.Sku == "two"); - - hidden.Remove("b"); - hidden.Add("a"); + allowed = false; run.Reconcile(); - await Until(() => run.ReplicaItem("b") != null && run.ReplicaItem("a") == null); + Assert.That(run.ReplicaItem("a"), Is.Null, "the unauthorized reconcile withdraws the rows"); - Assert.That(run.ReplicaItem("b")!.Sku, Is.EqualTo("one")); + armed = true; + allowed = true; + run.Reconcile(); + await Until(() => run.ReplicaItem("a")?.Sku == "three"); + await Task.Delay(100); + + Assert.That(run.ReplicaItem("a")!.Sku, Is.EqualTo("three")); + Assert.That(run.ReplicaItem("b")!.Sku, Is.EqualTo("two")); Assert.That(run.Client.Fault, Is.Null); } -- 2.47.3 From e3d038308f828c51ed63e6b20cf515e4d6bc8951 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 23:36:25 +0100 Subject: [PATCH 2/6] Test: wait for the unauthorized reconcile's removals --- tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs index 784c2234..18d389b6 100644 --- a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs @@ -815,7 +815,7 @@ namespace GameCult.Networking.Tests allowed = false; run.Reconcile(); - Assert.That(run.ReplicaItem("a"), Is.Null, "the unauthorized reconcile withdraws the rows"); + await Until(() => run.ReplicaItem("a") == null && run.ReplicaItem("b") == null); armed = true; allowed = true; -- 2.47.3 From 7285794f157e6a0c5fc02693d37e3410396cb592 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 23:39:56 +0100 Subject: [PATCH 3/6] Test: Subscribe snapshot ahead of a pending commit is forced by a cache observer ahead of the journal --- .../CultNetReplicaCommitTests.cs | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs index 18d389b6..1bc9a320 100644 --- a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs @@ -745,8 +745,8 @@ namespace GameCult.Networking.Tests Assert.That(run.Peer.Changes.Select(change => change.CommitCount), Is.All.EqualTo(2)); } - // Two commits the cache admitted and Watch has not seen (the subscription server's gate is held, so neither publisher has - // run; the test waits for the source to hold both, so the interleaving is forced, not hoped for). C1 sets a=s2, C2 sets a=s3 + // Two commits the cache admitted and Watch has not seen (a gate holds the publishers; the test waits for the source to + // hold both, so the interleaving is forced, not hoped for). C1 sets a=s2, C2 sets a=s3 // and b=s2, valid only after C1. A snapshot taken now reflects both; Watch must not replay C1 over it. private static (Task First, Task Second) AdmitTwoCommitsBehindTheGate(Replication run) { @@ -779,17 +779,27 @@ namespace GameCult.Networking.Tests Assert.That(run.Client.Fault, Is.Null); } + // Subscribe registers Watch under the gate and then reads its snapshot; a commit the cache admitted before that read and + // that has not reached the journal yet is delivered to Watch afterwards. A cache observer registered ahead of the database's + // holds both writers between admission and publication, so the subscription is made inside that window. [Test] public async Task ASubscribeSnapshotAheadOfAPendingCommitIsNotReplayed() { - using var run = new Replication(source => Stage(source, ("a", "s1"), ("b", "s9")), subscribe: false); + using var release = new ManualResetEventSlim(); + var hold = true; + using var run = new Replication( + source => + { + Stage(source, ("a", "s1"), ("b", "s9")); + source.Watch().Subscribe(_ => { if (Volatile.Read(ref hold)) release.Wait(10_000); }); + }, + subscribe: false); (Task First, Task Second) writes; - lock (run.Gate) - { - writes = AdmitTwoCommitsBehindTheGate(run); - run.Subscribe("late").GetAwaiter().GetResult(); - } + writes = AdmitTwoCommitsBehindTheGate(run); + run.Subscribe("late").GetAwaiter().GetResult(); + Volatile.Write(ref hold, false); + release.Set(); await Task.WhenAll(writes.First, writes.Second); await Until(() => run.ReplicaItem("a")?.Sku == "s3" && run.ReplicaItem("b")?.Sku == "s2"); await Task.Delay(100); -- 2.47.3 From 30eb3a4edd861439a36054a6a8a0ff94c185460d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 23:44:31 +0100 Subject: [PATCH 4/6] CultNet contract: one stated buffer bound covers every commit, Reconcile's included variants:ruling:reconcile-commit-stated-bound: a replica may bound what it buffers across incomplete commits; a commit past it faults the replica loudly and the consumer resubscribes for a snapshot; servers do not split commits. Co-Authored-By: Claude Opus 5.5 --- contracts/cultnet/cultnet-distributed-database.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/contracts/cultnet/cultnet-distributed-database.md b/contracts/cultnet/cultnet-distributed-database.md index 76dd22d3..62bde066 100644 --- a/contracts/cultnet/cultnet-distributed-database.md +++ b/contracts/cultnet/cultnet-distributed-database.md @@ -146,7 +146,11 @@ A malformed put or delete is `message_invalid`, not a per-operation code: the pe commit's changes as one commit, so the replica judges the result (a swap of two unique-index values) and not the state between records. A replica whose cache refuses a commit is faulted, never silent. `commitId` is opaque and valid only within the subscription. A server that re-evaluates a subscription (C# `Reconcile`) sends its diff as one such commit, and a server - never forwards a commit that its last snapshot to the subscription already reflects. The C# subscription server and database server tag commits; other runtimes adopt next. + never forwards a commit that its last snapshot to the subscription already reflects. A replica may bound how many + changes it buffers across incomplete commits (the C# client: `MaxBufferedChanges`, 1,000,000). One bound covers every + commit, whatever made it, a `Reconcile` diff included: a commit announcing more faults the replica loudly, and a faulted + consumer resubscribes for a snapshot, which is one message and has no such bound. A server does not split a commit to + fit a replica's bound. The C# subscription server and database server tag commits; other runtimes adopt next. - The C# writer sets every key of a `database_change_raw` message, nil where unset: a removed change carries `document` nil, an added or updated one `recordKey` and `schemaId` nil. The schema accepts those nils; an added or updated change still needs a document, and a removed one a `recordKey` and `schemaId`. -- 2.47.3 From 413c64a4424220d104a5cb0d2ee26cc894fd7fb8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 23:56:37 +0100 Subject: [PATCH 5/6] CultNet subscription server: a forward that throws still drains the deferred ones in order; contract scopes the fence to the C# subscription server; tests pin the fence boundary, the max, queue order and a nested Reconcile Co-Authored-By: Claude Sonnet 5.5 --- .../cultnet/cultnet-distributed-database.md | 4 +- .../CultNetDatabaseSubscriptionServer.cs | 42 ++++-- .../CultNetReplicaCommitTests.cs | 141 ++++++++++++++++++ 3 files changed, 172 insertions(+), 15 deletions(-) diff --git a/contracts/cultnet/cultnet-distributed-database.md b/contracts/cultnet/cultnet-distributed-database.md index 62bde066..a1c20466 100644 --- a/contracts/cultnet/cultnet-distributed-database.md +++ b/contracts/cultnet/cultnet-distributed-database.md @@ -145,8 +145,8 @@ A malformed put or delete is `message_invalid`, not a per-operation code: the pe peer that does not know them ignores them and applies each change alone. A replica that knows them applies the commit's changes as one commit, so the replica judges the result (a swap of two unique-index values) and not the state between records. A replica whose cache refuses a commit is faulted, never silent. `commitId` is opaque and valid only - within the subscription. A server that re-evaluates a subscription (C# `Reconcile`) sends its diff as one such commit, and a server - never forwards a commit that its last snapshot to the subscription already reflects. A replica may bound how many + within the subscription. A server that re-evaluates a subscription (C# `Reconcile`) sends its diff as one such commit, and the C# subscription server + never forwards a commit that its last snapshot to the subscription already reflects (the database server adopts next). A replica may bound how many changes it buffers across incomplete commits (the C# client: `MaxBufferedChanges`, 1,000,000). One bound covers every commit, whatever made it, a `Reconcile` diff included: a commit announcing more faults the replica loudly, and a faulted consumer resubscribes for a snapshot, which is one message and has no such bound. A server does not split a commit to diff --git a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs index 54217519..051cb050 100644 --- a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs +++ b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs @@ -521,33 +521,49 @@ namespace GameCult.Networking string.Equals(left.SourceRole, right.SourceRole, StringComparison.Ordinal); // The commit being forwarded, under _lifecycleGate: the change messages it produces are held here, not sent one by one. - // Set only by InOutbox; at most one is open. A forward that arrives while one is open (a DemandChanged handler, an - // authorizer or a cache write re-entering on this thread) waits in _deferred and runs after the open one is sent, so - // its older held changes are never overtaken. + // Set only by InOutbox; at most one is open. private CommitOutbox? _outbox; - private readonly Queue _deferred = new(); - private bool _draining; - // Under _lifecycleGate: runs work now, or after the open outbox is sent. + // One forward runs at a time. A forward that arrives while another is running (a DemandChanged handler, an authorizer, a + // cache write or a replica handler re-entering on this thread, while the outbox is open or being sent) waits in _deferred + // and runs, in arrival order, after the running one, so its older held changes are never overtaken. + private readonly Queue _deferred = new(); + private bool _forwarding; + + // Under _lifecycleGate: runs work now, or after the running forward. A forward that throws does not strand the deferred + // ones: all of them run, and the first exception is rethrown afterwards. private void Forward(Action work) { - if (_outbox != null) + if (_forwarding) { _deferred.Enqueue(work); return; } - work(); - if (_draining) return; - _draining = true; + _forwarding = true; + Exception? first = null; try { - while (_deferred.Count > 0) - _deferred.Dequeue()(); + var next = work; + while (true) + { + try + { + next(); + } + catch (Exception exception) + { + first ??= exception; + } + if (_deferred.Count == 0) break; + next = _deferred.Dequeue(); + } } finally { - _draining = false; + _forwarding = false; } + if (first != null) + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(first).Throw(); } private void InOutbox(string commitId, ICultNetSchemaServerPeer peer, Action produce) diff --git a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs index 1bc9a320..044b34ea 100644 --- a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs @@ -838,6 +838,147 @@ namespace GameCult.Networking.Tests Assert.That(run.Client.Fault, Is.Null); } + // A commit exactly at the snapshot's sequence is reflected by it and sends nothing; one above it is news. + [Test] + public async Task ACommitAtTheSnapshotSequenceIsDroppedAndOneAboveIsApplied() + { + using var run = new Replication(source => Stage(source, ("a", "s1"), ("b", "s9"))); + Task write; + int sentAtRelease; + + lock (run.Gate) + { + write = Task.Run(() => Stage(run.Source, ("a", "s2"))); + Assert.That(SpinWait.SpinUntil(() => run.Source.Get(new CultRecordKey("a"))!.Sku == "s2", 10_000)); + run.Reconcile(); + sentAtRelease = run.Peer.Sent.Count; + } + await write; + await Task.Delay(200); + Assert.That(run.Peer.Sent.Count, Is.EqualTo(sentAtRelease), "the commit the snapshot reflects was sent again"); + + Stage(run.Source, ("a", "s4")); + await Until(() => run.ReplicaItem("a")!.Sku == "s4"); + Assert.That(run.Client.Fault, Is.Null); + } + + // An unauthorized Reconcile takes the empty snapshot; it must not lower the fence the last real snapshot set. + [Test] + public async Task AnUnauthorizedReconcileDoesNotLowerTheFence() + { + var allowed = true; + using var run = new Replication(source => Stage(source, ("a", "s1"), ("b", "s9")), + authorizeRequest: (_, _) => allowed); + Task write; + int sentAtRelease; + + lock (run.Gate) + { + write = Task.Run(() => Stage(run.Source, ("a", "s2"))); + Assert.That(SpinWait.SpinUntil(() => run.Source.Get(new CultRecordKey("a"))!.Sku == "s2", 10_000)); + run.Reconcile(); + allowed = false; + run.Reconcile(); + allowed = true; + sentAtRelease = run.Peer.Sent.Count; + } + await write; + await Task.Delay(200); + + Assert.That(run.Peer.Sent.Count, Is.EqualTo(sentAtRelease), "a commit the fence covered was replayed"); + } + + // Two writes from one handler are two commits deferred behind the open diff; they reach the replica in the order written. + [Test] + public async Task DeferredCommitsReachTheReplicaInArrivalOrder() + { + var armed = false; + var allowed = true; + using var run = new Replication(source => Stage(source, ("a", "one"), ("b", "two")), + authorizeRequest: (_, _) => allowed); + run.Server.DemandChanged += demand => + { + if (!armed || !demand.Active) return; + Stage(run.Source, ("a", "three")); + Stage(run.Source, ("a", "four")); + }; + allowed = false; + run.Reconcile(); + await Until(() => run.ReplicaItem("a") == null); + + armed = true; + allowed = true; + run.Reconcile(); + await Until(() => run.ReplicaItem("a")?.Sku == "four"); + await Task.Delay(100); + + Assert.That(run.ReplicaItem("a")!.Sku, Is.EqualTo("four")); + Assert.That(run.Client.Fault, Is.Null); + } + + // A Reconcile called from inside a forward is a forward of its own: it runs after the open diff, on state that includes + // the handler's write, and does not send the older held diff over it. + [Test] + public async Task AReconcileNestedInsideAForwardRunsAfterIt() + { + var armed = false; + var allowed = true; + using var run = new Replication(source => Stage(source, ("a", "one"), ("b", "two")), + authorizeRequest: (_, _) => allowed); + run.Server.DemandChanged += demand => + { + if (!armed || !demand.Active) return; + armed = false; + Stage(run.Source, ("a", "three")); + run.Reconcile(); + }; + allowed = false; + run.Reconcile(); + await Until(() => run.ReplicaItem("a") == null); + + armed = true; + allowed = true; + run.Reconcile(); + await Until(() => run.ReplicaItem("a")?.Sku == "three"); + await Task.Delay(100); + + Assert.That(run.ReplicaItem("a")!.Sku, Is.EqualTo("three")); + Assert.That(run.ReplicaItem("b")!.Sku, Is.EqualTo("two")); + Assert.That(run.Client.Fault, Is.Null); + } + + // A second DemandChanged handler throws after the first wrote. The write's commit was deferred; the throw must not strand + // it, and the replica ends equal to the source. + [Test] + public async Task AThrowFromTheOpenForwardDoesNotStrandADeferredCommit() + { + var armed = false; + var allowed = true; + using var run = new Replication(source => Stage(source, ("a", "one"), ("b", "two")), + authorizeRequest: (_, _) => allowed); + run.Server.DemandChanged += demand => + { + if (armed && demand.Active) Stage(run.Source, ("a", "three")); + }; + run.Server.DemandChanged += demand => + { + if (armed && demand.Active) throw new InvalidOperationException("second handler"); + }; + allowed = false; + run.Reconcile(); + await Until(() => run.ReplicaItem("a") == null); + + armed = true; + allowed = true; + Assert.Throws(() => run.Reconcile()); + armed = false; + Stage(run.Source, ("a", "four")); + await Until(() => run.ReplicaItem("a")?.Sku == "four"); + + Assert.That(run.ReplicaItem("b")!.Sku, Is.EqualTo("two")); + Assert.That(run.Client.Fault, Is.Null); + } + // Source, wire and client all real: a CultNetDatabaseServer behind a Server on a loopback socket, a LiteNetLib client // standing in for the transport of a CultNetDatabaseSubscriptionClient. No handler is called directly. private sealed class SocketClient : ICultNetSchemaClient -- 2.47.3 From c339a2907b7c6bc5d98f0fd96a91e8384cf31dc8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 23:56:45 +0100 Subject: [PATCH 6/6] Test: the throw test waits for the deferred commit itself --- tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs index 044b34ea..78b1f4d0 100644 --- a/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetReplicaCommitTests.cs @@ -971,9 +971,7 @@ namespace GameCult.Networking.Tests armed = true; allowed = true; Assert.Throws(() => run.Reconcile()); - armed = false; - Stage(run.Source, ("a", "four")); - await Until(() => run.ReplicaItem("a")?.Sku == "four"); + await Until(() => run.ReplicaItem("a")?.Sku == "three"); Assert.That(run.ReplicaItem("b")!.Sku, Is.EqualTo("two")); Assert.That(run.Client.Fault, Is.Null); -- 2.47.3