diff --git a/src/GameCult.Caching.MessagePack/CultRecordRefFormatter.cs b/src/GameCult.Caching.MessagePack/CultRecordRefFormatter.cs index 1aa0968f..5a8ac630 100644 --- a/src/GameCult.Caching.MessagePack/CultRecordRefFormatter.cs +++ b/src/GameCult.Caching.MessagePack/CultRecordRefFormatter.cs @@ -3,15 +3,12 @@ using MessagePack.Formatters; namespace GameCult.Caching; -// An unset reference (the empty key) is nil on the wire and default(CultRecordRef) 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) in memory. Nil, written by 1.0.58 stores, reads as unset and saves as "". public sealed class CultRecordRefFormatter : IMessagePackFormatter> { - public void Serialize(ref MessagePackWriter writer, CultRecordRef value, MessagePackSerializerOptions options) - { - if (value.Key.Value.Length == 0) writer.WriteNil(); - else writer.Write(value.Key.Value); - } + public void Serialize(ref MessagePackWriter writer, CultRecordRef value, MessagePackSerializerOptions options) => + writer.Write(value.Key.Value); public CultRecordRef Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { diff --git a/src/GameCult.Caching/Contracts/cultcache-store-composition.md b/src/GameCult.Caching/Contracts/cultcache-store-composition.md index b24c83b3..ab028fca 100644 --- a/src/GameCult.Caching/Contracts/cultcache-store-composition.md +++ b/src/GameCult.Caching/Contracts/cultcache-store-composition.md @@ -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)`, -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)`, 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 diff --git a/tests/GameCult.Caching.Tests/SerializationOptionsTests.cs b/tests/GameCult.Caching.Tests/SerializationOptionsTests.cs index ff17d598..1b6dfe16 100644 --- a/tests/GameCult.Caching.Tests/SerializationOptionsTests.cs +++ b/tests/GameCult.Caching.Tests/SerializationOptionsTests.cs @@ -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(new CultRecordKey("other")) }, - new CultRecordKey("holder")); + await seed.UpsertAsync(typeof(UnsetRefHolder), new UnsetRefHolder { Name = "holder", Set = new CultRecordRef(new CultRecordKey("other")) }, key); await seed.FlushAsync(); } + var written = Convert.ToHexString(StoredPayload(path)); - var written = Payload(); - CultRecordRef unset; using (var reopened = new CultCache(registry)) { reopened.AddBackingStore(new SingleFileMessagePackBackingStore(path)); await reopened.PullAllBackingStoresAsync(); - var loaded = reopened.Get(new CultRecordKey("holder"))!; - unset = loaded.Unset; - await reopened.UpsertAsync(typeof(UnsetRefHolder), loaded, new CultRecordKey("holder")); + await reopened.UpsertAsync(typeof(UnsetRefHolder), reopened.Get(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))); - Assert.That(unset.Key, Is.EqualTo(new CultRecordKey("")), "default and \"\" are one empty key"); - var legacy = MessagePackSerializer.Serialize("", CultDocumentMessagePackSerialization.Options); - var read = MessagePackSerializer.Deserialize>(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)), "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(new CultRecordKey("alpha")); - var beta = new CultRecordRef(new CultRecordKey("beta")); + var handle = new CultRecordHandle(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(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(new CultRecordKey("holder")); + Dictionary, float> weights; + using (var reopened = new CultCache(registry)) + { + reopened.AddBackingStore(new SingleFileMessagePackBackingStore(path)); + await reopened.PullAllBackingStoresAsync(); + var loaded = reopened.Get(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(new CultRecordKey("alpha"))], Is.EqualTo(0.25f)); - Assert.That(loaded.Weights[new CultRecordRef(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, 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() {