diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index ff2314ce..6ee87c81 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -1505,9 +1505,8 @@ namespace GameCult.Caching batch.Sealed = true; } - if (!Monitor.TryEnter(_gate, wait ? Timeout.Infinite : 0)) - return CultCommitOutcome.Contended; - try + // The in-process gate is always entered; only the store lock attempt honors wait, so Contended means another writer holds the store. + lock (_gate) { var upserts = batch.Operations.Values.Where(op => op.Stored != null).Select(op => op.Stored!).ToArray(); var deletes = batch.Operations.Values @@ -1532,10 +1531,6 @@ namespace GameCult.Caching return request.ConditionsHold(inMemory, _entries.Values) ? CultCommitOutcome.Committed : CultCommitOutcome.Mismatch; }); } - finally - { - Monitor.Exit(_gate); - } } // Every add and remove passes here: single writes, committed batches, and loads (source set). @@ -1590,6 +1585,15 @@ namespace GameCult.Caching throw new InvalidOperationException( $"{descriptor.SchemaName} record {stored.Key.Value} was loaded from {source} but its home is {home?.ToString() ?? "no store"}."); + // One key, one store: a key never moves between homes, and two stores never both deliver it. + if (_entries.TryGetValue(stored.Key.Value, out var present) && + Home(present.Descriptor.DocumentType) is var held && + Home(descriptor.DocumentType) is var incoming && + held != incoming) + throw new InvalidOperationException( + $"Record {stored.Key.Value} is held by {held?.ToString() ?? "memory"}; " + + $"{(source == null ? "writing" : "loading")} it as {descriptor.SchemaName} from {incoming?.ToString() ?? "memory"} would give the key a second store."); + if (!descriptor.IsGlobal) continue; if (globals.TryGetValue(descriptor.DocumentType, out var existing) && existing != stored.Key.Value) diff --git a/tests/GameCult.Caching.Tests/ConditionalCommitTests.cs b/tests/GameCult.Caching.Tests/ConditionalCommitTests.cs index 49e6dc5b..c7c42b66 100644 --- a/tests/GameCult.Caching.Tests/ConditionalCommitTests.cs +++ b/tests/GameCult.Caching.Tests/ConditionalCommitTests.cs @@ -72,18 +72,22 @@ namespace GameCult.Caching.Tests var racers = new[] { a, b }.Select(cache => Task.Run(() => { var wins = 0; + var mismatches = 0; for (var attempt = 0; wins < n && attempt < 50 * n; attempt++) { cache.PullAllBackingStoresAsync(); if (Increment(cache)) wins++; + else + mismatches++; } - return wins; + return (Wins: wins, Mismatches: mismatches); })).ToArray(); - Task.WaitAll(racers, TimeSpan.FromMinutes(2)); + Assert.That(Task.WaitAll(racers, TimeSpan.FromMinutes(2)), Is.True, "the racers did not finish"); - Assert.That(racers.Select(racer => racer.Result), Is.All.EqualTo(n)); + Assert.That(racers.Select(racer => racer.Result.Wins), Is.All.EqualTo(n)); + Assert.That(racers.Sum(racer => racer.Result.Mismatches), Is.GreaterThan(0), "the writers never actually raced"); using var reader = store.Open(); Assert.That(reader.Get(Key)!.Value, Is.EqualTo(2 + 2 * n)); } @@ -113,6 +117,86 @@ namespace GameCult.Caching.Tests Assert.That(cache.Get(new CultRecordKey("y")), Is.Not.Null); } + [Test] + public void TryCommitIsNotContendedByAConcurrentReader() + { + var path = PathOf("reader.cc"); + var store = SingleFile(path); + Create(store, 0); + using var cache = store.Open(); + var handle = new CultRecordHandle(new CultRecordKey("read-under")); + var running = true; + var reads = 0; + using var started = new ManualResetEventSlim(); + var reading = Task.Run(() => + { + started.Set(); + while (Volatile.Read(ref running)) + { + _ = cache.AllStoredDocuments.Count(); + Interlocked.Increment(ref reads); + } + }); + + try + { + Assert.That(started.Wait(TimeSpan.FromSeconds(10)), Is.True); + for (var i = 0; i < 200; i++) + Assert.That(cache.TryCommit(batch => batch.Upsert(new Counter { Name = "read-under", Value = i }, handle)), + Is.EqualTo(CultCommitOutcome.Committed), $"attempt {i} lost to a reader, not a writer"); + } + finally + { + Volatile.Write(ref running, false); + Assert.That(reading.Wait(TimeSpan.FromSeconds(10)), Is.True); + } + + Assert.That(reads, Is.GreaterThan(0)); + using (new FileStream(path + ".lock", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) + Assert.That(cache.TryCommit(batch => batch.Upsert(new Counter { Name = "read-under" }, handle)), + Is.EqualTo(CultCommitOutcome.Contended)); + } + + [Test] + public void PushAllWaitsForHeldStoreLock() + { + var path = PathOf("push-wait.cc"); + using var cache = SingleFile(path).Open(); + cache.UpsertAsync(new Counter { Name = "pushed" }, new CultRecordHandle(Key)); + Task flush; + + using (new FileStream(path + ".lock", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) + { + flush = Task.Run(() => cache.FlushAllBackingStores()); + Assert.That(flush.Wait(150), Is.False, "PushAll did not wait for the held store lock"); + Assert.That(File.Exists(path), Is.False); + } + + Assert.That(flush.Wait(TimeSpan.FromSeconds(10)), Is.True); + using var reader = SingleFile(path).Open(); + Assert.That(reader.Get(Key), Is.Not.Null); + } + + [Test] + public void CommitWaitsForHeldStoreLock() + { + var path = PathOf("commit-wait.cc"); + using var cache = SingleFile(path).Open(); + Task commit; + + using (new FileStream(path + ".lock", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) + { + commit = Task.Run(() => CreateCommit(cache, 7)); + Assert.That(commit.Wait(150), Is.False, "Commit did not wait for the held store lock"); + Assert.That(File.Exists(path), Is.False); + } + + Assert.That(commit.Wait(TimeSpan.FromSeconds(10)), Is.True); + Assert.That(commit.Result, Is.True); + using var reader = SingleFile(path).Open(); + Assert.That(reader.Get(Key)!.Value, Is.EqualTo(7)); + } + [Test] public void PlainFlushNeverInterleaves() { @@ -167,7 +251,7 @@ namespace GameCult.Caching.Tests } }); - Task.WaitAll(new[] { flushing, committing }, TimeSpan.FromMinutes(2)); + Assert.That(Task.WaitAll(new[] { flushing, committing }, TimeSpan.FromMinutes(2)), Is.True, "the writers did not finish"); Volatile.Write(ref running, false); Assert.That(() => reading.Wait(TimeSpan.FromSeconds(10)), Throws.Nothing); Assert.That(reads, Is.GreaterThan(0)); diff --git a/tests/GameCult.Caching.Tests/DirectoryStoreDurabilityTests.cs b/tests/GameCult.Caching.Tests/DirectoryStoreDurabilityTests.cs index 69eb7142..473717cc 100644 --- a/tests/GameCult.Caching.Tests/DirectoryStoreDurabilityTests.cs +++ b/tests/GameCult.Caching.Tests/DirectoryStoreDurabilityTests.cs @@ -2,6 +2,7 @@ using System; using System.IO; using System.Linq; +using System.Security.Cryptography; using System.Threading.Tasks; using GameCult.Caching; using GameCult.Caching.MessagePack; @@ -78,6 +79,36 @@ namespace GameCult.Caching.Tests Assert.That(reader.Get(key)?.Text, Is.EqualTo("second")); } + [Test] + public void FlushWritesPagesBeforeManifest() + { + using var cache = Open(out var store); + var key = new CultRecordKey("page"); + var descriptor = Registry.GetRequired(); + store.Push(new CultStoredDocument(key, FixedStoredAt, descriptor, new Page { Name = "p", Text = "first" })); + store.PushAll(); + var before = File.ReadAllBytes(_manifest); + + const string nextStoredAt = "2026-09-13T00:00:01.0000000+00:00"; + var next = new Page { Name = "p", Text = "second" }; + var page = CultDocumentMessagePackSerialization.SerializePersistedRecord(new CultPersistedRecord + { + Key = key.Value, + SchemaId = descriptor.SchemaId, + StoredAt = nextStoredAt, + Payload = CultDocumentMessagePackSerialization.SerializeUntyped(next, typeof(Page), Registry) + }); + using (var sha = SHA256.Create()) + Directory.CreateDirectory(PagePath(sha.ComputeHash(page))); + + store.Push(new CultStoredDocument(key, nextStoredAt, descriptor, next)); + Assert.That(() => store.PushAll(), Throws.InstanceOf().Or.InstanceOf()); + + Assert.That(File.ReadAllBytes(_manifest), Is.EqualTo(before), "the manifest was written although its page was not"); + using var reader = Open(out _); + Assert.That(reader.Get(key)?.Text, Is.EqualTo("first")); + } + [Test] public void PullAllWaitsForHeldCommitLease() { diff --git a/tests/GameCult.Caching.Tests/StoreRoutingTests.cs b/tests/GameCult.Caching.Tests/StoreRoutingTests.cs index 62ac176d..03afd38f 100644 --- a/tests/GameCult.Caching.Tests/StoreRoutingTests.cs +++ b/tests/GameCult.Caching.Tests/StoreRoutingTests.cs @@ -258,6 +258,61 @@ namespace GameCult.Caching.Tests Assert.That(cache.BackingStores, Has.Count.EqualTo(1)); } + [Test] + public async Task KeyCannotMoveToAnotherStoreOnWrite() + { + var registry = Registry(); + var catalogPath = PathOf("catalog.cc"); + var runPath = PathOf("run.cc"); + var key = new CultRecordKey("shared-key"); + using var cache = new CultCache(registry); + var run = new SingleFileMessagePackBackingStore(runPath); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalogPath), typeof(RoutingNote)); + cache.AddBackingStore(run, typeof(RoutingOther)); + await cache.UpsertAsync(typeof(RoutingNote), new RoutingNote { Name = "n", Text = "catalog" }, key); + await cache.FlushAsync(); + var before = File.ReadAllBytes(catalogPath); + + var single = Assert.Throws(() => + cache.UpsertAsync(typeof(RoutingOther), new RoutingOther { Name = "o", Text = "run" }, key)); + var batched = Assert.Throws(() => + cache.Commit(batch => batch.Upsert(typeof(RoutingOther), new RoutingOther { Name = "o", Text = "run" }, key))); + await cache.FlushAsync(); + + Assert.That(single!.Message, Does.Contain(key.Value).And.Contain(catalogPath).And.Contain(runPath)); + Assert.That(batched!.Message, Is.EqualTo(single.Message)); + Assert.That(run.IsDirty, Is.False); + Assert.That(File.Exists(runPath), Is.False); + Assert.That(File.ReadAllBytes(catalogPath), Is.EqualTo(before)); + Assert.That(cache.Get(key)?.Text, Is.EqualTo("catalog")); + } + + [Test] + public void KeyLoadedFromTwoStoresIsRefused() + { + var registry = Registry(); + var catalogPath = PathOf("catalog.cc"); + var runPath = PathOf("run.cc"); + var key = new CultRecordKey("shared-key"); + WriteRecords(catalogPath, registry, (key.Value, FixedStoredAt, new RoutingNote { Name = "n", Text = "catalog" })); + WriteRecords(runPath, registry, (key.Value, FixedStoredAt, new RoutingOther { Name = "o", Text = "run" })); + var runBefore = File.ReadAllBytes(runPath); + using var cache = new CultCache(registry); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalogPath), typeof(RoutingNote)); + var changes = 0; + using var subscription = cache.Watch().Subscribe(_ => changes++); + + var refusal = Assert.Throws(() => + cache.AddBackingStore(new SingleFileMessagePackBackingStore(runPath), typeof(RoutingOther))); + + Assert.That(refusal!.Message, Does.Contain(key.Value).And.Contain(catalogPath).And.Contain(runPath)); + Assert.That(cache.BackingStores, Has.Count.EqualTo(1)); + Assert.That(cache.AllEntries.Count(), Is.EqualTo(1)); + Assert.That(cache.Get(key)?.Text, Is.EqualTo("catalog")); + Assert.That(changes, Is.Zero); + Assert.That(File.ReadAllBytes(runPath), Is.EqualTo(runBefore)); + } + [Test] public async Task LateRouteOverAdmittedTypeThrows() {