CultCache: the moved-store write gate moves into CacheBackingStore; the directory store refuses a unique-indexed write onto a moved manifest (cs-directory-stale-write-gate)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 00:18:30 +01:00
commit 9d665db0b2
4 changed files with 285 additions and 81 deletions

View file

@ -64,7 +64,8 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
var reports = new List<CultSchemaMigrationReport>();
var loaded = new Dictionary<string, CultStoredDocument>(StringComparer.Ordinal);
var foreign = new List<CultForeignRecord>();
LoadManifestPages(null, loaded, reports, foreign, Trace);
var versions = new Dictionary<string, string>(StringComparer.Ordinal);
LoadManifestPages(null, loaded, reports, foreign, Trace, versions);
bool Staged(string key) => _dirtyKeys.ContainsKey(key) || _deletedKeys.ContainsKey(key);
var arrived = loaded
@ -88,6 +89,7 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
Entries[stored.Key.Value] = stored;
foreach (var key in loaded.Keys)
_hydratedKeys.Add(key);
ReadAllVersions(versions);
SetLastSchemaMigrationReports(reports);
SetForeignRecords(foreign);
@ -96,19 +98,22 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
}
// The one load of manifest pages, for the whole store (key null) or one record: under the lease, with the moved-manifest retry.
// It reads only; adopting what it loaded is the caller's.
// It reads only; adopting what it loaded is the caller's. A whole-store load (key null) also fills versions with every manifest
// record's version, claimed and foreign: what the store held when it was read.
private void LoadManifestPages(
string? key,
Dictionary<string, CultStoredDocument> loaded,
List<CultSchemaMigrationReport> reports,
List<CultForeignRecord> foreign,
Action<string> trace)
Action<string> trace,
Dictionary<string, string>? versions = null)
{
for (var attempt = 1; ; attempt++)
{
loaded.Clear();
reports.Clear();
foreign.Clear();
versions?.Clear();
// Only pages named by the manifest read under the lease are loaded; orphaned pages are never loaded. With no
// lock to lease (none created yet, or a store copied without it) a writer may commit mid-load, so an unleased
// load stands only if its manifest is still current; if the manifest moved it reloads, under the lease the
@ -117,6 +122,12 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
var manifestBytes = ReadManifestBytes();
var (manifest, _) = ParseManifest(manifestBytes);
trace($"manifest records={manifest.Records.Length}");
if (key == null)
{
foreach (var record in manifest.Records)
versions?.TryAdd(record.Key, VersionOf(record.Payload));
}
try
{
if (lease == null)
@ -221,6 +232,11 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
return CultCommitOutcome.Committed;
}
RefuseWriteIntoMovedManifest(
manifest,
request.Upserts,
StagedKeys.Concat(request.Upserts.Select(entry => entry.Key.Value)).Concat(request.Deletes.Select(entry => entry.Key.Value)));
var previousEntries = Entries.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal);
var previousDirtyKeys = _dirtyKeys.Keys.ToArray();
var previousDeletedKeys = _deletedKeys.Keys.ToArray();
@ -278,7 +294,10 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
return;
RefuseUndeclaredOnDisk(manifest, StagedKeys, Array.Empty<CultStoredDocument>(), Array.Empty<CultStoredDocument>(), Array.Empty<string>());
if (IsDirty)
{
RefuseWriteIntoMovedManifest(manifest, Array.Empty<CultStoredDocument>(), StagedKeys);
WriteGeneration(manifest, catalogBytes);
}
else
MarkFlushSucceeded();
});
@ -337,18 +356,51 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
HeldAt,
WrittenAt,
deletes.Select(entry => entry.Key.Value).Concat(checks),
key => HeldAt(key) is { } held && Foreign(held, currentManifest.SchemaCatalog, VersionOf(held.Payload)) == null
? LoadPage(held, currentManifest.SchemaCatalog, out _, out _)
: null,
key => HeldAt(key) is { } held ? ForeignAt(held, currentManifest.SchemaCatalog) : null,
key => DurableAt(currentManifest, key),
key => ForeignAt(currentManifest, key),
key =>
{
_dirtyKeys.TryRemove(key, out _);
_deletedKeys.TryRemove(key, out _);
IsDirty = !_dirtyKeys.IsEmpty || !_deletedKeys.IsEmpty;
Unstage(key);
if (HeldAt(key) is { } held)
Wrote(key, VersionOf(held.Payload));
else
Forgot(key);
});
}
// The record at a key as the manifest holds it, decoded as a load would; null when none, or when no registered type claims it.
private CultStoredDocument? DurableAt(CultPersistedStoreSnapshot manifest, string key) =>
manifest.Records.FirstOrDefault(record => string.Equals(record.Key, key, StringComparison.Ordinal)) is { } held &&
Foreign(held, manifest.SchemaCatalog, VersionOf(held.Payload)) == null
? LoadPage(held, manifest.SchemaCatalog, out _, out _)
: null;
private CultForeignRecord? ForeignAt(CultPersistedStoreSnapshot manifest, string key) =>
manifest.Records.FirstOrDefault(record => string.Equals(record.Key, key, StringComparison.Ordinal)) is { } held
? ForeignAt(held, manifest.SchemaCatalog)
: null;
private void Unstage(string key)
{
_dirtyKeys.TryRemove(key, out _);
_deletedKeys.TryRemove(key, out _);
IsDirty = !_dirtyKeys.IsEmpty || !_deletedKeys.IsEmpty;
}
// A write that lands a record of a type with a unique index, in the batch or already staged, lands only while the manifest it
// read under the commit lease is the one this store last read or wrote, whichever record moved (the one rule every store
// shares, CacheBackingStore.RefuseWriteIntoMovedStore). Variants are refused earlier, so only the unique-index arm applies.
private void RefuseWriteIntoMovedManifest(CultPersistedStoreSnapshot manifest, IEnumerable<CultStoredDocument> upserts, IEnumerable<string> writeKeys) =>
RefuseWriteIntoMovedStore(
() => manifest.Records.ToDictionary(record => record.Key, record => VersionOf(record.Payload), StringComparer.Ordinal),
gated: WritesUniqueIndex(
upserts.Select(entry => entry.Descriptor.SchemaId)
.Concat(_dirtyKeys.Keys.Select(key => Entries.TryGetValue(key, out var staged) ? staged.Descriptor.SchemaId : null).OfType<string>())),
writeKeys,
key => DurableAt(manifest, key),
key => ForeignAt(manifest, key),
Unstage);
// Runs under the commit lease: pages first, then the manifest that names them.
private void WriteGeneration(CultPersistedStoreSnapshot currentManifest, IReadOnlyDictionary<CultSchemaCatalogEntry, byte[]> catalogBytes)
{
@ -416,6 +468,11 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
DeleteUnreferencedRecordPages(currentIndex.Values);
// The manifest names what this store wrote now: that is what it last read of those keys.
foreach (var key in _deletedKeys.Keys)
Forgot(key);
foreach (var key in written)
Wrote(key, Entries[key].StoredVersion);
_dirtyKeys.Clear();
_deletedKeys.Clear();
MarkFlushSucceeded();

View file

@ -4563,6 +4563,97 @@ namespace GameCult.Caching
throw refusal(null);
}
// The version of every record the store held when this store last read it, as this store last wrote it for keys it wrote. A write
// that lands a variant or a record with a unique index lands only while the durable versions still equal these
// (RefuseWriteIntoMovedStore). Bookkeeping derived from reads and writes: it judges no value.
private readonly Dictionary<string, string> _lastRead = new(StringComparer.Ordinal);
// A whole-store read: the versions of every record the store held, replacing what was last read.
protected void ReadAllVersions(IEnumerable<KeyValuePair<string, string>> versions)
{
_lastRead.Clear();
foreach (var (key, version) in versions)
_lastRead[key] = version;
}
// This store wrote the record at a key, at this version.
protected void Wrote(string key, string version) => _lastRead[key] = version;
// This store removed the record at a key, or found the store holds none.
protected void Forgot(string key) => _lastRead.Remove(key);
// Whether any of the schema ids is a type that holds a unique index.
protected bool WritesUniqueIndex(IEnumerable<string> schemaIds) =>
AttachedRegistry is { } registry && schemaIds.Any(registry.HoldsUniqueIndex);
/// <summary>
/// The one refusal of a write into a store that moved since this store last read it, for every store kind, called under the
/// store's lock. A write that is <paramref name="gated"/> (it lands a variant or a record of a type with a unique index, which
/// resolve against other records and which a write cannot judge against records it did not read) lands only while every
/// record the store holds is at the version this store last read or wrote, whichever record it names; otherwise nothing is
/// written, what moved is reloaded through <see cref="Refuse"/>, and a <see cref="CultWriteConflictException"/> is thrown for
/// the cache's judge to retry against. Versions only: a write hashes other records' bytes, never decodes them.
/// </summary>
/// <param name="durableVersions">The version of every record the store holds, read under the lock; evaluated only when gated.</param>
/// <param name="gated">Whether the write lands a record this rule guards.</param>
/// <param name="writeKeys">Every key the write would write or remove, staged ones included.</param>
/// <param name="durableAt">See <see cref="Refuse"/>.</param>
/// <param name="foreignAt">See <see cref="Refuse"/>.</param>
/// <param name="unstage">See <see cref="Refuse"/>; the store's last-read version of the key is set from the durable one after it.</param>
protected void RefuseWriteIntoMovedStore(
Func<IReadOnlyDictionary<string, string>> durableVersions,
bool gated,
IEnumerable<string> writeKeys,
Func<string, CultStoredDocument?> durableAt,
Func<string, CultForeignRecord?> foreignAt,
Action<string> unstage)
{
if (!gated)
return;
var versions = durableVersions();
var changed = new HashSet<string>(StringComparer.Ordinal);
foreach (var (key, version) in versions)
{
if (!_lastRead.TryGetValue(key, out var read) || !SameStoredIdentity(read, version))
changed.Add(key);
}
foreach (var key in _lastRead.Keys)
{
if (!versions.ContainsKey(key))
changed.Add(key);
}
if (changed.Count == 0)
return;
var recordKeys = writeKeys.Distinct(StringComparer.Ordinal).OrderBy(key => key, StringComparer.Ordinal).ToArray();
var changedKeys = changed.OrderBy(key => key, StringComparer.Ordinal).ToArray();
Refuse(
recordKeys.Concat(changedKeys),
key => Cache == null ? null : durableAt(key),
foreignAt,
key =>
{
unstage(key);
if (versions.TryGetValue(key, out var version))
_lastRead[key] = version;
else
_lastRead.Remove(key);
},
inner => new CultWriteConflictException(
Cache == null
? $"{this} holds a variant or a unique index and was written by a writer with no CultCache, which cannot resolve variants; nothing was written. " +
$"Records it would have written or removed: {string.Join(", ", recordKeys.Select(key => $"'{key}'"))}; records that differ from what the writer has read: {string.Join(", ", changedKeys.Select(key => $"'{key}'"))}."
: $"{this} changed since this cache last read it, and it holds a variant or a record with a unique index, which resolve against other records; nothing was written. " +
$"Records this write would have written or removed: {string.Join(", ", recordKeys.Select(key => $"'{key}'"))}; records that changed: {string.Join(", ", changedKeys.Select(key => $"'{key}'"))}. " +
(inner == null
? "The cache reloaded them; retry the write against what the store holds now."
: "Reloading them failed, so the cache is unchanged."),
recordKeys,
changedKeys,
inner));
}
// Two stored records are the same stored bytes when their versions are equal. The one place a pull's reload filter, the
// staleness check and a refusal's reload decide it.
protected static bool SameStoredIdentity(string? version, string? otherVersion) =>
@ -4638,10 +4729,6 @@ namespace GameCult.Caching
// A key is staged exactly while the store is dirty with it, and a pull runs only on a clean store.
private readonly HashSet<string> _staged = new(StringComparer.Ordinal);
// The version of every record the store held when this store last read it, as this store last wrote it for keys it wrote.
// A write into a store holding a variant lands only while the durable versions still equal these.
private readonly Dictionary<string, string> _lastRead = new(StringComparer.Ordinal);
/// <summary>
/// A store file from its parts, each already encoded: a catalog entry or record this store carries forward is the bytes its
/// file held, one it writes is <see cref="SerializeCatalogEntry"/> or <see cref="SerializeRecord"/> of the object.
@ -4735,7 +4822,7 @@ namespace GameCult.Caching
var durable = ReadSnapshot();
if (durable == null)
{
_lastRead.Clear();
ReadAllVersions(Array.Empty<KeyValuePair<string, string>>());
SetLastSchemaMigrationReports(Array.Empty<CultSchemaMigrationReport>());
SetForeignRecords(Array.Empty<CultForeignRecord>());
return;
@ -4772,9 +4859,7 @@ namespace GameCult.Caching
Entries.TryRemove(stored.Key.Value, out _);
foreach (var stored in loaded)
Entries[stored.Key.Value] = stored;
_lastRead.Clear();
foreach (var (key, version) in versions)
_lastRead[key] = version;
ReadAllVersions(versions);
SetLastSchemaMigrationReports(reports);
SetForeignRecords(foreign);
}
@ -5050,9 +5135,9 @@ namespace GameCult.Caching
Directory.CreateDirectory(FileInfo.DirectoryName!);
WriteSnapshotAtomically(FileInfo.FullName, SerializeStore(format, catalog, fileRecords));
foreach (var key in removed)
_lastRead.Remove(key);
Forgot(key);
foreach (var (staged, version) in versions)
_lastRead[staged.Record.Key] = version;
Wrote(staged.Record.Key, version);
return versions;
}
@ -5093,58 +5178,21 @@ namespace GameCult.Caching
return false;
}
private void RefuseWriteIntoMovedStore(Durable? durable, IReadOnlyCollection<CultStagedRecord> upserts, IReadOnlyCollection<string> removals)
{
var records = durable?.Snapshot.Records ?? Array.Empty<CultPersistedRecord>();
if (records.All(record => record.Variant == null) && upserts.All(staged => staged.Record.Variant == null) &&
!upserts.Any(staged => AttachedRegistry?.HoldsUniqueIndex(staged.Entry.SchemaId) == true))
return;
var changed = new HashSet<string>(StringComparer.Ordinal);
var versions = records.ToDictionary(record => record.Key, record => durable!.Version(record.Key), StringComparer.Ordinal);
foreach (var (key, version) in versions)
{
if (!_lastRead.TryGetValue(key, out var read) || !SameStoredIdentity(read, version))
changed.Add(key);
}
var durableKeys = records.Select(record => record.Key).ToHashSet(StringComparer.Ordinal);
foreach (var key in _lastRead.Keys)
{
if (!durableKeys.Contains(key))
changed.Add(key);
}
if (changed.Count == 0)
return;
var recordKeys = _staged.Concat(upserts.Select(staged => staged.Record.Key)).Concat(removals)
.Distinct(StringComparer.Ordinal).OrderBy(key => key, StringComparer.Ordinal).ToArray();
var changedKeys = changed.OrderBy(key => key, StringComparer.Ordinal).ToArray();
Refuse(
recordKeys.Concat(changedKeys),
key => Cache == null ? null : DurableAt(durable, key),
private void RefuseWriteIntoMovedStore(Durable? durable, IReadOnlyCollection<CultStagedRecord> upserts, IReadOnlyCollection<string> removals) =>
RefuseWriteIntoMovedStore(
() => (durable?.Snapshot.Records ?? Array.Empty<CultPersistedRecord>())
.ToDictionary(record => record.Key, record => durable!.Version(record.Key), StringComparer.Ordinal),
gated: (durable?.Snapshot.Records ?? Array.Empty<CultPersistedRecord>()).Any(record => record.Variant != null) ||
upserts.Any(staged => staged.Record.Variant != null) ||
WritesUniqueIndex(upserts.Select(staged => staged.Entry.SchemaId)),
_staged.Concat(upserts.Select(staged => staged.Record.Key)).Concat(removals),
key => DurableAt(durable, key),
key => ForeignAt(durable, key),
key =>
{
_staged.Remove(key);
IsDirty = _staged.Count > 0;
if (versions.TryGetValue(key, out var version))
_lastRead[key] = version;
else
_lastRead.Remove(key);
},
inner => new CultWriteConflictException(
Cache == null
? $"{this} holds a variant or a unique index and was written by a writer with no CultCache, which cannot resolve variants; nothing was written. " +
$"Records it would have written or removed: {string.Join(", ", recordKeys.Select(key => $"'{key}'"))}; records that differ from what the writer has read: {string.Join(", ", changedKeys.Select(key => $"'{key}'"))}."
: $"{this} changed since this cache last read it, and it holds a variant or a record with a unique index, which resolve against other records; nothing was written. " +
$"Records this write would have written or removed: {string.Join(", ", recordKeys.Select(key => $"'{key}'"))}; records that changed: {string.Join(", ", changedKeys.Select(key => $"'{key}'"))}. " +
(inner == null
? "The cache reloaded them; retry the write against what the store holds now."
: "Reloading them failed, so the cache is unchanged."),
recordKeys,
changedKeys,
inner));
}
});
// A writable store judges a removal of a key its cache does not hold at its next flush or commit, under the lock (StageChecks);
// a read-only store has neither, so it answers from its view and never creates the lock file.
@ -5204,7 +5252,7 @@ namespace GameCult.Caching
{
_staged.Remove(key);
IsDirty = _staged.Count > 0;
_lastRead[key] = durable!.Version(key);
Wrote(key, durable!.Version(key));
},
cacheless: Cache == null);
}

View file

@ -37,7 +37,7 @@ Available cache attributes:
- `CultDocument(schemaName, schemaVersion)`
- `CultName`
- `CultIndex(alias?)`: a unique lookup. Within one document type, a non-blank value names one record; a commit that would leave two records holding one is refused, and a store holding such a pair refuses to load. Uniqueness is judged by a `CultCache` over the single-file store; a cacheless `WriteDocument`/`WriteRecord` of such a type is refused (also when the catalog declares an index alias the call cannot classify), and concurrent writers on a directory store are not covered (`unique-index-directory-store`). A value is culture-invariant, and a number is its canonical decimal (`1.0m` and `1.00m`, `0.0` and `-0.0` are one value).
- `CultIndex(alias?)`: a unique lookup. Within one document type, a non-blank value names one record; a commit that would leave two records holding one is refused, and a store holding such a pair refuses to load. Uniqueness is judged by a `CultCache` over the single-file store; a cacheless `WriteDocument`/`WriteRecord` of such a type is refused (also when the catalog declares an index alias the call cannot classify). A cache whose single-file or directory store another writer changed since it last read it gets `CultWriteConflictException` for a write of an indexed type, nothing written and the changed records reloaded; retry against them (`Update` retries on its own). A value is culture-invariant, and a number is its canonical decimal (`1.0m` and `1.00m`, `0.0` and `-0.0` are one value).
- `CultRole(alias?)`: a selection and reference role. Many records may share a value; it is never a lookup.
- `CultGlobal`
- `CultReference(targetType?, many: false)`

View file

@ -51,8 +51,20 @@ namespace GameCult.Caching.Tests
private string PathOf(string name) => Path.Combine(_directory, name);
private static CultCache Open(string path, CultDocumentRegistry? registry = null) =>
CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = registry ?? Registry });
private static CultCache Open(string path, CultDocumentRegistry? registry = null) => Open(path, StoreKind.SingleFile, registry);
// The same cache over either store kind at one path: the rule under test is the base store's, so both kinds answer to it.
public enum StoreKind { SingleFile, Directory }
private static CultCache Open(string path, StoreKind kind, CultDocumentRegistry? registry = null)
{
registry ??= Registry;
if (kind == StoreKind.SingleFile)
return CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = registry });
var cache = new CultCache(registry, CultCacheMessagePack.CreateCodec(registry));
cache.AddBackingStore(new DirectoryMessagePackBackingStore(path));
return cache;
}
private static CultRecordKey Key(string name) => new(name);
@ -239,13 +251,13 @@ namespace GameCult.Caching.Tests
}
[Test]
public void AWriteOntoAMovedFileIsAConflictAndTheRetryIsRefused()
public void AWriteOntoAMovedStoreIsAConflictAndTheRetryIsRefused([Values] StoreKind kind)
{
var path = PathOf("items.cc");
using var seed = Open(path);
using var seed = Open(path, kind);
seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a")));
using var second = Open(path);
using (var first = Open(path))
using var second = Open(path, kind);
using (var first = Open(path, kind))
first.Commit(batch => batch.Upsert(typeof(UqItem), Item(Canary), Key("b")));
var conflict = Assert.Throws<CultWriteConflictException>(
@ -256,11 +268,98 @@ namespace GameCult.Caching.Tests
var retry = Refused(() => second.Commit(batch => batch.Upsert(typeof(UqItem), Item(Canary), Key("c"))));
Assert.That(retry.Message, Does.Contain("b").And.Contain("c").And.Not.Contain(Canary));
using var reopened = Open(path);
Assert.That(reopened.Get(Key("c")), Is.Null, "the file never holds the pair");
using var reopened = Open(path, kind);
Assert.That(reopened.Get(Key("c")), Is.Null, "the store never holds the pair");
Assert.That(reopened.Get(Key("b")), Is.Not.Null);
}
// The flush path: a staged upsert is judged when it flushes, under the store's lock, against the store as it is then.
[Test]
public void AFlushOntoAMovedDirectoryStoreIsAConflict()
{
var path = PathOf("items.cc");
using var seed = Open(path, StoreKind.Directory);
seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a")));
using var second = Open(path, StoreKind.Directory);
using (var first = Open(path, StoreKind.Directory))
first.Commit(batch => batch.Upsert(typeof(UqItem), Item(Canary), Key("b")));
second.Upsert(Item(Canary), new CultRecordHandle<UqItem>(Key("c")));
Assert.Throws<CultWriteConflictException>(() => second.FlushAllBackingStores());
using var reopened = Open(path, StoreKind.Directory);
Assert.That(reopened.Get(Key("c")), Is.Null, "the store never holds the pair");
Assert.That(reopened.Get(Key("b")), Is.Not.Null);
}
// Whole-store rule, as in the single-file store and the Rust one: another writer's change to a record of any type refuses an
// indexed write, because the write cannot know which of the records it did not read bear on its value.
[Test]
public void AnUnrelatedRecordMovedByAnotherWriterStillRefusesAnIndexedWrite([Values] StoreKind kind)
{
var path = PathOf("items.cc");
using var seed = Open(path, kind);
seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a")));
using var second = Open(path, kind);
using (var first = Open(path, kind))
first.Commit(batch => batch.Upsert(typeof(UqTagged), new UqTagged { Kind = "k" }, Key("tag")));
Assert.Throws<CultWriteConflictException>(
() => second.Commit(batch => batch.Upsert(typeof(UqItem), Item("fresh"), Key("c"))));
Assert.That(second.Get(Key("tag")), Is.Not.Null, "the moved record is loaded");
Assert.That(second.Commit(batch => batch.Upsert(typeof(UqItem), Item("fresh"), Key("c"))), Is.True, "the retry against what the store holds lands");
}
// A type without an index is never gated, and the writes it lands are recorded as this cache's own: its next indexed write
// is refused only for what another writer moved, never for what it wrote itself.
[Test]
public void AWriteOfATypeWithoutAnIndexOntoAMovedDirectoryStoreMerges()
{
var path = PathOf("items.cc");
using var seed = Open(path, StoreKind.Directory);
seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a")));
using var second = Open(path, StoreKind.Directory);
using (var first = Open(path, StoreKind.Directory))
first.Commit(batch => batch.Upsert(typeof(UqTagged), new UqTagged { Kind = "one" }, Key("t1")));
Assert.That(second.Commit(batch => batch.Upsert(typeof(UqTagged), new UqTagged { Kind = "two" }, Key("t2"))), Is.True);
using (var reopened = Open(path, StoreKind.Directory))
{
Assert.That(reopened.Get(Key("t1")), Is.Not.Null);
Assert.That(reopened.Get(Key("t2")), Is.Not.Null);
}
Assert.Throws<CultWriteConflictException>(
() => second.Commit(batch => batch.Upsert(typeof(UqItem), Item("x"), Key("c"))), "t1 was never read by this cache");
Assert.That(second.Commit(batch => batch.Upsert(typeof(UqTagged), new UqTagged { Kind = "three" }, Key("t3"))), Is.True);
Assert.That(second.Commit(batch => batch.Upsert(typeof(UqItem), Item("x"), Key("c"))), Is.True, "only this cache wrote since it last read");
}
// A conflict costs Update an attempt, not an error: it applies again to what the store holds and lands.
[Test]
public void AnUpdateOnAMovedDirectoryStoreRetriesAndLands()
{
var path = PathOf("items.cc");
using var seed = Open(path, StoreKind.Directory);
seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a")));
using var cache = Open(path, StoreKind.Directory);
using var rival = Open(path, StoreKind.Directory);
var calls = 0;
var result = cache.Update<UqItem>(Key("c"), item =>
{
if (++calls == 1)
rival.Commit(batch => batch.Upsert(typeof(UqItem), Item("rival"), Key("b")));
return Item("mine");
});
Assert.That(result.Outcome, Is.EqualTo(CultUpdateOutcome.Updated));
Assert.That(calls, Is.EqualTo(2));
using var reopened = Open(path, StoreKind.Directory);
Assert.That(reopened.Get<UqItem>(Key("c"))!.Sku, Is.EqualTo("mine"));
Assert.That(reopened.Get<UqItem>(Key("b"))!.Sku, Is.EqualTo("rival"));
}
[Test]
public void CachelessWritesOfAUniqueIndexedTypeAreRefused()
{
@ -357,13 +456,13 @@ namespace GameCult.Caching.Tests
}
[Test]
public void AMixedBatchOntoAMovedFileIsAConflictWhateverItsOrder()
public void AMixedBatchOntoAMovedStoreIsAConflictWhateverItsOrder([Values] StoreKind kind)
{
var path = PathOf("items.cc");
using var seed = Open(path);
using var seed = Open(path, kind);
seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a")));
using var second = Open(path);
using (var first = Open(path))
using var second = Open(path, kind);
using (var first = Open(path, kind))
first.Commit(batch => batch.Upsert(typeof(UqItem), Item("moved"), Key("b")));
Assert.Throws<CultWriteConflictException>(() => second.Commit(batch =>