CultCache C#: a public Clock for reproducible stores (#190)

This commit is contained in:
Eureka 2026-11-28 02:48:44 +00:00
commit 00e457050c
4 changed files with 69 additions and 2 deletions

View file

@ -2976,8 +2976,15 @@ namespace GameCult.Caching
throw new ArgumentException($"Expect({key.Value}) was given an instance this cache does not hold at that key.", nameof(current));
}
// The wall clock behind every storedAt. Internal: a test that writes a golden store pins it, so the bytes reproduce.
internal Func<DateTimeOffset> Clock { get; set; } = () => DateTimeOffset.UtcNow;
private Func<DateTimeOffset> _clock = () => DateTimeOffset.UtcNow;
/// <summary>The clock behind every <c>storedAt</c> this cache and its attached stores mint. Defaults to <see cref="DateTimeOffset.UtcNow"/>. Pin it to write reproducible stores: two caches with the same pinned clock replay the same writes into the same bytes, provided the keys and element ids are the consumer's too (a keyless add mints a random key, and an unset element id is minted at random on write; set them, or derive element ids). A replacing write is still stamped later than the record it replaces, per key, so a pinned clock advances one tick per rewrite. A detached store, which has no cache, restamps from the wall clock.</summary>
/// <exception cref="ArgumentNullException">The value is null.</exception>
public Func<DateTimeOffset> Clock
{
get => _clock;
set => _clock = value ?? throw new ArgumentNullException(nameof(value), "A cache's clock cannot be null.");
}
internal static string MintStoredAt(string? previous, DateTimeOffset now)
{

View file

@ -125,6 +125,20 @@ Each persisted record carries:
- `storedAt`
- `payload`
### Reproducible stores
`CultCache.Clock` is the clock behind every `storedAt` a cache and its attached stores mint (default
`DateTimeOffset.UtcNow`; setting null throws). Pin it to write reproducible stores. A replacing write is still stamped
later than the record it replaces, per key, so a pinned clock advances one tick per rewrite. Two stores written by the
same pinned-clock replay are byte-identical when three things hold: the clock is pinned, every record key is the
consumer's (a keyless add mints a random key), and every element id is set by the consumer or derived (an unset id is
minted at random on a cache write; `[CultElementId(nameof(Name))]` derives it from the element).
```csharp
var cache = await CultCacheMessagePack.OpenAsync("Data.msgpack");
cache.Clock = () => new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
```
## Happy Path
```csharp

View file

@ -65,5 +65,50 @@ namespace GameCult.Caching.Tests
Upsert(cache);
Assert.That(Upsert(cache), Is.EqualTo("2026-01-01T00:00:00.0000001+00:00"), "the same instant again is one tick later");
}
private static readonly CultDocumentRegistry DeckRegistry = CultDocumentRegistry.ForTypes(new[] { typeof(ElementIdTests.IdDeck) });
private static readonly DateTimeOffset Pinned = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
private static ElementIdTests.IdDeck Deck(string? reelId) => new()
{
Name = "deck",
Reels = { new ElementIdTests.IdReel { Label = "reel", Id = reelId ?? string.Empty, Marks = { new ElementIdTests.IdMark { Text = "m", Id = "00000000c10a" } } } }
};
// Replays the same keyed writes (a write, then a replacement) into a fresh store file and returns the file's bytes.
private byte[] Replay(string name, string? reelId)
{
var path = Path.Combine(_directory, name);
using (var cache = CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = DeckRegistry }))
{
cache.Clock = () => Pinned;
cache.Commit(batch => batch.Upsert(typeof(ElementIdTests.IdDeck), Deck(reelId), new CultRecordKey("deck")));
cache.FlushAsync().GetAwaiter().GetResult();
cache.Commit(batch => batch.Upsert(typeof(ElementIdTests.IdDeck), Deck(reelId), new CultRecordKey("deck")));
cache.FlushAsync().GetAwaiter().GetResult();
}
return File.ReadAllBytes(path);
}
[Test]
public void TwoReplaysWithAPinnedClockWriteIdenticalBytes()
{
Assert.That(Replay("a.cc", "00000000c10b"), Is.EqualTo(Replay("b.cc", "00000000c10b")));
}
[Test]
public void AnUnsetElementIdBreaksByteIdentity()
{
Assert.That(Replay("a.cc", null), Is.Not.EqualTo(Replay("b.cc", null)), "a write mints an unset element id at random");
}
[Test]
public void SettingANullClockThrows()
{
using var cache = Open();
Assert.Throws<ArgumentNullException>(() => cache.Clock = null!);
Assert.That(Upsert(cache), Is.Not.Null, "the refused value left the clock as it was");
}
}
}

View file

@ -16,6 +16,7 @@ All notable changes to this package are documented in this file.
### Added
- `CultCache.Clock` is public: the clock behind every `storedAt` the cache and its attached stores mint (default `DateTimeOffset.UtcNow`; null throws). Pin it to write reproducible stores. Byte-identity also needs consumer-set keys and element ids, because a cache write mints an unset element id and a keyless add's key at random.
- `CultCache.IsWritable(CultRecordKey)`: whether a removal of the key, or a write of the record's own type, would be let through, answered by the write's own decision: false for a foreign record, undeclared drift that drops slots, unread slots, a read-only home store, or a record no attached store is home to; true for a key the cache does not hold unless a store lists it foreign. It does not predict a `Flatten` refused for its base chain. Live and advisory: the write still decides.
- `CultUnreadSlots` (`TypeName`, `SlotCount`, `DeclaredCount`, `Occurrences`, `Explained`), `CultStoredDocument.UnreadSlots`, and `CultSchemaConflictException.UnreadSlots` with its constructor overload: what a load found past the reader's slots, holding no slot value. The refusal message names the type and both counts, never a value.