Soul probes: commit the pass-3 P-tests and the Cut 4 probes as recovered
SoulPub3Tests.cs is from 1ccc4927 (recovered pass-3 P-tests); SoulP4ProbeTests.cs is from 8ae8b3dc. Committed as Soul wrote them; the Finding-category probes fail on this commit and are the tests for the fixes that follow. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
13072fc5d7
commit
49582cf43e
2 changed files with 580 additions and 0 deletions
304
tests/GameCult.Networking.Tests/SoulP4ProbeTests.cs
Normal file
304
tests/GameCult.Networking.Tests/SoulP4ProbeTests.cs
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using NUnit.Framework;
|
||||
using R3;
|
||||
using static GameCult.Networking.Tests.NetworkingTests;
|
||||
|
||||
namespace GameCult.Networking.Tests
|
||||
{
|
||||
// Soul pass on Cut 4 (scratch; not for merge). Category Finding asserts the invariant Soul expects and is expected to
|
||||
// fail on 13072fc5; Pin asserts a promise that should hold; Measure reports numbers.
|
||||
public sealed class SoulP4ProbeTests
|
||||
{
|
||||
private const string ShardId = "soul-shard";
|
||||
private static readonly CultRecordKey One = new("soul:p4:one");
|
||||
private static readonly CultRecordKey Two = new("soul:p4:two");
|
||||
private static readonly CultRecordKey Three = new("soul:p4:three");
|
||||
|
||||
private static NetworkSchemaNote Note(string text) => new() { Schema = "tests.networking_note.v1", Text = text };
|
||||
private static string SchemaId(CultCache cache) => cache.Registry.GetRequired<NetworkSchemaNote>().SchemaId;
|
||||
|
||||
private static CultNetDatabase Db(CultCache cache, bool primary, ICultNetShardMutationLogStore? store) =>
|
||||
new(cache, new CultNetDatabaseOptions
|
||||
{
|
||||
Shards = [new CultNetShardDescriptor(ShardId, "primary", epoch: 1, isPrimary: primary, schemaIds: [SchemaId(cache)])],
|
||||
MutationLogStore = store
|
||||
});
|
||||
|
||||
private sealed class Store : ICultNetShardMutationLogStore
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly SortedDictionary<long, CultNetShardLogEntryMessage> _entries = new();
|
||||
private long _compacted;
|
||||
public Func<long, bool> RefuseAppend { get; set; } = _ => false;
|
||||
public bool RefuseCompact { get; set; }
|
||||
public int AppendDelayMs { get; set; }
|
||||
public ManualResetEventSlim InAppend { get; } = new();
|
||||
|
||||
public IReadOnlyList<CultNetShardLogEntryMessage> Read(string shardId, long afterSequence = 0, int? limit = null)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var e = _entries.Values.Where(x => x.Sequence > afterSequence);
|
||||
return (limit.HasValue ? e.Take(limit.Value) : e).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public void Append(string shardId, CultNetShardLogEntryMessage entry)
|
||||
{
|
||||
InAppend.Set();
|
||||
if (AppendDelayMs > 0) Thread.Sleep(AppendDelayMs);
|
||||
lock (_gate)
|
||||
{
|
||||
if (RefuseAppend(entry.Sequence)) throw new IOException($"refused {entry.Sequence}");
|
||||
_entries[entry.Sequence] = entry;
|
||||
}
|
||||
}
|
||||
|
||||
public long GetCompactedThrough(string shardId) { lock (_gate) return _compacted; }
|
||||
|
||||
public void CompactThrough(string shardId, long sequence)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (RefuseCompact) throw new IOException("refused compact");
|
||||
_compacted = Math.Max(_compacted, sequence);
|
||||
foreach (var k in _entries.Keys.Where(k => k <= sequence).ToArray()) _entries.Remove(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Peer : ICultNetShardLogFetcher, ICultNetShardSnapshotFetcher, IDisposable
|
||||
{
|
||||
private readonly Server _server;
|
||||
private readonly CultNetDatabaseServer _dbServer;
|
||||
private readonly CultNetDatabase _db;
|
||||
public Peer(CultCache cache, CultNetDatabase db)
|
||||
{
|
||||
_db = db;
|
||||
_server = new Server(cache, ServerSecurityOptions.Development());
|
||||
_dbServer = new CultNetDatabaseServer(_server, db);
|
||||
}
|
||||
public CultNetShardLogResponseMessage Log(long after) => _dbServer.CreateShardLogResponse(new CultNetShardLogRequestMessage
|
||||
{ MessageId = "pull", ShardId = ShardId, ShardEpoch = 1, AfterSequence = after });
|
||||
public Task<CultNetShardLogResponseMessage> FetchAsync(CultNetShardDescriptor shard, long afterSequence, int? limit = null) => Task.FromResult(Log(afterSequence));
|
||||
public Task<CultNetSnapshotResponseRawMessage> FetchAsync(CultNetShardDescriptor shard) => Task.FromResult(_db.CreateShardSnapshotResponse(_db.Shards[0], "snap"));
|
||||
public void Dispose() { _dbServer.Dispose(); _server.Dispose(); }
|
||||
}
|
||||
|
||||
private static int StashCount(CultNetDatabase db)
|
||||
{
|
||||
var field = typeof(CultNetDatabase).GetField("_stash", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
var stash = (System.Collections.ICollection)field.GetValue(db)!;
|
||||
lock (typeof(CultNetDatabase).GetField("_logGate", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(db)!)
|
||||
return stash.Count;
|
||||
}
|
||||
|
||||
// F1: the recorded residual is "tail reuse". A hole in the middle of the log after a double refusal and a restart
|
||||
// strands a replica behind it for good: the restarted primary has no floor, the store serves S+1 after S-1.
|
||||
[Test, Category("SoulFinding")]
|
||||
public async Task F1_MidLogHoleAfterDoubleRefusalAndRestartStrandsAReplica()
|
||||
{
|
||||
var store = new Store { RefuseAppend = s => s == 2, RefuseCompact = true };
|
||||
var cache = new CultCache();
|
||||
var primary = Db(cache, true, store);
|
||||
var replicaCache = new CultCache();
|
||||
var replica = Db(replicaCache, false, null);
|
||||
await primary.PutAsync(One, Note("one"));
|
||||
using (var p0 = new Peer(cache, primary))
|
||||
using (var r0 = new CultNetShardReplicator(replica, new CultNetShardReplicatorOptions { Fetcher = p0, SnapshotFetcher = p0 }))
|
||||
await r0.PullOnceAsync(ShardId);
|
||||
try { await primary.PutAsync(Two, Note("two")); } catch (CultNetShardLogException) { }
|
||||
store.RefuseCompact = false;
|
||||
await primary.PutAsync(Three, Note("three"));
|
||||
primary.Dispose();
|
||||
|
||||
var restarted = Db(cache, true, store);
|
||||
using var peer = new Peer(cache, restarted);
|
||||
using var replicator = new CultNetShardReplicator(replica, new CultNetShardReplicatorOptions { Fetcher = peer, SnapshotFetcher = peer });
|
||||
var errors = new List<string>();
|
||||
for (var attempt = 0; attempt < 3; attempt++)
|
||||
{
|
||||
try { await replicator.PullOnceAsync(ShardId); }
|
||||
catch (Exception e) { errors.Add(e.GetType().Name + ": " + e.Message); }
|
||||
}
|
||||
|
||||
TestContext.Out.WriteLine($"store={string.Join(",", store.Read(ShardId).Select(e => e.Sequence))} floor={restarted.GetCompactedMutationLogSequence(ShardId)} errors=[{string.Join(" | ", errors)}]");
|
||||
Assert.That(new[] { One, Two, Three }.Select(k => replicaCache.Get<NetworkSchemaNote>(k)?.Text), Is.EqualTo(new[] { "one", "two", "three" }));
|
||||
}
|
||||
|
||||
// F2: Q-P5 A says the writer gets a typed CultNetShardLogException. A commit of two changes on a refusing store
|
||||
// hands the writer an AggregateException; a writer's catch (CultNetShardLogException) misses it.
|
||||
[Test, Category("SoulFinding")]
|
||||
public void F2_ABatchOnARefusingStoreReachesTheWriterAsTheTypedException()
|
||||
{
|
||||
var store = new Store { RefuseAppend = _ => true };
|
||||
var cache = new CultCache();
|
||||
_ = Db(cache, true, store);
|
||||
Exception? caught = null;
|
||||
try
|
||||
{
|
||||
cache.Commit(batch =>
|
||||
{
|
||||
batch.Upsert(Note("one"), new CultRecordHandle<NetworkSchemaNote>(One));
|
||||
batch.Upsert(Note("two"), new CultRecordHandle<NetworkSchemaNote>(Two));
|
||||
});
|
||||
}
|
||||
catch (Exception e) { caught = e; }
|
||||
TestContext.Out.WriteLine($"writer caught {caught?.GetType().FullName}");
|
||||
Assert.That(caught, Is.InstanceOf<CultNetShardLogException>());
|
||||
}
|
||||
|
||||
// F3: main publishes PutPredictedAsync as Predicted and records the prediction whatever instance it is given. The
|
||||
// shape rule refuses a door whose instance is already the cached one, so a mutate-then-predict is published as
|
||||
// Updated, is logged on a primary, and its reconciliation is published as Updated.
|
||||
[Test, Category("SoulFinding")]
|
||||
public async Task F3_APredictionOfTheCachedInstanceIsPublishedAsAPrediction()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var db = new CultNetDatabase(cache, new CultNetDatabaseOptions
|
||||
{
|
||||
RuntimeId = "local",
|
||||
ClientAuthorityScopes = [new CultNetClientAuthorityScope("local")]
|
||||
});
|
||||
var shard = db.Shards[0];
|
||||
var kinds = new List<CultNetDatabaseChangeKind>();
|
||||
db.Watch<NetworkSchemaNote>().Subscribe(c => kinds.Add(c.Kind));
|
||||
await db.PutPredictedAsync(One, Note("p1"));
|
||||
var held = cache.Get<NetworkSchemaNote>(One)!;
|
||||
held.Text = "p2";
|
||||
await db.PutPredictedAsync(One, held);
|
||||
var auth = db.Documents.CreateRawDocumentPutMessage("a", new CultRecordHandle<NetworkSchemaNote>(One), Note("auth"));
|
||||
auth.ShardId = shard.ShardId;
|
||||
auth.ShardEpoch = shard.Epoch;
|
||||
await db.ApplyPutAsync(auth);
|
||||
TestContext.Out.WriteLine($"kinds=[{string.Join(",", kinds)}] log=[{string.Join(",", db.GetMutationLog(shard.ShardId).Select(e => e.Kind))}]");
|
||||
Assert.That(kinds, Is.EqualTo(new[] { CultNetDatabaseChangeKind.Predicted, CultNetDatabaseChangeKind.Predicted, CultNetDatabaseChangeKind.Reconciled }));
|
||||
Assert.That(db.GetMutationLog(shard.ShardId).Select(e => e.Kind), Is.EqualTo(new[] { CultNetDatabaseChangeKind.Updated }));
|
||||
}
|
||||
|
||||
// F4: the journal holds the cache gate across the log append, and cache reads take the gate, so a reader of an
|
||||
// unrelated key waits for the whole append.
|
||||
[Test, Category("SoulFinding")]
|
||||
public async Task F4_AReaderOfAnotherKeyDoesNotWaitForALogAppend()
|
||||
{
|
||||
var store = new Store { AppendDelayMs = 400 };
|
||||
var cache = new CultCache();
|
||||
await cache.UpsertAsync(Note("two"), new CultRecordHandle<NetworkSchemaNote>(Two));
|
||||
var db = Db(cache, true, store);
|
||||
var writer = Task.Run(() => cache.UpsertAsync(Note("one"), new CultRecordHandle<NetworkSchemaNote>(One)).GetAwaiter().GetResult());
|
||||
Assert.That(store.InAppend.Wait(5000), Is.True);
|
||||
var clock = Stopwatch.StartNew();
|
||||
_ = cache.Get<NetworkSchemaNote>(Two);
|
||||
var waited = clock.Elapsed.TotalMilliseconds;
|
||||
await writer;
|
||||
TestContext.Out.WriteLine($"reader of an unrelated key waited {waited:0.0} ms for a 400 ms append");
|
||||
Assert.That(waited, Is.LessThan(100));
|
||||
}
|
||||
|
||||
// P1: the constructor registers the observer before the journal, so a change stashed by the journal always finds
|
||||
// its publisher, even while another thread writes the cache during construction.
|
||||
[Test, Category("SoulPin")]
|
||||
public void P1_ConstructionUnderConcurrentWritesOrphansNoStash()
|
||||
{
|
||||
var orphans = 0;
|
||||
for (var round = 0; round < 200; round++)
|
||||
{
|
||||
var cache = new CultCache();
|
||||
using var stop = new CancellationTokenSource();
|
||||
var writer = Task.Run(() =>
|
||||
{
|
||||
var i = 0;
|
||||
while (!stop.IsCancellationRequested)
|
||||
cache.UpsertAsync(Note("w" + i++), new CultRecordHandle<NetworkSchemaNote>(new CultRecordKey("soul:p4:race:" + (i % 4)))).GetAwaiter().GetResult();
|
||||
});
|
||||
Thread.SpinWait(200 * (round % 7));
|
||||
var db = Db(cache, true, null);
|
||||
Thread.SpinWait(2000);
|
||||
stop.Cancel();
|
||||
writer.GetAwaiter().GetResult();
|
||||
orphans += StashCount(db);
|
||||
db.Dispose();
|
||||
}
|
||||
|
||||
Assert.That(orphans, Is.EqualTo(0), "no stash entry outlives its admission");
|
||||
}
|
||||
|
||||
// P2: every stash entry is removed by its publication.
|
||||
[Test, Category("SoulPin")]
|
||||
public async Task P2_TheStashDrainsAfterEveryWrite()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var db = Db(cache, true, new Store());
|
||||
await db.PutAsync(One, Note("one"));
|
||||
await cache.UpsertAsync(Note("two"), new CultRecordHandle<NetworkSchemaNote>(Two));
|
||||
cache.Commit(batch => batch.Upsert(Note("three"), new CultRecordHandle<NetworkSchemaNote>(Three)));
|
||||
await db.DeleteAsync<NetworkSchemaNote>(One);
|
||||
Assert.That(StashCount(db), Is.EqualTo(0));
|
||||
}
|
||||
|
||||
// P3: a replica never applies an entry past a hole. The primary burns 2 with compaction refused, then logs 3; a
|
||||
// replica at 1 is answered compacted_history and resyncs, never applying 3 on top of 1.
|
||||
[Test, Category("SoulPin")]
|
||||
public async Task P3_AReplicaAtTheHoleResyncsRatherThanSkippingIt()
|
||||
{
|
||||
var store = new Store { RefuseAppend = s => s == 2, RefuseCompact = true };
|
||||
var cache = new CultCache();
|
||||
var primary = Db(cache, true, store);
|
||||
using var peer = new Peer(cache, primary);
|
||||
var replicaCache = new CultCache();
|
||||
var replica = Db(replicaCache, false, null);
|
||||
using var replicator = new CultNetShardReplicator(replica, new CultNetShardReplicatorOptions { Fetcher = peer, SnapshotFetcher = peer });
|
||||
await primary.PutAsync(One, Note("one"));
|
||||
await replicator.PullOnceAsync(ShardId);
|
||||
try { await primary.PutAsync(Two, Note("two")); } catch (CultNetShardLogException) { }
|
||||
await primary.PutAsync(Three, Note("three"));
|
||||
Assert.That(peer.Log(1).Reason, Is.EqualTo("compacted_history"));
|
||||
var applied = await replicator.PullOnceAsync(ShardId);
|
||||
Assert.That(applied, Is.EqualTo(3));
|
||||
Assert.That(new[] { One, Two, Three }.Select(k => replicaCache.Get<NetworkSchemaNote>(k)?.Text), Is.EqualTo(new[] { "one", "two", "three" }));
|
||||
}
|
||||
|
||||
[Test, Category("SoulMeasure")]
|
||||
public async Task M1_BareWriteLatencyWithTheFileLogStore()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), "soulp4-log-" + Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
var cache = new CultCache();
|
||||
_ = Db(cache, true, new CultNetFileShardMutationLogStore(root));
|
||||
var times = new List<double>();
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
var clock = Stopwatch.StartNew();
|
||||
await cache.UpsertAsync(Note("n" + i), new CultRecordHandle<NetworkSchemaNote>(new CultRecordKey("soul:p4:lat:" + i)));
|
||||
times.Add(clock.Elapsed.TotalMilliseconds);
|
||||
}
|
||||
|
||||
TestContext.Out.WriteLine($"file store bare write ms: first100 avg {times.Take(100).Average():0.000}, 400-500 avg {times.Skip(400).Take(100).Average():0.000}, last100 avg {times.Skip(900).Average():0.000}, max {times.Max():0.0}");
|
||||
var bare = new CultCache();
|
||||
var t2 = new List<double>();
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
var clock = Stopwatch.StartNew();
|
||||
await bare.UpsertAsync(Note("n" + i), new CultRecordHandle<NetworkSchemaNote>(new CultRecordKey("soul:p4:lat:" + i)));
|
||||
t2.Add(clock.Elapsed.TotalMilliseconds);
|
||||
}
|
||||
|
||||
TestContext.Out.WriteLine($"no database bare write ms: last100 avg {t2.Skip(900).Average():0.000}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(root)) Directory.Delete(root, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
276
tests/GameCult.Networking.Tests/SoulPub3Tests.cs
Normal file
276
tests/GameCult.Networking.Tests/SoulPub3Tests.cs
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using NUnit.Framework;
|
||||
using R3;
|
||||
using static GameCult.Networking.Tests.NetworkingTests;
|
||||
|
||||
namespace GameCult.Networking.Tests
|
||||
{
|
||||
[CultDocument("tests.soul_throwing_name", "tests.soul_throwing_name.v1")]
|
||||
[MessagePack.MessagePackObject]
|
||||
public sealed class SoulThrowingName
|
||||
{
|
||||
[MessagePack.Key(0)]
|
||||
public string Text { get; set; } = string.Empty;
|
||||
|
||||
[MessagePack.Key(1)]
|
||||
[CultName]
|
||||
public string Name
|
||||
{
|
||||
get => Text == "boom" ? throw new InvalidOperationException("name getter boom") : Text;
|
||||
set { }
|
||||
}
|
||||
}
|
||||
|
||||
[NonParallelizable]
|
||||
public sealed class SoulPub3Tests
|
||||
{
|
||||
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(5);
|
||||
private static NetworkSchemaNote Note(string text) => new() { Schema = "tests.networking_note.v1", Text = text };
|
||||
private static string SchemaId => CultDocumentRegistry.Shared.GetRequired<NetworkSchemaNote>().SchemaId;
|
||||
|
||||
// Another thread becomes the drainer and parks inside a subscriber on the change "slow".
|
||||
private static (Task Writer, ManualResetEventSlim Release) BlockDrainer(CultNetDatabase database, CultCache cache, out IDisposable subscription)
|
||||
{
|
||||
var entered = new ManualResetEventSlim();
|
||||
var release = new ManualResetEventSlim();
|
||||
subscription = database.Watch<NetworkSchemaNote>().Subscribe(change =>
|
||||
{
|
||||
if (change.Document?.Text == "slow")
|
||||
{
|
||||
entered.Set();
|
||||
release.Wait(Wait);
|
||||
}
|
||||
});
|
||||
var writer = Task.Run(() => cache.UpsertAsync(Note("slow"), new CultRecordHandle<NetworkSchemaNote>(new CultRecordKey("soul3:slow"))).GetAwaiter().GetResult());
|
||||
Assert.That(entered.Wait(Wait), Is.True, "drainer parked");
|
||||
return (writer, release);
|
||||
}
|
||||
|
||||
// P1: a write that returns has been logged and published.
|
||||
[Test]
|
||||
public async Task P1_AWriteThatReturnedIsLoggedAndPublished()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var database = new CultNetDatabase(cache);
|
||||
var seen = new ConcurrentQueue<(string? Text, int Thread)>();
|
||||
using var watch = database.Watch<NetworkSchemaNote>().Subscribe(change => seen.Enqueue((change.Document?.Text, Environment.CurrentManagedThreadId)));
|
||||
var (writer, release) = BlockDrainer(database, cache, out var block);
|
||||
var fast = new CultRecordKey("soul3:fast");
|
||||
var writerThread = 0;
|
||||
await Task.Run(async () => { writerThread = Environment.CurrentManagedThreadId; await database.PutAsync(fast, Note("fast")); });
|
||||
|
||||
var logged = database.LastWriteSequence(SchemaId, fast);
|
||||
var published = seen.Any(entry => entry.Text == "fast");
|
||||
release.Set();
|
||||
await writer;
|
||||
block.Dispose();
|
||||
var deliveredOn = seen.First(entry => entry.Text == "fast").Thread;
|
||||
TestContext.Progress.WriteLine($"SOUL P1 logged-at-return={logged} published-at-return={published} writer={writerThread} deliveredOn={deliveredOn}");
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(logged, Is.Not.Null, "PutAsync returned before its change was logged");
|
||||
Assert.That(published, Is.True, "PutAsync returned before its change was published");
|
||||
});
|
||||
}
|
||||
|
||||
// P2: a subscriber that waits (bounded) for another thread's write to be observed.
|
||||
[Test]
|
||||
public async Task P2_ASubscriberWaitingForAnotherThreadsWriteIsNotStarved()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var database = new CultNetDatabase(cache);
|
||||
var other = new ManualResetEventSlim();
|
||||
var observedInTime = false;
|
||||
using var watch = database.Watch<NetworkSchemaNote>().Subscribe(change =>
|
||||
{
|
||||
if (change.Document?.Text == "other")
|
||||
other.Set();
|
||||
if (change.Document?.Text == "trigger")
|
||||
{
|
||||
Task.Run(() => database.PutAsync(new CultRecordKey("soul3:other"), Note("other")));
|
||||
observedInTime = other.Wait(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
});
|
||||
await database.PutAsync(new CultRecordKey("soul3:trigger"), Note("trigger"));
|
||||
Assert.That(observedInTime, Is.True, "another thread's committed write never reached subscribers while this handler ran");
|
||||
}
|
||||
|
||||
// P3: one observer's escaped exception (fail-fast R3 handler) loses one change; it must not stall all later ones.
|
||||
[Test]
|
||||
public async Task P3_AnEscapedObserverExceptionDoesNotStallLaterChanges()
|
||||
{
|
||||
var previous = ObservableSystem.GetUnhandledExceptionHandler();
|
||||
ObservableSystem.RegisterUnhandledExceptionHandler(exception => throw exception);
|
||||
try
|
||||
{
|
||||
var cache = new CultCache();
|
||||
using var thrower = cache.Watch<NetworkSchemaNote>().Subscribe(change =>
|
||||
{
|
||||
if (change.Document?.Text == "boom") throw new InvalidOperationException("observer boom");
|
||||
});
|
||||
var database = new CultNetDatabase(cache);
|
||||
var seen = new ConcurrentQueue<string?>();
|
||||
using var watch = database.Watch<NetworkSchemaNote>().Subscribe(change => seen.Enqueue(change.Document?.Text));
|
||||
try { await cache.UpsertAsync(Note("boom"), new CultRecordHandle<NetworkSchemaNote>(new CultRecordKey("soul3:boom"))); }
|
||||
catch (InvalidOperationException) { }
|
||||
|
||||
ObservableSystem.RegisterUnhandledExceptionHandler(previous);
|
||||
var after = new CultRecordKey("soul3:after");
|
||||
await database.PutAsync(after, Note("after"));
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(seen, Does.Contain("after"), "a later commit was never published");
|
||||
Assert.That(database.LastWriteSequence(SchemaId, after), Is.Not.Null, "a later commit was never logged");
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
ObservableSystem.RegisterUnhandledExceptionHandler(previous);
|
||||
}
|
||||
}
|
||||
|
||||
// P4: an admission that throws inside Apply after minting a Sequence (a [CultName] getter) must not stall later changes.
|
||||
[Test]
|
||||
public async Task P4_AThrowMidApplyDoesNotStallLaterChanges()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var database = new CultNetDatabase(cache);
|
||||
var seen = new ConcurrentQueue<string?>();
|
||||
using var watch = database.Watch<NetworkSchemaNote>().Subscribe(change => seen.Enqueue(change.Document?.Text));
|
||||
try
|
||||
{
|
||||
cache.Commit(batch =>
|
||||
{
|
||||
batch.Upsert(new SoulThrowingName { Text = "ok" }, new CultRecordHandle<SoulThrowingName>(new CultRecordKey("soul3:ok")));
|
||||
batch.Upsert(new SoulThrowingName { Text = "boom" }, new CultRecordHandle<SoulThrowingName>(new CultRecordKey("soul3:boomname")));
|
||||
});
|
||||
}
|
||||
catch (InvalidOperationException) { }
|
||||
|
||||
var after = new CultRecordKey("soul3:after-apply");
|
||||
await database.PutAsync(after, Note("after"));
|
||||
TestContext.Progress.WriteLine($"SOUL P4 ok-in-cache={cache.Get(new CultRecordKey("soul3:ok")) != null}");
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(seen, Does.Contain("after"), "a later commit was never published");
|
||||
Assert.That(database.LastWriteSequence(SchemaId, after), Is.Not.Null, "a later commit was never logged");
|
||||
});
|
||||
}
|
||||
|
||||
// P5: writers no longer carry their own delivery; the backlog behind one drainer grows without bound.
|
||||
[Test]
|
||||
public async Task P5_OtherWritersDoNotPileAnUnboundedBacklogOnOneDrainer()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var database = new CultNetDatabase(cache);
|
||||
var delivered = 0;
|
||||
var backlogAtBDone = -1;
|
||||
const int bWrites = 2000;
|
||||
using var watch = database.Watch<NetworkSchemaNote>().Subscribe(change =>
|
||||
{
|
||||
if (change.Document?.Text?.StartsWith("b") == true) Interlocked.Increment(ref delivered);
|
||||
if (change.Document?.Text == "a")
|
||||
{
|
||||
Task.Run(async () =>
|
||||
{
|
||||
for (var i = 0; i < bWrites; i++)
|
||||
await database.PutAsync(new CultRecordKey($"soul3:b:{i}"), Note($"b{i}"));
|
||||
}).Wait(Wait);
|
||||
backlogAtBDone = bWrites - Volatile.Read(ref delivered);
|
||||
}
|
||||
});
|
||||
await database.PutAsync(new CultRecordKey("soul3:a"), Note("a"));
|
||||
TestContext.Progress.WriteLine($"SOUL P5 undelivered after B's {bWrites} writes returned: {backlogAtBDone}");
|
||||
Assert.That(backlogAtBDone, Is.EqualTo(0));
|
||||
}
|
||||
|
||||
// P6: a prediction still queued when the authoritative put arrives.
|
||||
[Test]
|
||||
public async Task P6_AnAuthoritativePutArrivingBeforeItsPredictionIsDeliveredStillReconciles()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var database = new CultNetDatabase(cache, new CultNetDatabaseOptions
|
||||
{
|
||||
RuntimeId = "local",
|
||||
ClientAuthorityScopes = [new CultNetClientAuthorityScope("local")]
|
||||
});
|
||||
var key = new CultRecordKey("soul3:predict");
|
||||
var kinds = new ConcurrentQueue<CultNetDatabaseChangeKind>();
|
||||
using var watch = database.WatchRecord<NetworkSchemaNote>(key).Subscribe(change => kinds.Enqueue(change.Kind));
|
||||
CultNetDocumentPutRawMessage Put(string text)
|
||||
{
|
||||
var message = database.Documents.CreateRawDocumentPutMessage(text, new CultRecordHandle<NetworkSchemaNote>(key), Note(text));
|
||||
message.ShardId = database.Shards[0].ShardId;
|
||||
message.ShardEpoch = database.Shards[0].Epoch;
|
||||
return message;
|
||||
}
|
||||
|
||||
var (writer, release) = BlockDrainer(database, cache, out var block);
|
||||
await database.PutPredictedAsync(key, Note("predicted"));
|
||||
await database.ApplyPutAsync(Put("auth1"));
|
||||
release.Set();
|
||||
await writer;
|
||||
block.Dispose();
|
||||
await database.ApplyPutAsync(Put("auth2"));
|
||||
|
||||
Assert.That(kinds, Is.EqualTo(new[]
|
||||
{
|
||||
CultNetDatabaseChangeKind.Predicted,
|
||||
CultNetDatabaseChangeKind.Reconciled,
|
||||
CultNetDatabaseChangeKind.Updated
|
||||
}));
|
||||
}
|
||||
|
||||
// P7: a replica's absent-key delete is logged ahead of an earlier entry still queued; a bounded pull then sees a gap.
|
||||
[Test]
|
||||
public async Task P7_AReplicaLogStaysInSequenceOrderWhenAnAbsentDeleteOvertakesAQueuedPut()
|
||||
{
|
||||
const string shardId = "chain3";
|
||||
CultNetDatabase Make(CultCache cache, bool primary) => new(cache, new CultNetDatabaseOptions
|
||||
{
|
||||
Shards = [new CultNetShardDescriptor(shardId, "p", epoch: 2, isPrimary: primary, schemaIds: [SchemaId])]
|
||||
});
|
||||
var p = Make(new CultCache(), true);
|
||||
var rCache = new CultCache();
|
||||
var r = Make(rCache, false);
|
||||
var c = Make(new CultCache(), false);
|
||||
async Task Pull(CultNetDatabase from, CultNetDatabase to, int? limit = null)
|
||||
{
|
||||
await to.ApplyShardLogResponseAsync(new CultNetShardLogResponseMessage
|
||||
{
|
||||
ShardId = shardId,
|
||||
ShardEpoch = 2,
|
||||
Entries = from.GetMutationLogMessages(shardId, to.GetAppliedShardSequence(shardId), limit).ToArray()
|
||||
});
|
||||
}
|
||||
|
||||
var z = new CultRecordKey("soul3:z");
|
||||
await p.PutAsync(z, Note("z"));
|
||||
await Pull(p, r);
|
||||
await Pull(r, c);
|
||||
rCache.Remove(z);
|
||||
await p.PutAsync(new CultRecordKey("soul3:a"), Note("a"));
|
||||
await p.DeleteAsync<NetworkSchemaNote>(z);
|
||||
|
||||
var (writer, release) = BlockDrainer(r, rCache, out var block);
|
||||
await Pull(p, r);
|
||||
release.Set();
|
||||
await writer;
|
||||
block.Dispose();
|
||||
|
||||
TestContext.Progress.WriteLine($"SOUL P7 r log order: {string.Join(",", r.GetMutationLog(shardId).Select(e => e.Sequence))}");
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(r.GetMutationLog(shardId).Select(entry => entry.Sequence), Is.EqualTo(new[] { 1L, 2L, 3L }));
|
||||
Assert.DoesNotThrowAsync(() => Pull(r, c, limit: 1), "a bounded pull from R");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue