Merge hands/py-typed-leaves: C# leaf vectors (leaf-vectors-cs) and cultcache-py typed leaves that own each slot's C# type name and checks, held to them

leaf-vectors-cs Soul-held at pass 3 (cultlib-gaps:verdict:cut-leaf-vectors-cs.s3); py-typed-leaves Soul-held at pass 2 (cultlib-gaps:verdict:cut-py-typed-leaves.s2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-12 02:28:58 +02:00
commit b3bd8dd5e5
18 changed files with 1607 additions and 160 deletions

View file

@ -2,9 +2,11 @@
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GameCult.Caching.MessagePack;
using MessagePack;
using NUnit.Framework;
@ -18,12 +20,52 @@ namespace GameCult.Caching.Tests
{
private const string WriteVariable = "CULTCACHE_WRITE_VECTORS";
private static readonly string[] Leaves = { "int32", "int64", "float32", "float64" };
private static readonly string[] WideLeaves = { "string", "boolean", "bytes", "any", "list-string", "array-string", "nullable-int32", "list-int32", "record", "list-record", "union" };
[MessagePackObject] public sealed class Int32Slot { [Key(0)] public int V; }
[MessagePackObject] public sealed class Int64Slot { [Key(0)] public long V; }
[MessagePackObject] public sealed class Float32Slot { [Key(0)] public float V; }
[MessagePackObject] public sealed class Float64Slot { [Key(0)] public double V; }
// The wider leaves: one-slot records [value] for each kind of slot a document can declare.
[MessagePackObject] public sealed class StringSlot { [Key(0)] public string? V; }
[MessagePackObject] public sealed class BoolSlot { [Key(0)] public bool V; }
[MessagePackObject] public sealed class BytesSlot { [Key(0)] public byte[]? V; }
[MessagePackObject] public sealed class AnySlot { [Key(0)] public object? V; }
[MessagePackObject] public sealed class ListStringSlot { [Key(0)] public List<string>? V; }
[MessagePackObject] public sealed class ArrayStringSlot { [Key(0)] public string[]? V; }
[MessagePackObject] public sealed class NullableInt32Slot { [Key(0)] public int? V; }
[MessagePackObject] public sealed class ListInt32Slot { [Key(0)] public List<int>? V; }
[MessagePackObject] public sealed class LeafInner { [Key(0)] public string N = string.Empty; [Key(1)] public float W; }
[MessagePackObject] public sealed class RecordSlot { [Key(0)] public LeafInner? V; }
[MessagePackObject] public sealed class ListRecordSlot { [Key(0)] public List<LeafInner>? V; }
[Union(0, typeof(LeafCircle))] public interface ILeafShape { }
[MessagePackObject] public sealed class LeafCircle : ILeafShape { [Key(0)] public float R; }
[MessagePackObject] public sealed class UnionSlot { [Key(0)] public ILeafShape? V; }
// One member of every leaf kind: the record whose catalog rows and payload leaf-record.msgpack pins.
[CultDocument("cultcache.leaf-record", "cultcache.leaf_record.v1")]
[MessagePackObject]
public sealed class LeafRecord
{
[Key(0)] [CultName] public string Id = string.Empty;
[Key(1)] public bool Flag;
[Key(2)] public byte[] Blob = Array.Empty<byte>();
[Key(3)] public int I;
[Key(4)] public long L;
[Key(5)] public float F;
[Key(6)] public double D;
[Key(7)] public int? MaybeI;
[Key(8)] public List<string> Tags = new();
[Key(9)] public string[] Names = Array.Empty<string>();
[Key(10)] public object? Any;
[Key(11)] public LeafInner? Nested;
[Key(12)] public List<LeafInner> Items = new();
[Key(13)] public ILeafShape? Shape;
[Key(14)] public float[] Floats = Array.Empty<float>();
[Key(15)] public float? MaybeF;
}
// A record of every leaf kind, the shape a replicated document has.
[MessagePackObject]
public sealed class Mixed
@ -39,7 +81,7 @@ namespace GameCult.Caching.Tests
private static readonly MessagePackSerializerOptions Options = CultDocumentMessagePackSerialization.OptionsFor(typeof(NumericLeafVectorTests).Assembly);
private static string VectorPath(string name)
internal static string VectorPath(string name)
{
for (var dir = new DirectoryInfo(TestContext.CurrentContext.TestDirectory); dir != null; dir = dir.Parent)
{
@ -197,6 +239,120 @@ namespace GameCult.Caching.Tests
return buffer.WrittenSpan.ToArray();
}
// ---- the wider leaves: reads and one record of every leaf ----
// The value token of each wide read case, as MessagePack hex. c1 is a code no reader assigns; d40100 is an application ext, which the any leaf refuses; d6ff00000000, d7ff0000000000000000 and c70cff... are the timestamp32, timestamp64 and timestamp96 exts, which the any leaf reads, while d6fe00000000 and c70100ff are same-shaped non-timestamp exts, which it refuses; 92a161ca3f800000, 92a16105 and 92a161a162 give the record slots a float, an int and a str in the second slot.
private static readonly string[] WideValues =
{
"05", "ff", "cb3ff8000000000000", "ca3fc00000", "c0", "c2", "c3", "a161", "d90161", "c40100", "90", "9101", "91a161", "80", "81a161a162",
"920091ca3f800000", "9291a161ca3f800000", "9192a161ca3f800000", "c1",
"92a161ca3f800000", "92a16105", "92a161a162", "d40100",
"d6ff00000000", "d7ff0000000000000000", "c70cff000000000000000000000000", "d6fe00000000", "c70100ff",
};
// What the reference reads from a one-slot record of the leaf, and the bytes it writes back for what it read.
private static (bool Accepted, byte[] Rewrite) ReadWide(string leaf, byte[] payload) => leaf switch
{
"string" => Reread<StringSlot>(payload),
"boolean" => Reread<BoolSlot>(payload),
"bytes" => Reread<BytesSlot>(payload),
"any" => Reread<AnySlot>(payload),
"list-string" => Reread<ListStringSlot>(payload),
"array-string" => Reread<ArrayStringSlot>(payload),
"nullable-int32" => Reread<NullableInt32Slot>(payload),
"list-int32" => Reread<ListInt32Slot>(payload),
"record" => Reread<RecordSlot>(payload),
"list-record" => Reread<ListRecordSlot>(payload),
_ => Reread<UnionSlot>(payload),
};
private static (bool Accepted, byte[] Rewrite) Reread<T>(byte[] payload)
{
T value;
try
{
value = MessagePackSerializer.Deserialize<T>(payload, Options);
}
catch (Exception)
{
return (false, Array.Empty<byte>());
}
return (true, MessagePackSerializer.Serialize(value, Options));
}
// leaves-reads.msgpack: an array of [leaf, payload (bin), accepted, rewrite (bin: the reference's bytes for what it read, empty when refused)].
private static byte[] LeavesReadsVector()
{
var buffer = new ArrayBufferWriter<byte>();
var writer = new MessagePackWriter(buffer);
writer.WriteArrayHeader(WideLeaves.Length * WideValues.Length);
foreach (var leaf in WideLeaves)
foreach (var value in WideValues)
{
var payload = Payload(value);
var (accepted, rewrite) = ReadWide(leaf, payload);
writer.WriteArrayHeader(4);
writer.Write(leaf);
writer.Write(payload);
writer.Write(accepted);
writer.Write(rewrite);
}
writer.Flush();
return buffer.WrittenSpan.ToArray();
}
// Every float32 slot holds 0.1f, which float32 holds only as its own rounding, and the double slot 0.1, which float32 cannot hold; 1.5f is exact.
private static LeafRecord Everything() => new()
{
Id = "leaves", Flag = true, Blob = new byte[] { 1, 2, 3 }, I = -7, L = 5_000_000_000, F = 0.1f, D = 0.1, MaybeI = 9,
Tags = new List<string> { "a", "b" }, Names = new[] { "x", "y" }, Any = "text",
Nested = new LeafInner { N = "inner", W = 0.1f }, Items = new List<LeafInner> { new() { N = "one", W = 0.1f }, new() { N = "two", W = 1.5f } },
Shape = new LeafCircle { R = 0.1f }, Floats = new[] { 0.1f, 1.5f }, MaybeF = 0.1f,
};
// leaf-record.msgpack: [members, payload]. members are the catalog rows the store writes for LeafRecord, each
// [slot, memberName, typeName, isReference, isMany, targetSchemaName, isName, indexAlias]; payload (bin) is the record's bytes in that store.
private static async Task<byte[]> LeafRecordVector()
{
var path = Path.Combine(Path.GetTempPath(), $"cultlib-leaf-record-{Guid.NewGuid():N}.cc");
try
{
var store = new SingleFileMessagePackBackingStore(path);
var cache = new CultCache();
cache.AddBackingStore(store);
await cache.AddAsync(Everything());
store.PushAll();
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path));
var members = snapshot.SchemaCatalog.Single(entry => entry.SchemaName == "cultcache.leaf-record").Members;
var buffer = new ArrayBufferWriter<byte>();
var writer = new MessagePackWriter(buffer);
writer.WriteArrayHeader(2);
writer.WriteArrayHeader(members.Length);
foreach (var member in members)
{
writer.WriteArrayHeader(8);
writer.Write(member.Slot);
writer.Write(member.MemberName);
writer.Write(member.TypeName);
writer.Write(member.IsReference);
writer.Write(member.IsMany);
writer.Write(member.TargetSchemaName);
writer.Write(member.IsName);
writer.Write(member.IndexAlias);
}
writer.Write(snapshot.Records.Single().Payload);
writer.Flush();
return buffer.WrittenSpan.ToArray();
}
finally
{
if (File.Exists(path)) File.Delete(path);
}
}
// ---- tests ----
[Test]
@ -229,6 +385,30 @@ namespace GameCult.Caching.Tests
Assert.That((read.Id, read.I, read.L, read.F, read.D), Is.EqualTo(("n1", 7, 8L, 1.5f, 2.5)));
}
[Test]
public void LeavesReadsVectorMatches() => Check("leaves-reads.msgpack", LeavesReadsVector());
[Test]
public async Task LeafRecordVectorMatches()
{
var written = await LeafRecordVector();
Check("leaf-record.msgpack", written);
var reader = new MessagePackReader(written);
Assert.That(reader.ReadArrayHeader(), Is.EqualTo(2));
Assert.That(reader.ReadArrayHeader(), Is.EqualTo(16), "one member per leaf");
}
[Test]
public void LeavesReadCoverEveryLeafAndBothOutcomes()
{
var rows = WideLeaves.SelectMany(leaf => WideValues.Select(value => (leaf, result: ReadWide(leaf, Payload(value))))).ToList();
foreach (var leaf in WideLeaves)
{
Assert.That(rows.Count(row => row.leaf == leaf && row.result.Accepted), Is.GreaterThan(0), $"{leaf} accepts");
Assert.That(rows.Count(row => row.leaf == leaf && !row.result.Accepted), Is.GreaterThan(0), $"{leaf} refuses");
}
}
[Test]
public void ReadsCoverEveryLeafAndBothOutcomes()
{

View file

@ -0,0 +1,93 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GameCult.Caching.MessagePack;
using NUnit.Framework;
namespace GameCult.Caching.Tests
{
// The reference opens a store a Python typed-leaf definition (cultcache-py) wrote. The stores are vectors written only
// by cultcache-py's PythonWrittenStoreVectorTests (CULTCACHE_WRITE_VECTORS=1), values authored in Python.
public class PythonWrittenStoreTests
{
private static string Store(string name, string scratch)
{
var copy = Path.Combine(scratch, name);
File.Copy(NumericLeafVectorTests.VectorPath(Path.Combine("py-store", name)), copy, true);
return copy;
}
[Test]
public async Task APythonWrittenTypedLeafStoreOpensWithEverySlotItsCSharpValue()
{
var scratch = Directory.CreateTempSubdirectory().FullName;
try
{
var cache = new CultCache();
cache.AddBackingStore(new SingleFileMessagePackBackingStore(Store("leaf-record.cc", scratch)));
await cache.PullAllBackingStoresAsync();
var doc = cache.AllEntries.OfType<NumericLeafVectorTests.LeafRecord>().Single();
static int Bits(float f) => BitConverter.SingleToInt32Bits(f);
Assert.Multiple(() =>
{
Assert.That(doc.Id, Is.EqualTo("py"));
Assert.That(doc.Flag, Is.False);
Assert.That(doc.Blob, Is.EqualTo(new byte[] { 1, 0xff }));
Assert.That(doc.I, Is.EqualTo(int.MinValue));
Assert.That(doc.L, Is.EqualTo(long.MaxValue));
Assert.That(Bits(doc.F), Is.EqualTo(Bits(0.1f)));
Assert.That(doc.D, Is.EqualTo(1e-300));
Assert.That(doc.MaybeI, Is.Null);
Assert.That(doc.Tags, Is.Empty);
Assert.That(doc.Names, Is.EqualTo(new[] { "é", "z" }));
var any = (IDictionary<object, object>)doc.Any!;
Assert.That(Convert.ToInt64(any["n"]), Is.EqualTo(-3));
var k = (object[])any["k"];
Assert.That(Convert.ToInt64(k[0]), Is.EqualTo(1));
Assert.That(k[1], Is.EqualTo(true));
Assert.That(k[2], Is.Null);
Assert.That(k[3], Is.EqualTo(2.5));
Assert.That(k[4], Is.EqualTo("s"));
Assert.That(doc.Nested, Is.Null);
Assert.That(doc.Items.Select(i => i.N), Is.EqualTo(new[] { "one", "two" }));
Assert.That(Bits(doc.Items[0].W), Is.EqualTo(Bits((float)(9007199254740992L + 536870913L))));
Assert.That(Bits(doc.Items[1].W), Is.EqualTo(Bits(1e-40f)));
Assert.That(Bits(((NumericLeafVectorTests.LeafCircle)doc.Shape!).R), Is.EqualTo(Bits(0.1f)));
Assert.That(doc.Floats.Select(Bits), Is.EqualTo(new[] { 0.1f, 3f, -0.0f, float.PositiveInfinity }.Select(Bits)));
Assert.That(doc.MaybeF, Is.Null);
});
}
finally
{
Directory.Delete(scratch, true);
}
}
[TestCase(3)]
[TestCase(5)]
[TestCase(7)]
[TestCase(14)]
public async Task APythonWrittenCatalogNamingAnotherTypeForASlotIsRefused(int slot)
{
var scratch = Directory.CreateTempSubdirectory().FullName;
try
{
var cache = new CultCache();
var path = Store($"wrong-slot-{slot}.cc", scratch);
var error = Assert.CatchAsync<Exception>(async () =>
{
cache.AddBackingStore(new SingleFileMessagePackBackingStore(path));
await cache.PullAllBackingStoresAsync();
});
Assert.That(error!.Message, Does.Contain($"slot {slot} changed type"));
}
finally
{
Directory.Delete(scratch, true);
}
}
}
}

View file

@ -1,11 +1,14 @@
# numeric-leaves vectors
Written only by the C# reference, `tests/GameCult.Caching.Tests/NumericLeafVectorTests.cs`, with
Except `py-store/` (below), written only by the C# reference, `tests/GameCult.Caching.Tests/NumericLeafVectorTests.cs`, with
`CULTCACHE_WRITE_VECTORS=1`. Every other run reads these files and compares them byte for byte; a changed vector is a
reviewed commit. Other runtimes decode them and are held to the same answers.
A document with one slot, `[value]`, whose slot is a C# `int`, `long`, `float` or `double` (leaf `int32`, `int64`,
`float32`, `float64`).
These vectors hold every leaf kind, not only numbers. A document with one slot, `[value]`, whose slot is a C# `int`,
`long`, `float` or `double` (leaf `int32`, `int64`, `float32`, `float64`), or a `string`, `bool`, `byte[]`, `object`,
`List<string>`, `string[]`, `int?`, `List<int>`, a two-slot record class, a `List` of it or a `[Union]` interface (leaf
`string`, `boolean`, `bytes`, `any`, `list-string`, `array-string`, `nullable-int32`, `list-int32`, `record`, `list-record`,
`union`).
- `reads.msgpack`: an array of `[leaf, payload, accepted, bits]`. `payload` (bin) is the one-slot record fed to the
reference; `accepted` is whether it read; `bits` (bin, 8 bytes, big-endian) is the int64 it read, or the IEEE bits of
@ -14,3 +17,23 @@ A document with one slot, `[value]`, whose slot is a C# `int`, `long`, `float` o
bits in hex for a float leaf; `bytes` (bin) is the one-slot record the reference writes for that value.
- `float32-nan.msgpack`: an array of `[payload, bytes]`. `payload` (bin) is a one-slot `float` record holding an infinity
or a NaN; `bytes` (bin) is what the reference writes after reading it. It keeps every bit, a signalling NaN's included.
- `leaves-reads.msgpack`: an array of `[leaf, payload, accepted, rewrite]` for the wider leaves. `payload` (bin) is the
one-slot record `[token]` fed to the reference; `accepted` is whether it read; `rewrite` (bin) is what the reference
writes after reading it, and empty when refused. Every token is fed to every leaf: 11 leaves x 28 tokens, 308 rows.
The tokens include an application ext (`d40100`, which the `any` leaf refuses), the timestamp exts (`d6ff00000000`,
`d7ff0000000000000000`, `c70cff000000000000000000000000`, which the `any` leaf reads and rewrites as `91d6ff00000000`),
same-shaped non-timestamp exts (`d6fe00000000`, `c70100ff`, which it refuses), and complete, int-in-float-slot and
str-in-float-slot two-slot records.
On the `any` leaf's rewrite rows a sibling is held to the rewrite's value kind (nil, bool, int, float, str, bin, array, map; bool,
int and float are distinct, so `true`, `1` and `1.0` never match) and its exact value, recursively, not to its MessagePack numeric
width (the reference widens a boxed fixint, so the record `9105` rewrites as `91cc05`, and a float 32 as a float 64; ruling
`cultlib-gaps:ruling:any-rewrite-binds-kind-and-value`).
Every other leaf's rewrite binds bytes.
- `leaf-record.msgpack`: `[members, payload]` for one `cultcache.leaf-record` document holding every leaf. `members` are
the catalog rows the single-file store writes, each `[slot, memberName, typeName, isReference, isMany,
targetSchemaName, isName, indexAlias]`; `payload` (bin) is the record's bytes in that store.
- `py-store/`: single-file stores written only by cultcache-py (`PythonWrittenStoreVectorTests` in `test_typed_leaves.py`, with
`CULTCACHE_WRITE_VECTORS=1`), never by C#. `leaf-record.cc` holds one `cultcache.leaf-record` document authored in Python; the
reference (`PythonWrittenStoreTests`) opens it and asserts every field. `wrong-slot-N.cc` is the same store whose catalog names
another C# type for slot N (3, 5, 7, 14); the reference refuses each with `slot N changed type`.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.