From b653f68f811c134a1e4626baad25fcc61c76ec86 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 13 Sep 2026 20:01:36 +0200 Subject: [PATCH] Route every admitting gate entry through a hold FlushAllBackingStores and Dispose take the gate through Held, so a store method that loads can never reach Admit under a plain lock; Admit outside a hold throws a clear InvalidOperationException. Entering a cache's hold inside another cache's hold throws. PullAllBackingStoresAsync pulls every store even when an OnUpdate handler throws, then rethrows. The dead Try around Subject.OnNext is gone: R3 never throws there, so only OnUpdate exceptions reach the caller. Repull tests wait for the writer to start before their bounded wait. Co-Authored-By: Claude Opus 5 --- .../Contracts/cultcache-store-composition.md | 18 ++++-- src/GameCult.Caching/CultCache.cs | 63 +++++++++++++------ .../ConditionalCommitTests.cs | 16 ++++- .../StoreRoutingTests.cs | 55 ++++++++++++++++ 4 files changed, 124 insertions(+), 28 deletions(-) diff --git a/src/GameCult.Caching/Contracts/cultcache-store-composition.md b/src/GameCult.Caching/Contracts/cultcache-store-composition.md index fc2e96f8..5287455e 100644 --- a/src/GameCult.Caching/Contracts/cultcache-store-composition.md +++ b/src/GameCult.Caching/Contracts/cultcache-store-composition.md @@ -49,11 +49,14 @@ which route wrote it. published after the cache releases its gate and before the call that made it returns, on that caller's thread; no call publishes another call's changes. A direct `PullAll` on an attached store is such a call. -- An observer exception is rethrown to that caller after all of that call's - changes are delivered (an `AggregateException` if several threw). If the call - itself failed, its own exception is rethrown and observer exceptions are - dropped. A throwing observer cannot undo the store's adoption of a load; the - store and cache already agree when publication starts. +- An `OnUpdate` handler exception is rethrown to that caller after all of that + call's changes are delivered (an `AggregateException` if several threw). If + the call itself failed, its own exception is rethrown and handler exceptions + are dropped. A `Watch` subscriber exception is not rethrown; it follows R3's + unhandled-exception handling. A throwing handler cannot undo the store's + adoption of a load; the store and cache already agree when publication starts. +- Pulling all stores pulls every attached store even if a handler throws during + one store's load, then rethrows. - Hydration failure on open is loud: a corrupt store file, or a record whose schema the registry cannot resolve, makes the open throw and leaves the file byte-identical. Consumers never delete and rewrite a store they failed to @@ -63,7 +66,10 @@ which route wrote it. - One lock order: the cache's gate, then the store's lock. A store attached to a cache takes that cache's gate as its own lock, so a store's load callback into - the cache cannot take the two out of order. + the cache cannot take the two out of order. A store must not call `Loaded` + while holding its own lock outside the cache's hold. +- A thread holds one cache's gate at a time: entering a cache's hold inside + another cache's hold throws. - A store doing I/O on behalf of its cache (pull, flush, commit) holds the gate, so that cache's readers wait for the I/O. The file lock (`.lock` or the directory commit lease) is always taken inside the gate and released before a diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index c35109c5..b3f01f6c 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -1306,22 +1306,36 @@ namespace GameCult.Caching public Task PullAllBackingStoresAsync() { // Our stores take the gate themselves; a third-party store might not, so the cache takes it here. + // One store's throwing OnUpdate handler does not stop the others from loading. + var failures = new List(); foreach (var store in BackingStores) - Held(() => { store.PullAll(); return true; }); + { + try + { + Held(() => { store.PullAll(); return true; }); + } + catch (Exception exception) + { + failures.Add(exception); + } + } + + if (failures.Count == 1) + ExceptionDispatchInfo.Capture(failures[0]).Throw(); + if (failures.Count > 1) + throw new AggregateException(failures); return Task.CompletedTask; } - public void FlushAllBackingStores() + public void FlushAllBackingStores() => Held(() => { - lock (_gate) + foreach (var (store, _) in _stores) { - foreach (var (store, _) in _stores) - { - if (!store.IsReadOnly && store.IsDirty) - store.PushAll(); - } + if (!store.IsReadOnly && store.IsDirty) + store.PushAll(); } - } + return true; + }); // soft is dead. CultCacheStudioWindow reflects on FlushAsync(bool) until Cut 6 rewrites it. public Task FlushAsync(bool soft = false) @@ -1428,11 +1442,12 @@ namespace GameCult.Caching public void Dispose() { - lock (_gate) + Held(() => { if (FlushAttachedStoresOnDispose && IsDirty) FlushAllBackingStores(); - } + return true; + }); foreach (var store in BackingStores) store.Dispose(); @@ -1553,6 +1568,8 @@ namespace GameCult.Caching CacheBackingStore? source, Func land) => Held(() => { + if (_held == null) + throw new InvalidOperationException("An admission reached the cache under a plain lock on its gate; every admission runs in a hold."); var outcome = land(Validate(admitted, evicted, source)); if (outcome != CultCommitOutcome.Committed) return outcome; @@ -1569,6 +1586,9 @@ namespace GameCult.Caching { if (Monitor.IsEntered(_gate)) return body(); + if (_held != null) + throw new InvalidOperationException( + "A cache hold was entered inside another cache's hold; a thread holds one cache's gate at a time."); var outer = _held; var mine = _held = new List<(CultCache Cache, Change Change, bool Loaded)>(); T result; @@ -1596,17 +1616,20 @@ namespace GameCult.Caching private static List Deliver(List<(CultCache Cache, Change Change, bool Loaded)> changes) { var failures = new List(); - void Try(Action observe) - { - try { observe(); } - catch (Exception exception) { failures.Add(exception); } - } - foreach (var (cache, change, loaded) in changes) { - Try(() => cache._changes.OnNext(change)); - if (loaded) - Try(() => cache.OnUpdate?.Invoke(change.Previous, change.Document)); + // R3 routes a throwing subscriber to its unhandled-exception handler; OnNext does not throw. + cache._changes.OnNext(change); + if (!loaded) + continue; + try + { + cache.OnUpdate?.Invoke(change.Previous, change.Document); + } + catch (Exception exception) + { + failures.Add(exception); + } } return failures; diff --git a/tests/GameCult.Caching.Tests/ConditionalCommitTests.cs b/tests/GameCult.Caching.Tests/ConditionalCommitTests.cs index 54e3fd58..373f9df0 100644 --- a/tests/GameCult.Caching.Tests/ConditionalCommitTests.cs +++ b/tests/GameCult.Caching.Tests/ConditionalCommitTests.cs @@ -353,7 +353,13 @@ namespace GameCult.Caching.Tests { var pulling = Task.Run(() => cache.PullAllBackingStoresAsync()); Assert.That(store.Entered.Wait(TimeSpan.FromSeconds(10)), Is.True, "the pull never read the file"); - var writing = Task.Run(() => cache.UpsertAsync(new Counter { Name = "staged" }, new CultRecordHandle(staged))); + using var started = new ManualResetEventSlim(); + var writing = Task.Run(() => + { + started.Set(); + return cache.UpsertAsync(new Counter { Name = "staged" }, new CultRecordHandle(staged)); + }); + Assert.That(started.Wait(TimeSpan.FromSeconds(10)), Is.True, "the writer never started"); writing.Wait(200); Assert.That(store.PushedWhilePaused, Is.False, "a write reached the store while the pull held the gate"); store.Pause = null; @@ -393,7 +399,13 @@ namespace GameCult.Caching.Tests var pulling = Task.Run(() => cache.PullAllBackingStoresAsync()); Assert.That(Slow.Entered.Wait(TimeSpan.FromSeconds(10)), Is.True, "the pull never loaded a page"); // Admitting the write indexes its name under the gate, so a write that gets past the gate reads it while paused. - var writing = Task.Run(() => cache.UpsertAsync(new Slow { Name = "staged" }, new CultRecordHandle(staged))); + using var started = new ManualResetEventSlim(); + var writing = Task.Run(() => + { + started.Set(); + return cache.UpsertAsync(new Slow { Name = "staged" }, new CultRecordHandle(staged)); + }); + Assert.That(started.Wait(TimeSpan.FromSeconds(10)), Is.True, "the writer never started"); writing.Wait(200); Assert.That(Slow.ReadWhilePaused, Is.False, "a write was admitted while the pull held the gate"); Slow.Pause = null; diff --git a/tests/GameCult.Caching.Tests/StoreRoutingTests.cs b/tests/GameCult.Caching.Tests/StoreRoutingTests.cs index 03afd38f..205a0c99 100644 --- a/tests/GameCult.Caching.Tests/StoreRoutingTests.cs +++ b/tests/GameCult.Caching.Tests/StoreRoutingTests.cs @@ -576,6 +576,45 @@ namespace GameCult.Caching.Tests Assert.That(second.BackingStores, Is.Empty); } + [Test] + public void PullAllPullsEveryStoreWhenAHandlerThrows() + { + var registry = Registry(); + var notes = PathOf("notes.cc"); + var others = PathOf("others.cc"); + const string before = "2026-01-01T00:00:00.0000000+00:00"; + const string after = "2026-01-02T00:00:00.0000000+00:00"; + WriteRecords(notes, registry, ("note", before, new RoutingNote { Name = "note", Text = "old" })); + WriteRecords(others, registry, ("other", before, new RoutingOther { Name = "other", Text = "old" })); + using var cache = new CultCache(registry); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(notes), typeof(RoutingNote)); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(others), typeof(RoutingOther)); + + WriteRecords(notes, registry, ("note", after, new RoutingNote { Name = "note", Text = "new" })); + WriteRecords(others, registry, ("other", after, new RoutingOther { Name = "other", Text = "new" })); + cache.OnUpdate += (_, document) => + { + if (document is RoutingNote) + throw new InvalidOperationException("handler refuses notes"); + }; + + Assert.That(() => cache.PullAllBackingStoresAsync(), Throws.InvalidOperationException.With.Message.Contains("handler refuses notes")); + Assert.That(cache.Get(new CultRecordKey("other"))?.Text, Is.EqualTo("new"), "the second store was not pulled"); + } + + [Test] + public async Task NestedHoldOnAnotherCacheThrows() + { + var registry = Registry(); + using var second = new CultCache(registry); + using var first = new CultCache(registry); + first.AddBackingStore(new NestingStore(PathOf("nesting.cc"), () => second.UpsertAsync(new RoutingOther { Name = "other" }))); + await first.UpsertAsync(new RoutingNote { Name = "note" }); + + Assert.That(() => first.FlushAllBackingStores(), Throws.InvalidOperationException.With.Message.Contains("another cache's hold")); + Assert.That(second.AllEntries, Is.Empty); + } + private const string FixedStoredAt = "2026-09-13T00:00:00.0000000+00:00"; private string PathOf(string fileName) => Path.Combine(_directory, fileName); @@ -634,6 +673,22 @@ namespace GameCult.Caching.Tests throw new InvalidOperationException("RefusingStore refuses every write."); } + private sealed class NestingStore : SingleFileMessagePackBackingStore + { + private readonly Action _nested; + + public NestingStore(string filePath, Action nested) : base(filePath) + { + _nested = nested; + } + + public override void PushAll() + { + _nested(); + base.PushAll(); + } + } + private sealed class ObservingStore : SingleFileMessagePackBackingStore { private readonly Action _committed;