CultNet C#: subscription snapshots fence older commits; deferred forwards survive a throw #187

Merged
eureka merged 6 commits from hands/cs-reconcile-sequence into main 2026-11-27 23:55:05 +00:00
6 changed files with 357 additions and 59 deletions

View file

@ -145,7 +145,12 @@ 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 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
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`.

View file

@ -2389,16 +2389,16 @@ namespace GameCult.Caching
}
}
public IEnumerable<CultStoredDocument> AllStoredDocuments
public IEnumerable<CultStoredDocument> AllStoredDocuments => AllStoredDocumentsWithSequence().Documents;
// Every change whose Sequence is at or below the returned one is reflected in the returned documents.
public (IReadOnlyList<CultStoredDocument> 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<CultCacheDocumentChange<T>> Watch<T>() where T : class

View file

@ -321,13 +321,20 @@ namespace GameCult.Networking
/// </summary>
public sealed class CultNetDatabaseCommit
{
public CultNetDatabaseCommit(string id, IReadOnlyList<object> changes)
public CultNetDatabaseCommit(string id, long sequence, IReadOnlyList<object> changes)
{
Id = id;
Sequence = sequence;
Changes = changes;
}
public string Id { get; }
/// <summary>
/// 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.
/// </summary>
public long Sequence { get; }
public IReadOnlyList<object> 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<object> Published { get; } = new();
}

View file

@ -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<CultNetEdge>());
return new ProjectedSnapshot(bySourceRecordKey, page.Edges ?? Array.Empty<CultNetEdge>(), cacheSequence);
}
private void ApplyProjectedChange(
@ -527,8 +521,65 @@ 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.
private CommitOutbox? _outbox;
// 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<Action> _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 (_forwarding)
{
_deferred.Enqueue(work);
return;
}
_forwarding = true;
Exception? first = null;
try
{
var next = work;
while (true)
{
try
{
next();
}
catch (Exception exception)
{
first ??= exception;
}
if (_deferred.Count == 0) break;
next = _deferred.Dequeue();
}
}
finally
{
_forwarding = false;
}
if (first != null)
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(first).Throw();
}
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,
string subscriptionId,
@ -707,12 +758,15 @@ namespace GameCult.Networking
public Dictionary<string, CultNetRawDocumentRecord> 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<string, CultNetRawDocumentRecord> bySourceRecordKey, CultNetEdge[]? edges = null)
public ProjectedSnapshot(Dictionary<string, CultNetRawDocumentRecord> bySourceRecordKey, CultNetEdge[]? edges = null, long sequence = 0)
{
Sequence = sequence;
BySourceRecordKey = bySourceRecordKey;
Documents = bySourceRecordKey.Values.ToArray();
Edges = edges ?? Array.Empty<CultNetEdge>();
@ -723,6 +777,7 @@ namespace GameCult.Networking
public Dictionary<string, CultNetRawDocumentRecord> BySourceRecordKey { get; }
public CultNetEdge[] Edges { get; }
public CultNetRawDocumentRecord[] Documents { get; }
public long Sequence { get; }
}
private sealed class SubscriptionKey

View file

@ -525,11 +525,24 @@ namespace GameCult.Networking
Func<string, CultRecordKey, long> ordinalOf,
ulong asOf,
CultNetDocumentMessageOptions? options,
Func<CultDocumentDescriptor, CultRecordKey, bool>? rowFilter = null)
Func<CultDocumentDescriptor, CultRecordKey, bool>? rowFilter = null) =>
SelectAll(cache, selection, ordinalOf, asOf, options, rowFilter, out _);
/// <summary>As above; <paramref name="cacheSequence"/> is the cache Sequence the evaluated rows reflect.</summary>
internal CultNetSelectionPage SelectAll(
CultCache cache,
CultNetSelection selection,
Func<string, CultRecordKey, long> ordinalOf,
ulong asOf,
CultNetDocumentMessageOptions? options,
Func<CultDocumentDescriptor, CultRecordKey, bool>? rowFilter,
out long cacheSequence)
{
selection = ExpandSchemaBindingAliases(selection);
var stored = cache.AllStoredDocuments;
var (documents, sequence) = cache.AllStoredDocumentsWithSequence();
cacheSequence = sequence;
IEnumerable<CultStoredDocument> stored = documents;
if (rowFilter != null)
stored = stored.Where(entry => rowFilter(entry.Descriptor, entry.Key));
var entries = stored.ToArray();

View file

@ -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<ReplicaItem>().SchemaId });
public object Gate => typeof(CultNetDatabaseSubscriptionServer)
.GetField("_lifecycleGate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(_server)!;
public Replication(Action<CultCache>? seedSource = null, Action<CultCache>? seedReplica = null,
Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, string, string, bool>? authorizeRecord = null)
Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, string, string, bool>? authorizeRecord = null,
Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, bool>? 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<ReplicaItem>(Replica.Registry));
Client = new CultNetDatabaseSubscriptionClient(new Client(wire, Peer), Replica, documents);
Client.Faulted += Faults.Add;
Client.SubscribeAsync("items", schemaIds: new[] { Source.Registry.GetRequired<ReplicaItem>().SchemaId })
.GetAwaiter().GetResult();
if (subscribe) Subscribe("items").GetAwaiter().GetResult();
}
public ReplicaItem? ReplicaItem(string key) => Replica.Get<ReplicaItem>(new CultRecordKey(key));
@ -741,23 +745,235 @@ 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 (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)
{
var hidden = new HashSet<string>();
var first = Task.Run(() => Stage(run.Source, ("a", "s2")));
Assert.That(SpinWait.SpinUntil(() => run.Source.Get<ReplicaItem>(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<ReplicaItem>(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);
}
// 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 release = new ManualResetEventSlim();
var hold = true;
using var run = new Replication(
source =>
{
Stage(source, ("a", "s1"), ("b", "s9"));
source.Watch<ReplicaItem>().Subscribe(_ => { if (Volatile.Read(ref hold)) release.Wait(10_000); });
},
subscribe: false);
(Task First, Task Second) writes;
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);
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);
await Until(() => run.ReplicaItem("a") == null && run.ReplicaItem("b") == null);
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);
}
// 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<ReplicaItem>(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<ReplicaItem>(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<InvalidOperationException>(() => run.Reconcile());
await Until(() => run.ReplicaItem("a")?.Sku == "three");
Assert.That(run.ReplicaItem("b")!.Sku, Is.EqualTo("two"));
Assert.That(run.Client.Fault, Is.Null);
}