From 7362257f08a9668bd1bdb6fcd7965ef3d0eebb5c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 16:48:19 +0200 Subject: [PATCH 1/8] CultCache: read names and indexes once before minting; a throwing getter refuses the whole change set Resolve now ends in Project, the only place an admission runs a [CultName] or [CultIndex] getter on a landing record. It runs before land and before any Sequence is minted, so a throwing getter refuses the admission (loads included) with nothing written, minted or left in memory. The variant name and index rules and the indexer read the projection; Apply runs no user code. Co-Authored-By: Claude Sonnet 5 --- src/GameCult.Caching/CultCache.cs | 157 +++++++++---- .../CultCacheProjectionTests.cs | 210 ++++++++++++++++++ .../CultCachePublicationIsolationTests.cs | 63 ++++++ 3 files changed, 388 insertions(+), 42 deletions(-) create mode 100644 tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs create mode 100644 tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index b2f06659..8af4360c 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -2465,11 +2465,82 @@ namespace GameCult.Caching // Variants this admission did not write whose base chain it changed: re-resolved, same delta, same storedAt. public List Dependents { get; } = new(); + + // Name and index values of every record that lands (Admitted and Dependents), by key. Filled once by Project. + public Dictionary Projections { get; } = new(StringComparer.Ordinal); + } + + // What a landing record's [CultName] and [CultIndex] getters said. Indexes holds only non-blank values. + private sealed class Projection + { + public Projection(string? name, (string Alias, string Value)[] indexes) + { + Name = name; + Indexes = indexes; + } + + public string? Name { get; } + public (string Alias, string Value)[] Indexes { get; } + } + + // The only place an admission runs a name or index getter on a landing record. It runs before land and before any + // sequence is minted, so a getter that throws refuses the whole admission with nothing written and nothing minted. + private static void Project(VariantPlan plan) + { + foreach (var stored in plan.Admitted.Concat(plan.Dependents)) + { + var descriptor = stored.Descriptor; + string? name = null; + if (descriptor.NameAccessor != null) + name = Read(stored, $"[CultName] member {descriptor.NameMember}", descriptor.NameAccessor) is { Length: > 0 } read ? read : null; + var indexes = new List<(string Alias, string Value)>(); + foreach (var pair in descriptor.IndexAccessors) + { + var member = descriptor.RichMembers.First(candidate => candidate.IndexAlias == pair.Key).Member.Name; + var value = Read(stored, $"index '{pair.Key}' member {member}", pair.Value); + if (!string.IsNullOrWhiteSpace(value)) + indexes.Add((pair.Key, value!)); + } + + plan.Projections[stored.Key.Value] = new Projection(name, indexes.ToArray()); + } + } + + private static string? Read(CultStoredDocument stored, string what, Func getter) + { + try + { + return getter(stored.Document); + } + catch (Exception exception) + { + throw new InvalidOperationException( + $"Record {stored.Key.Value} ({stored.Descriptor.SchemaName}) is refused: its {what} threw: {exception.GetBaseException().Message}", exception); + } + } + + // Every admission is judged here: variants resolved, then every landing record's name and index values read once, + // then the rules that compare them. It refuses naming the keys, and mutates nothing. + private VariantPlan Resolve( + IReadOnlyList admitted, + IReadOnlyList evicted, + CacheBackingStore? source) + { + var plan = ResolveVariants(admitted, evicted, source); + Project(plan); + // The variant rules are judged only when a variant is involved. + if (_variantKeys.Count != 0 || admitted.Any(stored => stored.Variant != null)) + { + RefuseVariantNameSharing(plan, evicted); + RefuseVariantIndexSharing(plan, evicted); + } + + return plan; } // Resolves every admitted variant and every variant whose base chain this admission changes, base first, against // the post-admission set. It refuses a broken variant naming the keys, and mutates nothing. - private VariantPlan Resolve( + private VariantPlan ResolveVariants( IReadOnlyList admitted, IReadOnlyList evicted, CacheBackingStore? source) @@ -2531,11 +2602,7 @@ namespace GameCult.Caching } if (toResolve.Count == 0) - { - var unchanged = new VariantPlan(admitted); - RefuseVariantIndexSharing(unchanged, incoming, gone); - return unchanged; - } + return new VariantPlan(admitted); var pending = new HashSet(toResolve, StringComparer.Ordinal); var done = new Dictionary(StringComparer.Ordinal); @@ -2546,7 +2613,6 @@ namespace GameCult.Caching var plan = new VariantPlan(admitted.Select(stored => done.TryGetValue(stored.Key.Value, out var resolved) ? resolved : stored).ToList()); foreach (var key in toResolve.Where(key => !incoming.ContainsKey(key))) plan.Dependents.Add(done[key]); - RefuseVariantIndexSharing(plan, incoming, gone); return plan; CultStoredDocument ResolveOne(string key) @@ -2610,21 +2676,6 @@ namespace GameCult.Caching var document = _codec.Deserialize(type, type, kept.Count == 0 ? payload : _codec.Overlay(payload, kept)) ?? throw new InvalidOperationException($"Variant {key} resolved to nothing."); - if (isVariant) - { - // R6: the name index maps one name to one key, so a variant that kept its base's name would shadow it. - if (descriptor.NameAccessor?.Invoke(document) is { Length: > 0 } variantName) - { - for (var ancestor = baseStored; ancestor != null; - ancestor = ancestor.Variant == null ? null : done.TryGetValue(ancestor.Variant.BaseKey, out var above) ? above : Lookup(ancestor.Variant.BaseKey)) - { - if (descriptor.NameAccessor(ancestor.Document) == variantName) - throw new InvalidOperationException( - $"Variant {key} and its base {ancestor.Key.Value} are both named '{variantName}'; a variant must override its name."); - } - } - } - stack.RemoveAt(stack.Count - 1); return done[key] = isVariant ? variant.Resolved(document) @@ -2632,20 +2683,49 @@ namespace GameCult.Caching } } + // R6: the name index maps one name to one key, so a variant that kept its base's name would shadow it. A variant's + // name is its projection; an ancestor that lands is read from its projection, one that stays is read as held. + private void RefuseVariantNameSharing(VariantPlan plan, IReadOnlyList evicted) + { + var gone = evicted.Select(stored => stored.Key.Value).ToHashSet(StringComparer.Ordinal); + var landing = plan.Admitted.Concat(plan.Dependents).ToDictionary(stored => stored.Key.Value, StringComparer.Ordinal); + + CultStoredDocument? Ancestor(string key) => + landing.TryGetValue(key, out var landed) ? landed + : gone.Contains(key) ? null + : _entries.TryGetValue(key, out var held) ? held : null; + + string? NameOf(CultStoredDocument stored) => + plan.Projections.TryGetValue(stored.Key.Value, out var projection) + ? projection.Name + : stored.Descriptor.NameAccessor == null ? null : Read(stored, $"[CultName] member {stored.Descriptor.NameMember}", stored.Descriptor.NameAccessor); + + foreach (var variant in landing.Values.Where(stored => stored.Variant != null)) + { + if (plan.Projections[variant.Key.Value].Name is not { } variantName) + continue; + for (var ancestor = Ancestor(variant.Variant!.BaseKey); ancestor != null; + ancestor = ancestor.Variant == null ? null : Ancestor(ancestor.Variant.BaseKey)) + { + if (NameOf(ancestor) == variantName) + throw new InvalidOperationException( + $"Variant {variant.Key.Value} and its base {ancestor.Key.Value} are both named '{variantName}'; a variant must override its name."); + } + } + } + // The one index rule, judged on the commit's result whatever the write order: a variant may not share an indexed // value with another record. It reads the truthful held index (every holder of a value), minus the records this // commit replaces or removes, plus the records it lands. Plain-vs-plain sharing is not this rule's business. // A unique index maps a value to one key at lookup; a variant sharing it would be found in place of its // holder or lose the value, and the store would refuse to reopen. - private void RefuseVariantIndexSharing( - VariantPlan plan, - IReadOnlyDictionary incoming, - HashSet gone) + private void RefuseVariantIndexSharing(VariantPlan plan, IReadOnlyList evicted) { var landing = plan.Admitted.Concat(plan.Dependents).ToList(); if (landing.All(stored => stored.Descriptor.IndexAccessors.Count == 0)) return; - var replaced = new HashSet(incoming.Keys.Concat(gone).Concat(plan.Dependents.Select(stored => stored.Key.Value)), StringComparer.Ordinal); + var replaced = new HashSet( + plan.Admitted.Concat(evicted).Concat(plan.Dependents).Select(stored => stored.Key.Value), StringComparer.Ordinal); var landingByKey = landing.ToDictionary(stored => stored.Key.Value, StringComparer.Ordinal); bool IsVariant(string key) => @@ -2656,12 +2736,9 @@ namespace GameCult.Caching var landed = new Dictionary<((Type Type, string Alias) Index, string Value), List>(); foreach (var stored in landing) { - foreach (var pair in stored.Descriptor.IndexAccessors) + foreach (var (alias, value) in plan.Projections[stored.Key.Value].Indexes) { - var value = pair.Value(stored.Document); - if (string.IsNullOrWhiteSpace(value)) - continue; - var index = (stored.Descriptor.DocumentType, pair.Key); + var index = (stored.Descriptor.DocumentType, alias); landedValues.Add((stored, index, value)); if (!landed.TryGetValue((index, value), out var landedKeys)) landed[(index, value)] = landedKeys = new List(); @@ -2733,7 +2810,7 @@ namespace GameCult.Caching _entries[stored.Key.Value] = stored; _handles.AddOrUpdate(stored.Document, new KeyBox(stored.Key)); - Index(stored); + Index(stored, plan.Projections[stored.Key.Value]); if (stored.Variant == null) _variantKeys.Remove(stored.Key.Value); else @@ -2790,19 +2867,15 @@ namespace GameCult.Caching } } - private void Index(CultStoredDocument stored) + private void Index(CultStoredDocument stored, Projection projection) { var type = stored.Descriptor.DocumentType; if (stored.Descriptor.IsGlobal) _globals[type] = stored.Key.Value; - if (stored.Descriptor.NameAccessor?.Invoke(stored.Document) is { Length: > 0 } name) - MapOf(_names, type)[name] = stored.Key.Value; - foreach (var pair in stored.Descriptor.IndexAccessors) - { - var value = pair.Value(stored.Document); - if (!string.IsNullOrWhiteSpace(value)) - AddHolder(_indexes, (type, pair.Key), value, stored.Key.Value); - } + if (projection.Name != null) + MapOf(_names, type)[projection.Name] = stored.Key.Value; + foreach (var (alias, value) in projection.Indexes) + AddHolder(_indexes, (type, alias), value, stored.Key.Value); } // Documents are mutable, so a name or index value may have changed since it was indexed: drop by key. diff --git a/tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs b/tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs new file mode 100644 index 00000000..a35db5bd --- /dev/null +++ b/tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs @@ -0,0 +1,210 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using NUnit.Framework; +using R3; + +namespace GameCult.Caching.Tests +{ + // Cut 1 of docs/cultcache-publication-cut.md: an admission reads every landing record's name and index values once, + // before land and before any sequence is minted. A getter that throws refuses the whole change set. + [NonParallelizable] + public class CultCacheProjectionTests + { + private static readonly CultDocumentRegistry Registry = CultDocumentRegistry.ForTypes(new[] { typeof(ProjectedRecord) }); + + private string _directory = string.Empty; + + [SetUp] + public void Prepare() + { + _directory = Path.Combine(Path.GetTempPath(), $"cultlib-projection-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_directory); + ProjectedRecord.Armed = false; + ProjectedRecord.Reads = 0; + } + + [TearDown] + public void Cleanup() + { + ProjectedRecord.Armed = false; + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } + + [CultDocument("tests.projected_record", "tests.projected_record.v1")] + [MessagePackObject(AllowPrivate = true)] + internal sealed class ProjectedRecord + { + public static long Reads; + public static volatile bool Armed; + [IgnoreMember] private string _name = string.Empty; + [IgnoreMember] private string _code = string.Empty; + + [Key(0)] + [CultName] + public string Name + { + get + { + Interlocked.Increment(ref Reads); + if (Armed && _name == "boom") + throw new InvalidOperationException("name getter boom"); + return _name; + } + set => _name = value; + } + + [Key(1)] + [CultIndex("code")] + public string Code + { + get + { + Interlocked.Increment(ref Reads); + if (Armed && _code == "boom") + throw new InvalidOperationException("index getter boom"); + return _code; + } + set => _code = value; + } + } + + private static readonly CultRecordKey OkKey = new("projected:ok"); + private static readonly CultRecordKey BoomKey = new("projected:boom"); + + private static ProjectedRecord Ok() => new() { Name = "ok", Code = "ok-code" }; + + private static ProjectedRecord Boom(bool name) => name ? new ProjectedRecord { Name = "boom", Code = "boom-code" } : new ProjectedRecord { Name = "boom-name", Code = "boom" }; + + private string PathOf(string name) => Path.Combine(_directory, name); + + private static CultCache Open(string path) => CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = Registry }); + + private static void Put(CultCache cache, ProjectedRecord document, CultRecordKey key) => + cache.Commit(batch => batch.Upsert(typeof(ProjectedRecord), document, key)); + + private static long SequenceOf(CultCache cache) => cache.GetWithSequence(OkKey).Sequence; + + private static void StageBoth(CultCacheBatch batch, ProjectedRecord boom) + { + batch.Upsert(typeof(ProjectedRecord), Ok(), OkKey); + batch.Upsert(typeof(ProjectedRecord), boom, BoomKey); + } + + [TestCase(true, "[CultName] member Name")] + [TestCase(false, "index 'code' member Code")] + public void ARefusedGetterMintsNothingAndChangesNothing(bool nameThrows, string member) + { + using var cache = new CultCache(Registry); + var seen = new List(); + using var watch = cache.Watch().Subscribe(change => seen.Add(change.Sequence)); + Put(cache, new ProjectedRecord { Name = "seed", Code = "seed-code" }, new CultRecordKey("projected:seed")); + var before = SequenceOf(cache); + seen.Clear(); + ProjectedRecord.Armed = true; + + var refusal = Assert.Throws(() => cache.Commit(batch => StageBoth(batch, Boom(nameThrows))))!; + + ProjectedRecord.Armed = false; + Assert.Multiple(() => + { + Assert.That(refusal.Message, Does.Contain(BoomKey.Value).And.Contain(member).And.Contain("getter boom")); + Assert.That(SequenceOf(cache), Is.EqualTo(before), "a refused admission mints nothing"); + Assert.That(cache.Get(OkKey), Is.Null, "the good record did not land"); + Assert.That(cache.Get(BoomKey), Is.Null); + Assert.That(cache.GetByName("ok"), Is.Null, "the name index holds nothing of the refused set"); + Assert.That(cache.GetByIndex("code", "ok-code"), Is.Null); + Assert.That(seen, Is.Empty, "nothing was published"); + }); + + Put(cache, Ok(), OkKey); + Assert.That(SequenceOf(cache), Is.EqualTo(before + 1), "the next write is previous + 1"); + Assert.That(seen, Is.EqualTo(new[] { before + 1 })); + } + + [Test] + public void ARefusedSingleWriteMintsNothing() + { + using var cache = new CultCache(Registry); + ProjectedRecord.Armed = true; + + var refusal = Assert.Throws(() => Put(cache, Boom(true), BoomKey))!; + + ProjectedRecord.Armed = false; + Assert.That(refusal.Message, Does.Contain(BoomKey.Value)); + Assert.That(SequenceOf(cache), Is.EqualTo(0)); + Assert.That(cache.Get(BoomKey), Is.Null); + } + + [Test] + public void ARefusedBatchLeavesAStoreByteIdenticalAndReopensWithNeitherKey() + { + var path = PathOf("projected.cc"); + using (var seed = Open(path)) + Put(seed, new ProjectedRecord { Name = "seed", Code = "seed-code" }, new CultRecordKey("projected:seed")); + var before = File.ReadAllBytes(path); + + using (var cache = Open(path)) + { + ProjectedRecord.Armed = true; + Assert.Throws(() => cache.Commit(batch => StageBoth(batch, Boom(true)))); + ProjectedRecord.Armed = false; + Assert.That(File.ReadAllBytes(path), Is.EqualTo(before)); + } + + using var reopened = Open(path); + Assert.Multiple(() => + { + Assert.That(reopened.Get(OkKey), Is.Null); + Assert.That(reopened.Get(BoomKey), Is.Null); + Assert.That(File.ReadAllBytes(path), Is.EqualTo(before)); + }); + } + + [Test] + public void ALoadWhoseGetterThrowsRefusesTheOpenAndLeavesTheFileByteIdentical() + { + var path = PathOf("poisoned.cc"); + using (var seed = Open(path)) + Put(seed, Boom(true), BoomKey); + var before = File.ReadAllBytes(path); + + ProjectedRecord.Armed = true; + var refusal = Assert.Throws(() => Open(path))!; + ProjectedRecord.Armed = false; + + Assert.That(refusal.Message, Does.Contain(BoomKey.Value).And.Contain("[CultName] member Name")); + Assert.That(File.ReadAllBytes(path), Is.EqualTo(before)); + } + + // A counting getter: each landing record is read once for its name and once for its index, and never again by the + // variant rules or the indexer. A variant re-resolved by a base edit lands too, and is read once. + [Test] + public void EachLandedRecordIsReadOncePerGetterIncludingAVariantDependent() + { + using var cache = new CultCache(Registry, CultCacheMessagePack.CreateCodec(Registry)); + var baseKey = new CultRecordKey("projected:base"); + Put(cache, new ProjectedRecord { Name = "base", Code = "base-code" }, baseKey); + cache.Commit(batch => batch.UpsertVariant(new CultRecordKey("projected:variant"), baseKey, new[] + { + cache.Override(nameof(ProjectedRecord.Name), "variant"), + cache.Override(nameof(ProjectedRecord.Code), "variant-code") + })); + + ProjectedRecord.Reads = 0; + Put(cache, new ProjectedRecord { Name = "base", Code = "base-code-2" }, baseKey); + + // Two landing records (the base, and the variant re-resolved against it), two getters each. + Assert.That(Interlocked.Read(ref ProjectedRecord.Reads), Is.EqualTo(4)); + Assert.That(cache.GetByIndex("code", "base-code-2"), Is.Not.Null); + Assert.That(cache.GetByName("variant"), Is.Not.Null); + } + } +} diff --git a/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs b/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs new file mode 100644 index 00000000..9ba78efa --- /dev/null +++ b/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs @@ -0,0 +1,63 @@ +#nullable enable +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Threading.Tasks; +using GameCult.Caching; +using NUnit.Framework; +using R3; +using static GameCult.Networking.Tests.NetworkingTests; + +namespace GameCult.Networking.Tests +{ + [CultDocument("tests.publication_throwing_name", "tests.publication_throwing_name.v1")] + [MessagePack.MessagePackObject] + public sealed class PublicationThrowingName + { + [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 { } + } + } + + // Cache publication cuts 1 and 2 seen through CultNetDatabase: a refused or failing change never stalls the + // publication and log of the changes after it. (Soul pass 3 probes P4 and P3.) + [NonParallelizable] + public sealed class CultCachePublicationIsolationTests + { + private static NetworkSchemaNote Note(string text) => new() { Schema = "tests.networking_note.v1", Text = text }; + private static string SchemaId => CultDocumentRegistry.Shared.GetRequired().SchemaId; + + // An admission that a [CultName] getter refuses publishes nothing, leaves nothing in memory, and stalls nothing after it. + [Test] + public async Task ARefusedAdmissionLeavesNothingAndLaterChangesStillPublishAndLog() + { + var cache = new CultCache(); + var database = new CultNetDatabase(cache); + var seen = new ConcurrentQueue(); + using var watch = database.Watch().Subscribe(change => seen.Enqueue(change.Document?.Text)); + var okKey = new CultRecordKey("pub:ok"); + var refusal = Assert.Throws(() => cache.Commit(batch => + { + batch.Upsert(new PublicationThrowingName { Text = "ok" }, new CultRecordHandle(okKey)); + batch.Upsert(new PublicationThrowingName { Text = "boom" }, new CultRecordHandle(new CultRecordKey("pub:boomname"))); + }))!; + + var after = new CultRecordKey("pub:after"); + await database.PutAsync(after, Note("after")); + Assert.Multiple(() => + { + Assert.That(refusal.Message, Does.Contain("pub:boomname").And.Contain("name getter boom")); + Assert.That(cache.Get(okKey), Is.Null, "the good record of a refused batch did not land"); + Assert.That(seen, Is.EqualTo(new[] { "after" })); + Assert.That(database.LastWriteSequence(SchemaId, after), Is.Not.Null, "a later commit was never logged"); + }); + } + } +} From 6b0cf66f0e1e2066b2867ccd1a898a4f0a19b716 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 16:50:29 +0200 Subject: [PATCH 2/8] Count serializer reads apart in the once-per-landed-record projection test Resolving a variant serializes its base, and the serializer reads the same getters; the test measured them together and expected too few. Co-Authored-By: Claude Sonnet 5 --- .../CultCacheProjectionTests.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs b/tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs index a35db5bd..88f251c6 100644 --- a/tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs +++ b/tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs @@ -189,7 +189,8 @@ namespace GameCult.Caching.Tests [Test] public void EachLandedRecordIsReadOncePerGetterIncludingAVariantDependent() { - using var cache = new CultCache(Registry, CultCacheMessagePack.CreateCodec(Registry)); + var codec = CultCacheMessagePack.CreateCodec(Registry); + using var cache = new CultCache(Registry, codec); var baseKey = new CultRecordKey("projected:base"); Put(cache, new ProjectedRecord { Name = "base", Code = "base-code" }, baseKey); cache.Commit(batch => batch.UpsertVariant(new CultRecordKey("projected:variant"), baseKey, new[] @@ -198,11 +199,16 @@ namespace GameCult.Caching.Tests cache.Override(nameof(ProjectedRecord.Code), "variant-code") })); + // Resolving a variant serializes its base, and the serializer reads the same getters: count those reads apart. + ProjectedRecord.Reads = 0; + codec.Serialize(new ProjectedRecord(), typeof(ProjectedRecord), typeof(ProjectedRecord)); + var serializerReads = Interlocked.Read(ref ProjectedRecord.Reads); + ProjectedRecord.Reads = 0; Put(cache, new ProjectedRecord { Name = "base", Code = "base-code-2" }, baseKey); - // Two landing records (the base, and the variant re-resolved against it), two getters each. - Assert.That(Interlocked.Read(ref ProjectedRecord.Reads), Is.EqualTo(4)); + // Two landing records (the base, and the variant re-resolved against it), two getters each, plus the one serialization. + Assert.That(Interlocked.Read(ref ProjectedRecord.Reads), Is.EqualTo(4 + serializerReads)); Assert.That(cache.GetByIndex("code", "base-code-2"), Is.Not.Null); Assert.That(cache.GetByName("variant"), Is.Not.Null); } From ecee41e8fff510b3616d44e7582b6e34ee038036 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 16:51:33 +0200 Subject: [PATCH 3/8] CultCache: own the observer list and isolate every observer The cache no longer fans changes out through an R3 Subject. It keeps a copy-on-write observer array and Publish catches per observer: every observer receives every change, an exception that escapes (a fail-fast R3 handler) joins the OnUpdate failures rethrown to the writer after delivery, and the observer stays subscribed. Dispose completes observers, and a disposed cache completes new ones at once. Deletes the false "OnNext does not throw" comment. The composition contract now states the observer policy and that a throwing name or index getter refuses a change set, loads included. Co-Authored-By: Claude Sonnet 5 --- .../Contracts/cultcache-store-composition.md | 17 ++- src/GameCult.Caching/CultCache.cs | 73 ++++++++- .../CultCacheObserverTests.cs | 139 ++++++++++++++++++ .../CultCachePublicationIsolationTests.cs | 35 +++++ 4 files changed, 252 insertions(+), 12 deletions(-) create mode 100644 tests/GameCult.Caching.Tests/CultCacheObserverTests.cs diff --git a/src/GameCult.Caching/Contracts/cultcache-store-composition.md b/src/GameCult.Caching/Contracts/cultcache-store-composition.md index ab028fca..6cf6cdfa 100644 --- a/src/GameCult.Caching/Contracts/cultcache-store-composition.md +++ b/src/GameCult.Caching/Contracts/cultcache-store-composition.md @@ -77,14 +77,21 @@ which route wrote it. - 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. + are dropped. Every `Watch` subscriber receives every change: R3 routes a + subscriber's exception to its unhandled-exception handler, and if that handler + rethrows (fail-fast), the exception is treated as an `OnUpdate` handler + exception. The subscriber stays subscribed and the commit stands. A throwing + handler cannot undo the store's adoption of a load; the store and cache + already agree when publication starts. +- A record's `[CultName]` and `[CultIndex]` getters run once per landing record, + before the store is written and before any `Sequence` is minted. A getter that + throws refuses the whole change set, loads included: nothing is written, + minted or left in memory. - 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 + schema the registry cannot resolve or whose name or index getter throws, makes + the open throw and leaves the file byte-identical. Consumers never delete and rewrite a store they failed to open. ## Locking diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index 8af4360c..2a9de06e 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -1806,7 +1806,11 @@ namespace GameCult.Caching // Keys holding a variant: derived from the entries by Apply, never decided anywhere else. private readonly HashSet _variantKeys = new(StringComparer.Ordinal); private readonly ConditionalWeakTable _handles = new(); - private readonly Subject _changes = new(); + // The cache's own observers, copy-on-write under _observerGate: publication reads one snapshot per change and + // catches per observer, so no observer decides whether another receives a change. + private Observer[] _observers = Array.Empty>(); + private bool _observersCompleted; + private readonly object _observerGate = new(); private readonly object _gate = new(); private long _sequence; // The changes admitted by this thread's outermost hold, published by that hold when it exits. @@ -1886,7 +1890,7 @@ namespace GameCult.Caching public Observable> Watch() where T : class { - return _changes + return Observable.Create(Register) .Where(change => typeof(T).IsAssignableFrom(change.Stored.Descriptor.DocumentType)) .Select(change => new CultCacheDocumentChange( change.Kind, @@ -1896,6 +1900,25 @@ namespace GameCult.Caching change.Sequence)); } + private IDisposable Register(Observer observer) + { + lock (_observerGate) + { + if (!_observersCompleted) + { + _observers = _observers.Append(observer).ToArray(); + return Disposable.Create(() => + { + lock (_observerGate) + _observers = _observers.Where(held => !ReferenceEquals(held, observer)).ToArray(); + }); + } + } + + observer.OnCompleted(); + return Disposable.Empty; + } + public Observable> WatchRecord(CultRecordKey key) where T : class { return Watch().Where(change => change.Key.Equals(key)); @@ -2151,7 +2174,31 @@ namespace GameCult.Caching foreach (var store in BackingStores) store.Dispose(); - _changes.Dispose(); + Observer[] completing; + lock (_observerGate) + { + completing = _observers; + _observers = Array.Empty>(); + _observersCompleted = true; + } + + var failures = new List(); + foreach (var observer in completing) + { + try + { + observer.OnCompleted(); + } + catch (Exception exception) + { + failures.Add(exception); + } + } + + if (failures.Count == 1) + ExceptionDispatchInfo.Capture(failures[0]).Throw(); + if (failures.Count > 1) + throw new AggregateException(failures); } internal static void RequireInstanceOf(Type documentType, object document) @@ -2333,8 +2380,8 @@ namespace GameCult.Caching // Every admission runs in a hold. A nested hold on the same cache adds to the outermost one, which publishes // exactly its own changes after it leaves the gate, before it returns, on its caller's thread: observers never // run under the gate, and a write an observer makes is a new outermost hold. Cross-thread delivery order is not - // guaranteed; each change carries the Sequence it was admitted with. Every change is delivered even if an - // OnUpdate handler throws; then the first handler exception (an AggregateException for several) is rethrown. + // guaranteed; each change carries the Sequence it was admitted with. Every change reaches every observer even + // if an observer or an OnUpdate handler throws; then the first exception (an AggregateException for several) is rethrown. // If the body threw, its exception wins. internal T Held(Func body) { @@ -2371,8 +2418,20 @@ namespace GameCult.Caching var failures = new List(); foreach (var (change, loaded) in changes) { - // R3 routes a throwing subscriber to its unhandled-exception handler; OnNext does not throw. - _changes.OnNext(change); + // R3 routes a throwing subscriber to its unhandled-exception handler, and a fail-fast handler rethrows: every + // observer still runs, the exception joins the failures, and the observer stays subscribed. + foreach (var observer in Volatile.Read(ref _observers)) + { + try + { + observer.OnNext(change); + } + catch (Exception exception) + { + failures.Add(exception); + } + } + if (!loaded) continue; try diff --git a/tests/GameCult.Caching.Tests/CultCacheObserverTests.cs b/tests/GameCult.Caching.Tests/CultCacheObserverTests.cs new file mode 100644 index 00000000..8cb3992d --- /dev/null +++ b/tests/GameCult.Caching.Tests/CultCacheObserverTests.cs @@ -0,0 +1,139 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using NUnit.Framework; +using R3; + +namespace GameCult.Caching.Tests +{ + // Cut 2 of docs/cultcache-publication-cut.md: the cache keeps its own observers and catches per observer, so no + // observer decides whether another receives a change. R3 routes a subscriber's exception to the unhandled handler; + // these tests install a fail-fast (rethrowing) handler, the only way an exception reaches the cache. + [NonParallelizable] + public class CultCacheObserverTests + { + private static readonly CultDocumentRegistry Registry = CultDocumentRegistry.ForTypes(new[] { typeof(ObservedPing) }); + + private Action _previousHandler = _ => { }; + + [SetUp] + public void FailFast() + { + _previousHandler = ObservableSystem.GetUnhandledExceptionHandler(); + ObservableSystem.RegisterUnhandledExceptionHandler(exception => throw exception); + } + + [TearDown] + public void Restore() => ObservableSystem.RegisterUnhandledExceptionHandler(_previousHandler); + + [CultDocument("tests.observed_ping", "tests.observed_ping.v1")] + [MessagePackObject(AllowPrivate = true)] + internal sealed class ObservedPing + { + [Key(0)] + public string Text = string.Empty; + } + + private static CultRecordKey KeyOf(string text) => new($"observed:{text}"); + + private static void Send(CultCache cache, params string[] texts) => + cache.Commit(batch => + { + foreach (var text in texts) + batch.Upsert(typeof(ObservedPing), new ObservedPing { Text = text }, KeyOf(text)); + }); + + [Test] + public void AnEscapedObserverExceptionReachesTheWriterAfterEveryObserverSawEveryChange() + { + using var cache = new CultCache(Registry); + var thrower = new List(); + var later = new List(); + using var first = cache.Watch().Subscribe(change => + { + thrower.Add(change.Document!.Text); + if (change.Document.Text == "boom") + throw new InvalidOperationException("observer boom"); + }); + using var second = cache.Watch().Subscribe(change => later.Add(change.Document!.Text)); + + var escaped = Assert.Throws(() => Send(cache, "boom", "after"))!; + + Assert.Multiple(() => + { + Assert.That(escaped.Message, Is.EqualTo("observer boom")); + Assert.That(later, Is.EqualTo(new[] { "boom", "after" }), "the observer after the thrower saw every change of the hold"); + Assert.That(thrower, Is.EqualTo(new[] { "boom", "after" }), "the thrower kept receiving after its own exception"); + Assert.That(cache.Get(KeyOf("boom")), Is.Not.Null, "the commit stands"); + Assert.That(cache.Get(KeyOf("after")), Is.Not.Null); + }); + + Send(cache, "later"); + Assert.That(thrower, Is.EqualTo(new[] { "boom", "after", "later" }), "the thrower stayed subscribed"); + Assert.That(later, Is.EqualTo(new[] { "boom", "after", "later" })); + } + + [Test] + public void SeveralEscapedObserverExceptionsArriveTogether() + { + using var cache = new CultCache(Registry); + using var one = cache.Watch().Subscribe(_ => throw new InvalidOperationException("one")); + using var two = cache.Watch().Subscribe(_ => throw new InvalidOperationException("two")); + + var escaped = Assert.Throws(() => Send(cache, "boom"))!; + + Assert.That(escaped.InnerExceptions.Select(exception => exception.Message), Is.EqualTo(new[] { "one", "two" })); + } + + [Test] + public void ObserversMayJoinAndLeaveDuringADeliveryWithoutBreakingTheOthers() + { + using var cache = new CultCache(Registry); + var a = new List(); + var b = new List(); + var c = new List(); + var d = new List(); + IDisposable? leaving = null; + IDisposable? joined = null; + using var first = cache.Watch().Subscribe(change => + { + a.Add(change.Sequence); + if (a.Count != 1) + return; + leaving!.Dispose(); + joined = cache.Watch().Subscribe(next => c.Add(next.Sequence)); + }); + leaving = cache.Watch().Subscribe(change => b.Add(change.Sequence)); + using var last = cache.Watch().Subscribe(change => d.Add(change.Sequence)); + + Send(cache, "one", "two"); + joined?.Dispose(); + + Assert.Multiple(() => + { + Assert.That(a, Is.EqualTo(new[] { 1L, 2L })); + Assert.That(d, Is.EqualTo(new[] { 1L, 2L }), "an observer that did not move still saw everything"); + Assert.That(b, Does.Not.Contain(2L), "a disposed observer stops receiving"); + Assert.That(c, Is.EqualTo(new[] { 2L }), "an observer that joined mid-hold receives from the next change"); + }); + } + + [Test] + public void DisposeCompletesObserversAndACompletedCacheCompletesNewOnes() + { + var cache = new CultCache(Registry); + var completed = 0; + using var before = cache.Watch().Subscribe(_ => { }, _ => completed++); + + cache.Dispose(); + Assert.That(completed, Is.EqualTo(1)); + + using var after = cache.Watch().Subscribe(_ => { }, _ => completed++); + Assert.That(completed, Is.EqualTo(2), "subscribing to a disposed cache completes at once"); + } + } +} diff --git a/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs b/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs index 9ba78efa..33d1100d 100644 --- a/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs +++ b/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs @@ -59,5 +59,40 @@ namespace GameCult.Networking.Tests Assert.That(database.LastWriteSequence(SchemaId, after), Is.Not.Null, "a later commit was never logged"); }); } + + // One observer's escaped exception (a fail-fast R3 handler) does not stop the database observer after it, and the writer gets it. + [Test] + public async Task AnEscapedObserverExceptionDoesNotStopTheDatabaseOrLaterChanges() + { + var previous = ObservableSystem.GetUnhandledExceptionHandler(); + ObservableSystem.RegisterUnhandledExceptionHandler(exception => throw exception); + try + { + var cache = new CultCache(); + using var thrower = cache.Watch().Subscribe(change => + { + if (change.Document?.Text == "boom") throw new InvalidOperationException("observer boom"); + }); + var database = new CultNetDatabase(cache); + var seen = new ConcurrentQueue(); + using var watch = database.Watch().Subscribe(change => seen.Enqueue(change.Document?.Text)); + var boom = new CultRecordKey("pub:boom"); + var escaped = Assert.ThrowsAsync(() => cache.UpsertAsync(Note("boom"), new CultRecordHandle(boom))); + + ObservableSystem.RegisterUnhandledExceptionHandler(previous); + var after = new CultRecordKey("pub:after"); + await database.PutAsync(after, Note("after")); + Assert.Multiple(() => + { + Assert.That(escaped!.Message, Is.EqualTo("observer boom")); + Assert.That(seen, Is.EqualTo(new[] { "boom", "after" }), "the database observer after the thrower saw both changes"); + Assert.That(database.LastWriteSequence(SchemaId, after), Is.Not.Null, "a later commit was never logged"); + }); + } + finally + { + ObservableSystem.RegisterUnhandledExceptionHandler(previous); + } + } } } From b8ceab84acdbc80a3f1babb4075070e53d5cc029 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 16:54:40 +0200 Subject: [PATCH 4/8] Drive the escaped-observer probe through a database write A direct cache write is not a database change on this base, so the database observer could not show it. PutAsync is, and the observer after the thrower must see it. Co-Authored-By: Claude Sonnet 5 --- .../CultCachePublicationIsolationTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs b/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs index 33d1100d..8b6106ec 100644 --- a/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs +++ b/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs @@ -77,7 +77,7 @@ namespace GameCult.Networking.Tests var seen = new ConcurrentQueue(); using var watch = database.Watch().Subscribe(change => seen.Enqueue(change.Document?.Text)); var boom = new CultRecordKey("pub:boom"); - var escaped = Assert.ThrowsAsync(() => cache.UpsertAsync(Note("boom"), new CultRecordHandle(boom))); + var escaped = Assert.ThrowsAsync(() => database.PutAsync(boom, Note("boom"))); ObservableSystem.RegisterUnhandledExceptionHandler(previous); var after = new CultRecordKey("pub:after"); From 41b964c6f1cc3c8df48f71b0617ad29dae257e58 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 16:57:04 +0200 Subject: [PATCH 5/8] Narrow the escaped-observer probe to what this base can show A database write is published after its cache write returns, so a write whose observer threw never reaches the database observers on this base. Keep the probe to the exception reaching the writer and later changes still publishing and logging; the ordering question belongs to the database cut. Co-Authored-By: Claude Sonnet 5 --- .../CultCachePublicationIsolationTests.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs b/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs index 8b6106ec..f8eeec8f 100644 --- a/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs +++ b/tests/GameCult.Networking.Tests/CultCachePublicationIsolationTests.cs @@ -60,9 +60,11 @@ namespace GameCult.Networking.Tests }); } - // One observer's escaped exception (a fail-fast R3 handler) does not stop the database observer after it, and the writer gets it. + // One observer's escaped exception (a fail-fast R3 handler) reaches the writer and does not stall later changes. + // A database write is published by the database after its cache write returns, so the failed write itself is not + // published here; that ordering belongs to the CultNetDatabase cut. [Test] - public async Task AnEscapedObserverExceptionDoesNotStopTheDatabaseOrLaterChanges() + public async Task AnEscapedObserverExceptionReachesTheWriterAndDoesNotStallLaterChanges() { var previous = ObservableSystem.GetUnhandledExceptionHandler(); ObservableSystem.RegisterUnhandledExceptionHandler(exception => throw exception); @@ -85,7 +87,7 @@ namespace GameCult.Networking.Tests Assert.Multiple(() => { Assert.That(escaped!.Message, Is.EqualTo("observer boom")); - Assert.That(seen, Is.EqualTo(new[] { "boom", "after" }), "the database observer after the thrower saw both changes"); + 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"); }); } From 9b23b33f8c35afc76204659807925ff4e924b94a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 17:11:47 +0200 Subject: [PATCH 6/8] Let Stryker mutate the variant name rule The is-not pattern binding made every mutant in RefuseVariantNameSharing a compile error, so Stryker removed the whole method from its run. Co-Authored-By: Claude Sonnet 5 --- src/GameCult.Caching/CultCache.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index 2a9de06e..d2115535 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -2761,7 +2761,8 @@ namespace GameCult.Caching foreach (var variant in landing.Values.Where(stored => stored.Variant != null)) { - if (plan.Projections[variant.Key.Value].Name is not { } variantName) + var variantName = plan.Projections[variant.Key.Value].Name; + if (variantName == null) continue; for (var ancestor = Ancestor(variant.Variant!.BaseKey); ancestor != null; ancestor = ancestor.Variant == null ? null : Ancestor(ancestor.Variant.BaseKey)) From 0a543c9fb29a4773398d8f32686fb0ba2f27f533 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 17:46:36 +0200 Subject: [PATCH 7/8] Kill the Stryker survivors in the projection and observer cuts Delete the dead removed-ancestor branch and the duplicated name-read in the variant name rule (resolution already refuses a missing or removed base and a variant shares its base type). Add tests for the index rule counting a record the same commit removes, blank names not colliding, and Dispose rethrowing escaped completions after every observer completed. Co-Authored-By: Claude Sonnet 5 --- src/GameCult.Caching/CultCache.cs | 16 +++---- .../CultCacheObserverTests.cs | 35 ++++++++++++++++ .../CultCacheProjectionTests.cs | 42 +++++++++++++++++++ 3 files changed, 85 insertions(+), 8 deletions(-) diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index d2115535..f9497cb3 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -2551,7 +2551,7 @@ namespace GameCult.Caching var descriptor = stored.Descriptor; string? name = null; if (descriptor.NameAccessor != null) - name = Read(stored, $"[CultName] member {descriptor.NameMember}", descriptor.NameAccessor) is { Length: > 0 } read ? read : null; + name = NameRead(stored) is { Length: > 0 } read ? read : null; var indexes = new List<(string Alias, string Value)>(); foreach (var pair in descriptor.IndexAccessors) { @@ -2565,6 +2565,9 @@ namespace GameCult.Caching } } + private static string? NameRead(CultStoredDocument stored) => + Read(stored, $"[CultName] member {stored.Descriptor.NameMember}", stored.Descriptor.NameAccessor!); + private static string? Read(CultStoredDocument stored, string what, Func getter) { try @@ -2590,7 +2593,7 @@ namespace GameCult.Caching // The variant rules are judged only when a variant is involved. if (_variantKeys.Count != 0 || admitted.Any(stored => stored.Variant != null)) { - RefuseVariantNameSharing(plan, evicted); + RefuseVariantNameSharing(plan); RefuseVariantIndexSharing(plan, evicted); } @@ -2744,20 +2747,17 @@ namespace GameCult.Caching // R6: the name index maps one name to one key, so a variant that kept its base's name would shadow it. A variant's // name is its projection; an ancestor that lands is read from its projection, one that stays is read as held. - private void RefuseVariantNameSharing(VariantPlan plan, IReadOnlyList evicted) + private void RefuseVariantNameSharing(VariantPlan plan) { - var gone = evicted.Select(stored => stored.Key.Value).ToHashSet(StringComparer.Ordinal); var landing = plan.Admitted.Concat(plan.Dependents).ToDictionary(stored => stored.Key.Value, StringComparer.Ordinal); + // Resolution already refused a base that is missing or removed, so an ancestor is landing or held. CultStoredDocument? Ancestor(string key) => landing.TryGetValue(key, out var landed) ? landed - : gone.Contains(key) ? null : _entries.TryGetValue(key, out var held) ? held : null; string? NameOf(CultStoredDocument stored) => - plan.Projections.TryGetValue(stored.Key.Value, out var projection) - ? projection.Name - : stored.Descriptor.NameAccessor == null ? null : Read(stored, $"[CultName] member {stored.Descriptor.NameMember}", stored.Descriptor.NameAccessor); + plan.Projections.TryGetValue(stored.Key.Value, out var projection) ? projection.Name : NameRead(stored); foreach (var variant in landing.Values.Where(stored => stored.Variant != null)) { diff --git a/tests/GameCult.Caching.Tests/CultCacheObserverTests.cs b/tests/GameCult.Caching.Tests/CultCacheObserverTests.cs index 8cb3992d..7fde01e7 100644 --- a/tests/GameCult.Caching.Tests/CultCacheObserverTests.cs +++ b/tests/GameCult.Caching.Tests/CultCacheObserverTests.cs @@ -135,5 +135,40 @@ namespace GameCult.Caching.Tests using var after = cache.Watch().Subscribe(_ => { }, _ => completed++); Assert.That(completed, Is.EqualTo(2), "subscribing to a disposed cache completes at once"); } + + // Completing an observer is publication too: every observer is completed, and a fail-fast handler's exception + // reaches the disposer afterwards (an AggregateException for several). + [Test] + public void ACompletionThatEscapesReachesTheDisposerAfterEveryObserverCompleted() + { + var cache = new CultCache(Registry); + var completed = new List(); + using var one = cache.Watch().Subscribe(_ => { }, _ => + { + completed.Add("one"); + throw new InvalidOperationException("one"); + }); + using var two = cache.Watch().Subscribe(_ => { }, _ => + { + completed.Add("two"); + throw new InvalidOperationException("two"); + }); + + var escaped = Assert.Throws(() => cache.Dispose())!; + + Assert.That(completed, Is.EqualTo(new[] { "one", "two" })); + Assert.That(escaped.InnerExceptions.Select(exception => exception.Message), Is.EqualTo(new[] { "one", "two" })); + } + + [Test] + public void ASingleEscapedCompletionIsRethrownAsItself() + { + var cache = new CultCache(Registry); + using var only = cache.Watch().Subscribe(_ => { }, _ => throw new InvalidOperationException("only")); + + var escaped = Assert.Throws(() => cache.Dispose())!; + + Assert.That(escaped.Message, Is.EqualTo("only")); + } } } diff --git a/tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs b/tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs index 88f251c6..57135929 100644 --- a/tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs +++ b/tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs @@ -212,5 +212,47 @@ namespace GameCult.Caching.Tests Assert.That(cache.GetByIndex("code", "base-code-2"), Is.Not.Null); Assert.That(cache.GetByName("variant"), Is.Not.Null); } + + // The index rule counts the holders a commit leaves behind: a record removed by the same commit no longer holds its value. + [Test] + public void AVariantMayTakeAnIndexedValueFromARecordTheSameCommitRemoves() + { + using var cache = new CultCache(Registry, CultCacheMessagePack.CreateCodec(Registry)); + var baseKey = new CultRecordKey("projected:base"); + var holderKey = new CultRecordKey("projected:holder"); + Put(cache, new ProjectedRecord { Name = "base", Code = "base-code" }, baseKey); + Put(cache, new ProjectedRecord { Name = "holder", Code = "shared" }, holderKey); + + var landed = cache.Commit(batch => + { + batch.Remove(holderKey); + batch.UpsertVariant(new CultRecordKey("projected:variant"), baseKey, new[] + { + cache.Override(nameof(ProjectedRecord.Name), "variant"), + cache.Override(nameof(ProjectedRecord.Code), "shared") + }); + }); + + Assert.That(landed, Is.True); + Assert.That(cache.GetByIndex("code", "shared"), Is.Not.Null); + Assert.That(cache.Get(holderKey), Is.Null); + } + + // A blank name is no name: a variant and its base that are both blank do not shadow each other. + [Test] + public void ABlankNameIsNoNameSoBlankVariantAndBaseDoNotCollide() + { + using var cache = new CultCache(Registry, CultCacheMessagePack.CreateCodec(Registry)); + var baseKey = new CultRecordKey("projected:base"); + Put(cache, new ProjectedRecord { Name = "", Code = "base-code" }, baseKey); + + cache.Commit(batch => batch.UpsertVariant(new CultRecordKey("projected:variant"), baseKey, new[] + { + cache.Override(nameof(ProjectedRecord.Name), ""), + cache.Override(nameof(ProjectedRecord.Code), "variant-code") + })); + + Assert.That(cache.Get(new CultRecordKey("projected:variant")), Is.Not.Null); + } } } From 5fb3fca2baf7ff256fd3df53909069a5699361a9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 18:14:24 +0200 Subject: [PATCH 8/8] Normalise a blank name once, where it is read The held-ancestor path compared the raw empty string, so a blank variant name and a blank held base name never met the blank rule; NameRead now returns null for blank on both paths. Co-Authored-By: Claude Sonnet 5 --- src/GameCult.Caching/CultCache.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index f9497cb3..245e9367 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -2549,9 +2549,7 @@ namespace GameCult.Caching foreach (var stored in plan.Admitted.Concat(plan.Dependents)) { var descriptor = stored.Descriptor; - string? name = null; - if (descriptor.NameAccessor != null) - name = NameRead(stored) is { Length: > 0 } read ? read : null; + var name = descriptor.NameAccessor == null ? null : NameRead(stored); var indexes = new List<(string Alias, string Value)>(); foreach (var pair in descriptor.IndexAccessors) { @@ -2565,8 +2563,9 @@ namespace GameCult.Caching } } + // A blank name is no name. private static string? NameRead(CultStoredDocument stored) => - Read(stored, $"[CultName] member {stored.Descriptor.NameMember}", stored.Descriptor.NameAccessor!); + Read(stored, $"[CultName] member {stored.Descriptor.NameMember}", stored.Descriptor.NameAccessor!) is { Length: > 0 } name ? name : null; private static string? Read(CultStoredDocument stored, string what, Func getter) {