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 <noreply@anthropic.com>
This commit is contained in:
parent
a61450fd52
commit
d6fb494409
6 changed files with 188 additions and 59 deletions
|
|
@ -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`.
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,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<Action> _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<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 +761,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
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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,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<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);
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue