Write an unset CultRecordRef as "" in every position

452f928 made nil the unset wire form, including dictionary keys: a
Dictionary<CultRecordRef<H>, float> holding the empty key encoded it as C0.
Python msgpack refuses nil map keys under strict_map_key, its default, so
cultcache-py cannot decode such a record. Nil cannot be the one canonical
form; "" can, and every runtime reads it.

The writer always writes "". The reader still takes nil as unset, because
452f928/b85a828 stores and Aetheria's Cut 9 import wrote nil; such a record
converts to "" on its next save and is byte-stable after that. The
store-composition contract names "" for value and key position, requires
readers to accept nil, and tells other runtimes to write "".

The tests pin payload bytes, so each claim is consequential: an unset ref
writes "", reloads through a fresh cache and resaves byte-identical; a
nil-written legacy payload reads as unset and resaves as ""; a ref-keyed
dictionary with an empty key writes "", reads back unset and resaves
byte-identical. The nil writer fails every byte assertion, a reader taking
nil as a set key fails the legacy pair, and a reader taking "" as a set key
fails the read-back assertions.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-14 21:34:23 +02:00
commit a92381e589
3 changed files with 59 additions and 42 deletions

View file

@ -3,15 +3,12 @@ using MessagePack.Formatters;
namespace GameCult.Caching;
// An unset reference (the empty key) is nil on the wire and default(CultRecordRef<T>) in memory; a "" read from older
// stores is the same unset reference, so load then save is byte-stable.
// An unset reference (the empty key) is "" on the wire in every position, map keys included (other runtimes refuse nil
// map keys), and default(CultRecordRef<T>) in memory. Nil, written by 1.0.58 stores, reads as unset and saves as "".
public sealed class CultRecordRefFormatter<T> : IMessagePackFormatter<CultRecordRef<T>>
{
public void Serialize(ref MessagePackWriter writer, CultRecordRef<T> value, MessagePackSerializerOptions options)
{
if (value.Key.Value.Length == 0) writer.WriteNil();
else writer.Write(value.Key.Value);
}
public void Serialize(ref MessagePackWriter writer, CultRecordRef<T> value, MessagePackSerializerOptions options) =>
writer.Write(value.Key.Value);
public CultRecordRef<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{

View file

@ -239,13 +239,15 @@ another runtime need not obey the `storedAt` rule.
## Record references
A record reference is its target's key string. An unset reference, the empty
key, is **nil** on the wire, never `""`. A reader takes nil and `""` as the same
unset reference and writes it back as nil, so loading and re-saving an unchanged
record is byte-stable. In C# the unset reference is `default(CultRecordRef<T>)`,
equal to one built from `""`; `CultRecordKey.Value` is never null. Rust,
TypeScript and Python have no reference type: a reference member is a string in
the consumer's own payload value, so a consumer writes an unset one as its
language's null (`null`, `None`, `Option::None`), not as an empty string.
key, is **`""`** on the wire in value and map-key position alike. Nil cannot be
the form: msgpack readers in other runtimes (Python under `strict_map_key`)
refuse nil map keys. Readers must also accept nil as unset, because C# 1.0.58
stores wrote it; the writer always writes `""`, so such a record converts on its
next save and is byte-stable after that. In C# the unset reference is
`default(CultRecordRef<T>)`, equal to one built from `""`;
`CultRecordKey.Value` is never null. Rust, TypeScript and Python have no
reference type: a reference member is a string in the consumer's own payload,
and a consumer writes an unset one as `""`.
## Value-type encoding

View file

@ -38,41 +38,47 @@ namespace GameCult.Caching.Tests
Assert.That(Convert.ToHexString(payload), Is.EqualTo(InteropNotePayloadHex));
}
// An unset reference is "" (A0) on the wire. Legacy is the same record as 1.0.58 wrote it, with nil (C0).
private const string UnsetRefPayloadHex = "93A6686F6C646572A0A56F74686572";
private const string UnsetRefLegacyPayloadHex = "93A6686F6C646572C0A56F74686572";
// A ref-keyed dictionary whose unset key is "" (A0): msgpack readers under strict_map_key refuse a nil key.
private const string RefKeyedPayloadHex = "92A6686F6C64657282A5616C706861CA3E800000A0CA40000000";
[Test]
public async Task UnsetRefReloadsAndResavesByteIdentical()
public async Task UnsetRefWritesEmptyStringAndResavesByteIdentical()
{
var path = Path.Combine(Path.GetTempPath(), $"cultlib-unsetref-{Guid.NewGuid():N}.cc");
var registry = CultDocumentRegistry.ForTypes(new[] { typeof(UnsetRefHolder) });
byte[] Payload() => CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)).Records.Single().Payload;
var key = new CultRecordKey("holder");
try
{
using (var seed = new CultCache(registry))
{
seed.AddBackingStore(new SingleFileMessagePackBackingStore(path));
await seed.UpsertAsync(typeof(UnsetRefHolder), new UnsetRefHolder { Name = "holder", Set = new CultRecordRef<UnsetRefHolder>(new CultRecordKey("other")) },
new CultRecordKey("holder"));
await seed.UpsertAsync(typeof(UnsetRefHolder), new UnsetRefHolder { Name = "holder", Set = new CultRecordRef<UnsetRefHolder>(new CultRecordKey("other")) }, key);
await seed.FlushAsync();
}
var written = Convert.ToHexString(StoredPayload(path));
var written = Payload();
CultRecordRef<UnsetRefHolder> unset;
using (var reopened = new CultCache(registry))
{
reopened.AddBackingStore(new SingleFileMessagePackBackingStore(path));
await reopened.PullAllBackingStoresAsync();
var loaded = reopened.Get<UnsetRefHolder>(new CultRecordKey("holder"))!;
unset = loaded.Unset;
await reopened.UpsertAsync(typeof(UnsetRefHolder), loaded, new CultRecordKey("holder"));
await reopened.UpsertAsync(typeof(UnsetRefHolder), reopened.Get<UnsetRefHolder>(key)!, key);
await reopened.FlushAsync();
}
var resaved = Convert.ToHexString(StoredPayload(path));
Assert.That(Payload(), Is.EqualTo(written), "an unset reference loads and re-saves byte-identical");
Assert.That(unset, Is.EqualTo(default(CultRecordRef<UnsetRefHolder>)));
Assert.That(unset.Key, Is.EqualTo(new CultRecordKey("")), "default and \"\" are one empty key");
var legacy = MessagePackSerializer.Serialize("", CultDocumentMessagePackSerialization.Options);
var read = MessagePackSerializer.Deserialize<CultRecordRef<UnsetRefHolder>>(legacy, CultDocumentMessagePackSerialization.Options);
Assert.That(MessagePackSerializer.Serialize(read, CultDocumentMessagePackSerialization.Options), Is.EqualTo(new[] { MessagePackCode.Nil }),
"a \"\" reference reads as unset and writes nil");
var legacy = (UnsetRefHolder)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(UnsetRefHolder), Convert.FromHexString(UnsetRefLegacyPayloadHex), registry);
var legacyResaved = Convert.ToHexString(CultDocumentMessagePackSerialization.SerializeUntyped(legacy, typeof(UnsetRefHolder), registry));
Assert.Multiple(() =>
{
Assert.That(written, Is.EqualTo(UnsetRefPayloadHex), "the writer writes an unset reference as \"\"");
Assert.That(resaved, Is.EqualTo(UnsetRefPayloadHex), "reloaded through a fresh cache, it resaves byte-identical");
Assert.That(legacy.Unset, Is.EqualTo(default(CultRecordRef<UnsetRefHolder>)), "a nil reference reads as unset");
Assert.That(legacyResaved, Is.EqualTo(UnsetRefPayloadHex), "a nil reference resaves as \"\"");
});
}
finally
{
@ -81,31 +87,40 @@ namespace GameCult.Caching.Tests
}
[Test]
public async Task RefKeyedDictionaryRoundTrips()
public async Task RefKeyedDictionaryWithUnsetKeyRoundTripsByteIdentical()
{
var path = Path.Combine(Path.GetTempPath(), $"cultlib-refkeyed-{Guid.NewGuid():N}.cc");
var registry = CultDocumentRegistry.ForTypes(new[] { typeof(RefKeyedHolder) });
var alpha = new CultRecordRef<RefKeyedHolder>(new CultRecordKey("alpha"));
var beta = new CultRecordRef<RefKeyedHolder>(new CultRecordKey("beta"));
var handle = new CultRecordHandle<RefKeyedHolder>(new CultRecordKey("holder"));
try
{
using (var cache = new CultCache(registry))
{
cache.AddBackingStore(new SingleFileMessagePackBackingStore(path));
await cache.UpsertAsync(
new RefKeyedHolder { Name = "holder", Weights = new() { [alpha] = 0.25f, [beta] = 2f } },
new CultRecordHandle<RefKeyedHolder>(new CultRecordKey("holder")));
await cache.UpsertAsync(new RefKeyedHolder { Name = "holder", Weights = new() { [alpha] = 0.25f, [default] = 2f } }, handle);
cache.FlushAllBackingStores();
}
var written = Convert.ToHexString(StoredPayload(path));
using var reopened = new CultCache(registry);
reopened.AddBackingStore(new SingleFileMessagePackBackingStore(path));
await reopened.PullAllBackingStoresAsync();
var loaded = reopened.Get<RefKeyedHolder>(new CultRecordKey("holder"));
Dictionary<CultRecordRef<RefKeyedHolder>, float> weights;
using (var reopened = new CultCache(registry))
{
reopened.AddBackingStore(new SingleFileMessagePackBackingStore(path));
await reopened.PullAllBackingStoresAsync();
var loaded = reopened.Get<RefKeyedHolder>(handle.Key)!;
weights = loaded.Weights;
await reopened.UpsertAsync(loaded, handle);
reopened.FlushAllBackingStores();
}
var resaved = Convert.ToHexString(StoredPayload(path));
Assert.That(loaded, Is.Not.Null);
Assert.That(loaded!.Weights[new CultRecordRef<RefKeyedHolder>(new CultRecordKey("alpha"))], Is.EqualTo(0.25f));
Assert.That(loaded.Weights[new CultRecordRef<RefKeyedHolder>(new CultRecordKey("beta"))], Is.EqualTo(2f));
Assert.Multiple(() =>
{
Assert.That(written, Is.EqualTo(RefKeyedPayloadHex), "the unset key is written as \"\"");
Assert.That(weights, Is.EqualTo(new Dictionary<CultRecordRef<RefKeyedHolder>, float> { [alpha] = 0.25f, [default] = 2f }), "the unset key reads back unset");
Assert.That(resaved, Is.EqualTo(RefKeyedPayloadHex), "reloaded, it resaves byte-identical");
});
}
finally
{
@ -113,6 +128,9 @@ namespace GameCult.Caching.Tests
}
}
private static byte[] StoredPayload(string path) =>
CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)).Records.Single().Payload;
[Test]
public void DeclaredResolverEncodesValueTypeAsPositionalArray()
{