Carry order as data: per-cache change Sequence, no delivery scheduler
bcae483made the cache a delivery scheduler (tickets, _deliveryGate turn waits, per-thread delivery queues). It deadlocked inside CultLib: a load's delivery reaching a CultNetDatabaseSubscriptionServer observer that needs _lifecycleGate, while a subscribe's demand handler holding that gate writes the cache and waits for the delivery's turn. The cache now owns order as data. Every admitted change takes the next value of a per-cache in-memory sequence under the gate, published as CultCacheDocumentChange<T>.Sequence. Delivery is the 544c087/b653f68 rule: each call publishes its own changes on its own thread after releasing the gate; nothing waits on another call's delivery. Cross-thread delivery order is not guaranteed. Deleted: ticket counter, _delivered, _deliveryGate, Monitor.Wait turns, per-thread delivery queues, per-ticket catch-all, and the save-order contract text with its observer-must-not-block rule. Consumer: a cache-backed CultMesh document handle hands its observed and reactive mirrors each snapshot's Sequence; ApplyCanonicalSnapshot drops one not newer than the last applied. Tests: SequenceIncreasesInAdmissionOrder, ObserverWritingTheSameCacheDoesNotWaitOnOtherDeliveries, SubscriptionDemandHandlerWritingCacheDuringDeliveryDoesNotDeadlock, WatchRecordIgnoresStaleSequence. The last three time out onbcae483. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
bcae4839d0
commit
456234018f
8 changed files with 233 additions and 166 deletions
|
|
@ -757,65 +757,60 @@ namespace GameCult.Caching.Tests
|
|||
batch.Upsert(new Counter { Name = "counter", Value = value }, new CultRecordHandle<Counter>(Key));
|
||||
});
|
||||
|
||||
// Delivered in save order: each change replaces the document the previously delivered change installed.
|
||||
// One writer's delivery is parked in an observer; other writers, whose observers write the same cache, finish.
|
||||
// The cache is not disposed on failure because a stuck delivery would hang disposal too.
|
||||
[Test]
|
||||
public void ConcurrentWritersDeliverInSaveOrder()
|
||||
public void ObserverWritingTheSameCacheDoesNotWaitOnOtherDeliveries()
|
||||
{
|
||||
var cache = new CultCache(Registry);
|
||||
using var release = new ManualResetEventSlim();
|
||||
using var parked = new ManualResetEventSlim();
|
||||
using var park = cache.Watch<Counter>().Subscribe(change =>
|
||||
{
|
||||
if (change.Key.Value != "parked") return;
|
||||
parked.Set();
|
||||
release.Wait(TimeSpan.FromSeconds(30));
|
||||
});
|
||||
using var tallies = cache.Watch<Counter>().Subscribe(change =>
|
||||
cache.UpsertAsync(new Tally { Name = $"t:{change.Key.Value}" }, new CultRecordHandle<Tally>(new CultRecordKey($"t:{change.Key.Value}"))));
|
||||
|
||||
var parkedWriter = Task.Run(() => cache.UpsertAsync(new Counter { Name = "parked" }, new CultRecordHandle<Counter>(new CultRecordKey("parked"))));
|
||||
Assert.That(parked.Wait(TimeSpan.FromSeconds(5)), Is.True);
|
||||
var writers = Enumerable.Range(0, 8).Select(thread => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < 100; i++)
|
||||
cache.UpsertAsync(new Counter { Name = $"c:{thread}", Value = i }, new CultRecordHandle<Counter>(new CultRecordKey($"c:{thread}")));
|
||||
})).ToArray();
|
||||
var finished = Task.WaitAll(writers, TimeSpan.FromSeconds(10));
|
||||
release.Set();
|
||||
|
||||
Assert.That(finished, Is.True, "a writer waited on another thread's delivery");
|
||||
Assert.That(parkedWriter.Wait(TimeSpan.FromSeconds(10)), Is.True);
|
||||
cache.Dispose();
|
||||
}
|
||||
|
||||
// Ordered by Sequence, each change replaces the document installed by the change before it.
|
||||
[Test]
|
||||
public void SequenceIncreasesInAdmissionOrder()
|
||||
{
|
||||
using var cache = new CultCache(Registry);
|
||||
var key = new CultRecordKey("ordered");
|
||||
var observed = new System.Collections.Generic.List<(object? Document, object? Previous)>();
|
||||
using var subscription = cache.Watch<Counter>().Subscribe(change =>
|
||||
{
|
||||
lock (observed)
|
||||
observed.Add((change.Document, change.PreviousDocument));
|
||||
});
|
||||
var observed = new ConcurrentBag<CultCacheDocumentChange<Counter>>();
|
||||
using var subscription = cache.Watch<Counter>().Subscribe(observed.Add);
|
||||
|
||||
var writers = Enumerable.Range(0, 8).Select(thread => Task.Run(() =>
|
||||
var writers = Enumerable.Range(0, 8).Select(_ => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < 2000; i++)
|
||||
cache.UpsertAsync(new Counter { Name = "ordered", Value = i }, new CultRecordHandle<Counter>(key));
|
||||
})).ToArray();
|
||||
|
||||
Assert.That(Task.WaitAll(writers, TimeSpan.FromSeconds(60)), Is.True);
|
||||
Assert.That(observed, Has.Count.EqualTo(16000));
|
||||
Assert.That(FirstOutOfOrder(observed), Is.EqualTo(-1), "a change was delivered out of save order");
|
||||
}
|
||||
|
||||
// The cache is not disposed on failure because a deadlocked delivery would hang the test thread too.
|
||||
[Test]
|
||||
public void ObserverWritingTheSameCacheDuringConcurrentDeliveryDoesNotDeadlock()
|
||||
{
|
||||
var cache = new CultCache(Registry);
|
||||
var tally = new CultRecordKey("tally");
|
||||
var observed = new System.Collections.Generic.List<(object? Document, object? Previous)>();
|
||||
using var counters = cache.Watch<Counter>().Subscribe(_ =>
|
||||
cache.UpsertAsync(new Tally { Name = "tally" }, new CultRecordHandle<Tally>(tally)));
|
||||
using var tallies = cache.Watch<Tally>().Subscribe(change =>
|
||||
{
|
||||
lock (observed)
|
||||
observed.Add((change.Document, change.PreviousDocument));
|
||||
});
|
||||
|
||||
var writers = Enumerable.Range(0, 8).Select(thread => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < 500; i++)
|
||||
cache.UpsertAsync(new Counter { Name = $"c:{thread}", Value = i }, new CultRecordHandle<Counter>(new CultRecordKey($"c:{thread}")));
|
||||
})).ToArray();
|
||||
|
||||
Assert.That(Task.WaitAll(writers, TimeSpan.FromSeconds(60)), Is.True, "an observer writing the cache during delivery deadlocked");
|
||||
Assert.That(observed, Has.Count.EqualTo(4000));
|
||||
Assert.That(FirstOutOfOrder(observed), Is.EqualTo(-1), "an observer's write was delivered out of save order");
|
||||
cache.Dispose();
|
||||
}
|
||||
|
||||
private static int FirstOutOfOrder(System.Collections.Generic.List<(object? Document, object? Previous)> observed)
|
||||
{
|
||||
for (var i = 1; i < observed.Count; i++)
|
||||
{
|
||||
if (!ReferenceEquals(observed[i].Previous, observed[i - 1].Document))
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
var ordered = observed.OrderBy(change => change.Sequence).ToArray();
|
||||
Assert.That(ordered, Has.Length.EqualTo(16000));
|
||||
Assert.That(ordered.Select(change => change.Sequence).Distinct().Count(), Is.EqualTo(16000), "a Sequence repeated");
|
||||
var broken = Enumerable.Range(1, ordered.Length - 1)
|
||||
.FirstOrDefault(i => !ReferenceEquals(ordered[i].PreviousDocument, ordered[i - 1].Document));
|
||||
Assert.That(broken, Is.EqualTo(0), "a change's previous document is not the one installed by the next-lower Sequence");
|
||||
}
|
||||
|
||||
private string PathOf(string fileName) => System.IO.Path.Combine(_directory, fileName);
|
||||
|
|
|
|||
|
|
@ -1387,6 +1387,38 @@ public sealed class CultMeshStreamingTests
|
|||
observed.Current.Revision.Should().Be(2);
|
||||
}
|
||||
|
||||
// The older of two racing writes is parked in an earlier observer until the newer one has been applied.
|
||||
[Test]
|
||||
public async Task WatchRecordIgnoresStaleSequence()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var key = new CultRecordKey("mesh-note:stale-sequence");
|
||||
var handle = new CultRecordHandle<MeshNoteDocument>(key);
|
||||
MeshNoteDocument Note(string text, int revision) =>
|
||||
new() { Schema = "tests.mesh_note.v1", Text = text, Revision = revision };
|
||||
await cache.UpsertAsync(Note("initial", 1), handle);
|
||||
using var release = new System.Threading.ManualResetEventSlim();
|
||||
using var parked = new System.Threading.ManualResetEventSlim();
|
||||
using var park = cache.WatchRecord<MeshNoteDocument>(key).Subscribe(change =>
|
||||
{
|
||||
if (change.Document?.Revision != 2) return;
|
||||
parked.Set();
|
||||
release.Wait(TimeSpan.FromSeconds(30));
|
||||
});
|
||||
using var observed = await CultMesh.Document<MeshNoteDocument>(cache, key).ObserveAsync();
|
||||
|
||||
var older = Task.Run(() => cache.UpsertAsync(Note("older", 2), handle));
|
||||
parked.Wait(TimeSpan.FromSeconds(5)).Should().BeTrue();
|
||||
var newer = Task.Run(() => cache.UpsertAsync(Note("newer", 3), handle));
|
||||
var newerFinished = newer.Wait(TimeSpan.FromSeconds(10));
|
||||
release.Set();
|
||||
|
||||
newerFinished.Should().BeTrue("a writer waited on another thread's delivery");
|
||||
older.Wait(TimeSpan.FromSeconds(10)).Should().BeTrue();
|
||||
observed.Current.Text.Should().Be("newer");
|
||||
cache.Dispose();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReactiveDocument_DisposeSuppressesScheduledFlush()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1820,6 +1820,78 @@ namespace GameCult.Networking.Tests
|
|||
Assert.That(removed.Active, Is.False);
|
||||
}
|
||||
|
||||
// A load's delivery reaches a subscription observer that needs the lifecycle gate while a subscribe's demand
|
||||
// handler, holding that gate, writes the same cache. Nothing is disposed on failure: disposal would hang too.
|
||||
[Test]
|
||||
public async Task SubscriptionDemandHandlerWritingCacheDuringDeliveryDoesNotDeadlock()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"cultlib-demand-{Guid.NewGuid():N}.cc");
|
||||
using (var seed = new CultCache())
|
||||
{
|
||||
seed.AddBackingStore(new SingleFileMessagePackBackingStore(path));
|
||||
await seed.UpsertAsync(new NetworkSchemaNote { Schema = "tests.networking_note.v1", Text = "loaded" },
|
||||
new CultRecordHandle<NetworkSchemaNote>(new CultRecordKey("demand:loaded")));
|
||||
seed.FlushAllBackingStores();
|
||||
}
|
||||
|
||||
var cache = new CultCache();
|
||||
var delivering = new ManualResetEventSlim();
|
||||
cache.OnUpdate += (_, _) => delivering.Set();
|
||||
var database = new CultNetDatabase(cache);
|
||||
var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions
|
||||
{
|
||||
RuntimeId = "demand-write-server",
|
||||
Socket = BindUdpSocket()
|
||||
});
|
||||
var subscriptions = new CultNetDatabaseSubscriptionServer(server, database);
|
||||
var written = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
subscriptions.DemandChanged += demand =>
|
||||
{
|
||||
if (!demand.Active) return;
|
||||
_ = Task.Run(() => cache.AddBackingStore(new SingleFileMessagePackBackingStore(path)));
|
||||
if (!delivering.Wait(TimeSpan.FromSeconds(5)))
|
||||
{
|
||||
written.TrySetException(new TimeoutException("the load never started delivering"));
|
||||
return;
|
||||
}
|
||||
cache.UpsertAsync(new NetworkSchemaNote { Schema = "tests.networking_note.v1", Text = "demanded" },
|
||||
new CultRecordHandle<NetworkSchemaNote>(new CultRecordKey("demand:written"))).GetAwaiter().GetResult();
|
||||
written.TrySetResult(true);
|
||||
};
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var serverThread = new Thread(() =>
|
||||
{
|
||||
while (!cancellation.IsCancellationRequested)
|
||||
{
|
||||
_ = server.PollOnceAsync().GetAwaiter().GetResult();
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}) { IsBackground = true };
|
||||
serverThread.Start();
|
||||
|
||||
using var client = CultNetSchemaClients.CreateRudp("demand-write-client");
|
||||
client.Connect("127.0.0.1", server.LocalEndPoint.Port);
|
||||
await WaitUntilAsync(() => client.Connected, TimeSpan.FromSeconds(2));
|
||||
client.SendCultNet(new CultNetDatabaseSubscribeMessage
|
||||
{
|
||||
MessageId = "subscribe-demand-write",
|
||||
SubscriptionId = "demand-write",
|
||||
RecordKeys = ["demand:other"],
|
||||
IncludeSnapshot = false
|
||||
});
|
||||
|
||||
var finished = await Task.WhenAny(written.Task, Task.Delay(TimeSpan.FromSeconds(10))) == written.Task;
|
||||
cancellation.Cancel();
|
||||
Assert.That(finished, Is.True, "the demand handler's cache write deadlocked with the load's delivery");
|
||||
await written.Task;
|
||||
serverThread.Join();
|
||||
subscriptions.Dispose();
|
||||
server.Dispose();
|
||||
database.Dispose();
|
||||
cache.Dispose();
|
||||
File.Delete(path);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DatabaseSubscriptionServer_ClassifiesLoopbackTcpDemandAsSameMachine()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue