From b7f2a7dbd01c9066368868b56323c8f6939b7fc0 Mon Sep 17 00:00:00 2001 From: Eureka Date: Fri, 27 Nov 2026 21:43:15 +0000 Subject: [PATCH] Vectors: catalog member rows across C#, Rust, TypeScript and Python (#185) --- .../tests/test_catalog_members.py | 51 ++++ .../cultcache-rs/tests/catalog_members.rs | 248 ++++++++++++++++ .../cultcache-ts/test/catalog-members.test.ts | 47 +++ .../CatalogMemberVectorTests.cs | 268 ++++++++++++++++++ tests/vectors/catalog-members/README.md | 62 ++++ .../catalog-members/csharp-members-store.cc | Bin 0 -> 6942 bytes tests/vectors/catalog-members/members.json | 31 ++ .../rust-members-empty-store.cc | Bin 0 -> 683 bytes 8 files changed, 707 insertions(+) create mode 100644 packages/cultcache-py/tests/test_catalog_members.py create mode 100644 packages/cultcache-rs/tests/catalog_members.rs create mode 100644 packages/cultcache-ts/test/catalog-members.test.ts create mode 100644 tests/GameCult.Caching.Tests/CatalogMemberVectorTests.cs create mode 100644 tests/vectors/catalog-members/README.md create mode 100644 tests/vectors/catalog-members/csharp-members-store.cc create mode 100644 tests/vectors/catalog-members/members.json create mode 100644 tests/vectors/catalog-members/rust-members-empty-store.cc diff --git a/packages/cultcache-py/tests/test_catalog_members.py b/packages/cultcache-py/tests/test_catalog_members.py new file mode 100644 index 00000000..1443214d --- /dev/null +++ b/packages/cultcache-py/tests/test_catalog_members.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import json +import shutil +import tempfile +import unittest +from pathlib import Path + +from cultcache_py import SingleFileMessagePackBackingStore + +# tests/vectors/catalog-members (variants:ruling:rs-catalog-member-rows-every-member): one record in two stores. The C# reference's +# publishes a catalog row for each of the 29 members, every one of which members.json spells; the one cultcache-rs wrote before it +# wrote member rows publishes members []. A reader takes both and pulls the one record m:1. +VECTORS = Path(__file__).resolve().parents[3] / "tests" / "vectors" / "catalog-members" + +# [slot, member, typeName, isReference, isMany, targetSchemaName, isName, indexAlias] +TABLE = json.loads((VECTORS / "members.json").read_text(encoding="utf-8")) + + +def pull(name: str): + directory = Path(tempfile.mkdtemp()) + copy = directory / "store.cc" + shutil.copyfile(VECTORS / name, copy) + try: + return SingleFileMessagePackBackingStore(copy).pull_all() + finally: + shutil.rmtree(directory, ignore_errors=True) + + +class CatalogMembersVectorTests(unittest.TestCase): + def test_the_csharp_written_store_publishes_every_row_of_the_shared_table(self) -> None: + envelopes = pull("csharp-members-store.cc") + self.assertEqual([envelope.key for envelope in envelopes], ["m:1"]) + entry = envelopes[0].catalog_entry + self.assertEqual(entry.schema_name, "tests.catalog_members") + self.assertEqual(len(TABLE), 29) + rows = [ + [m.slot, m.member_name, m.type_name, m.is_reference, m.is_many, m.target_schema_name, m.is_name, m.index_alias] + for m in entry.members + ] + self.assertEqual(rows, TABLE) + + def test_the_rust_written_store_publishes_no_members_and_one_record(self) -> None: + envelopes = pull("rust-members-empty-store.cc") + self.assertEqual([envelope.key for envelope in envelopes], ["m:1"]) + self.assertEqual(envelopes[0].catalog_entry.schema_name, "tests.catalog_members") + self.assertEqual(tuple(envelopes[0].catalog_entry.members), ()) + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/cultcache-rs/tests/catalog_members.rs b/packages/cultcache-rs/tests/catalog_members.rs new file mode 100644 index 00000000..08f276ee --- /dev/null +++ b/packages/cultcache-rs/tests/catalog_members.rs @@ -0,0 +1,248 @@ +//! `tests/vectors/catalog-members`: a record that holds a value in every member shape, in the two stores the vector folder +//! holds. `csharp-members-store.cc` is written by the C# reference and publishes one catalog row per member; +//! `rust-members-empty-store.cc` is written by this runtime as it stood at e503edf2, whose catalog entry holds `members []`. +//! Rust writes the second only under `CULTCACHE_WRITE_VECTORS=1` and it is never regenerated: it pins the bytes old Rust +//! wrote, so a runtime that reads a store with no member rows keeps reading one. Both stores must read back the same record. + +use std::path::PathBuf; + +use cultcache_rs::{CultCache, CultSlots, CultUnion, DatabaseEntry, SingleFileMessagePackBackingStore}; + +#[derive(Clone, Debug, PartialEq, CultSlots)] +struct CatalogMemberMark { + #[cultcache(key = 0)] + label: String, + #[cultcache(key = 1)] + weight: i32, + #[cultcache(key = 2)] + id: String, +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +struct CatalogMemberTextArm { + #[cultcache(key = 0)] + text: String, + #[cultcache(key = 1)] + id: String, +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +struct CatalogMemberCountArm { + #[cultcache(key = 0)] + count: i32, + #[cultcache(key = 1)] + id: String, +} + +#[derive(Clone, Debug, PartialEq, CultUnion)] +enum CatalogMemberArm { + #[cultcache(key = 0)] + Text(CatalogMemberTextArm), + #[cultcache(key = 1)] + Count(CatalogMemberCountArm), +} + +/// The slot a C# `DateTime` is: a MessagePack timestamp extension (type -1), kept as the bytes C# wrote. +#[derive(Clone, Debug, PartialEq)] +struct Timestamp(Vec); + +impl serde::Serialize for Timestamp { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_newtype_struct("_ExtStruct", &(-1i8, serde_bytes::Bytes::new(&self.0))) + } +} + +impl<'de> serde::Deserialize<'de> for Timestamp { + fn deserialize>(deserializer: D) -> Result { + struct Visit; + impl<'de> serde::de::Visitor<'de> for Visit { + type Value = Timestamp; + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a MessagePack extension") + } + fn visit_newtype_struct>(self, deserializer: D) -> Result { + let (tag, bytes): (i8, serde_bytes::ByteBuf) = serde::Deserialize::deserialize(deserializer)?; + if tag != -1 { + return Err(serde::de::Error::custom("not a timestamp extension")); + } + Ok(Timestamp(bytes.into_vec())) + } + } + deserializer.deserialize_newtype_struct("_ExtStruct", Visit) + } +} + +/// A field type that names no C# type: no `type_name` attribute, so the row the library cut writes for it is `System.Object`. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +struct Opaque(String); + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "tests.catalog_members", schema = "tests.catalog_members")] +struct CatalogMembers { + #[cultcache(key = 0, name)] + title: String, + #[cultcache(key = 1, index = "sku")] + sku: String, + #[cultcache(key = 2)] + count: i32, + #[cultcache(key = 3)] + total: u64, + #[cultcache(key = 4)] + ratio: f64, + #[cultcache(key = 5)] + scale: f32, + #[cultcache(key = 6)] + flag: bool, + #[cultcache(key = 7)] + maybe_count: Option, + #[cultcache(key = 8)] + note: Option, + #[cultcache(key = 9)] + tags: Vec, + #[cultcache(key = 10)] + labels: Vec, + #[cultcache(key = 11, bytes)] + raw: Vec, + #[cultcache(key = 12)] + chunks: Vec, + #[cultcache(key = 13)] + weights: std::collections::BTreeMap, + #[cultcache(key = 14)] + mark: CatalogMemberMark, + #[cultcache(key = 15)] + arm: CatalogMemberArm, + #[cultcache(key = 17)] + late: i64, + #[cultcache(key = 18)] + items: Vec, + #[cultcache(key = 19)] + marks: Vec, + #[cultcache(key = 20)] + by_label: std::collections::BTreeMap, + #[cultcache(key = 21)] + maybe_mark: Option, + #[cultcache(key = 22)] + arms: Vec, + #[cultcache(key = 23)] + grid: Vec>, + #[cultcache(key = 24)] + by_number: std::collections::BTreeMap, + #[cultcache(key = 25)] + kind: i32, + #[cultcache(key = 26)] + ident: String, + #[cultcache(key = 27)] + when: Timestamp, + #[cultcache(key = 28)] + price: String, + #[cultcache(key = 29)] + opaque: Opaque, +} + +fn expected() -> CatalogMembers { + CatalogMembers { + title: "Brass lantern".into(), + sku: "LAN-0042".into(), + count: -7, + total: 10_000_000_000, + ratio: 0.25, + scale: 1.5, + flag: true, + maybe_count: Some(3), + note: Some("handle with care".into()), + tags: vec!["fragile".into(), "lit".into()], + labels: vec!["a".into(), "b".into(), "c".into()], + raw: vec![0, 1, 2, 254, 255], + chunks: vec![serde_bytes::ByteBuf::from(vec![9, 8]), serde_bytes::ByteBuf::from(vec![7])], + weights: [("brass".to_string(), 12), ("glass".to_string(), 3)].into_iter().collect(), + mark: CatalogMemberMark { label: "stamp".into(), weight: 5, id: "0000000000a0".into() }, + arm: CatalogMemberArm::Count(CatalogMemberCountArm { count: 21, id: "0000000000a1".into() }), + late: -9_000_000_000, + items: vec![CatalogMemberMark { label: "i0".into(), weight: 1, id: "0000000000b0".into() }, CatalogMemberMark { label: "i1".into(), weight: 2, id: "0000000000b1".into() }], + marks: vec![CatalogMemberMark { label: "m0".into(), weight: 3, id: "0000000000c0".into() }], + by_label: [ + ("x".to_string(), CatalogMemberMark { label: "bx".into(), weight: 4, id: "0000000000d0".into() }), + ("y".to_string(), CatalogMemberMark { label: "by".into(), weight: 5, id: "0000000000d1".into() }), + ] + .into_iter() + .collect(), + maybe_mark: Some(CatalogMemberMark { label: "maybe".into(), weight: 6, id: "0000000000e0".into() }), + arms: vec![ + CatalogMemberArm::Text(CatalogMemberTextArm { text: "t".into(), id: "0000000000f0".into() }), + CatalogMemberArm::Count(CatalogMemberCountArm { count: 8, id: "0000000000f1".into() }), + ], + grid: vec![vec![1, 2], vec![3]], + by_number: [(-1, "neg".to_string()), (7, "seven".to_string())].into_iter().collect(), + kind: 2, + ident: "00112233-4455-6677-8899-aabbccddeeff".into(), + when: Timestamp(vec![0x69, 0xa7, 0xbd, 0xbf]), + price: "12.50".into(), + opaque: Opaque("opaque".into()), + } +} + +fn vectors() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/vectors/catalog-members") +} + +fn read_from(path: &std::path::Path) -> CatalogMembers { + let dir = tempfile::tempdir().unwrap(); + let copy = dir.path().join("store.cc"); + std::fs::copy(path, ©).unwrap(); + let mut cache = CultCache::new(); + cache.register_entry_type::().unwrap(); + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(©)).unwrap(); + cache.pull_all_backing_stores().unwrap(); + cache.get::("m:1").unwrap().expect("m:1 is in the store") +} + +#[test] +fn the_members_empty_store_vector() { + let path = vectors().join("rust-members-empty-store.cc"); + if std::env::var("CULTCACHE_WRITE_VECTORS").as_deref() == Ok("1") { + std::fs::create_dir_all(vectors()).unwrap(); + let _ = std::fs::remove_file(&path); + let mut cache = CultCache::new(); + cache.register_entry_type::().unwrap(); + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap(); + cache.pull_all_backing_stores().unwrap(); + cache.put("m:1", &expected()).unwrap(); + return; + } + assert_eq!(read_from(&path), expected()); +} + +#[test] +fn a_csharp_written_store_reads_in_rust() { + assert_eq!(read_from(&vectors().join("csharp-members-store.cc")), expected()); +} + +/// The shared expected rows (members.json): [slot, member, typeName, isReference, isMany, targetSchemaName, isName, indexAlias]. +type Row = (i64, String, String, bool, bool, Option, bool, Option); + +/// The store's catalog entries as the file spells them (id, name, version, hash, canonical json, compatible ids, members). +type Entry = (String, String, String, String, String, Vec, Vec); + +fn catalog_rows(store: &str) -> Vec { + let bytes = std::fs::read(vectors().join(store)).unwrap(); + let (_header, mut catalog, _records): (String, Vec, serde::de::IgnoredAny) = rmp_serde::from_slice(&bytes).unwrap(); + assert_eq!(catalog.len(), 1, "one schema in {store}"); + catalog.remove(0).6 +} + +#[test] +fn the_csharp_catalog_holds_every_row_of_the_shared_table() { + let table: Vec = serde_json::from_slice(&std::fs::read(vectors().join("members.json")).unwrap()).unwrap(); + assert_eq!(table.len(), 29); + let rows = catalog_rows("csharp-members-store.cc"); + assert_eq!(rows.len(), table.len()); + for (index, (row, expected)) in rows.iter().zip(&table).enumerate() { + assert_eq!(row, expected, "row {index}"); + } +} + +#[test] +fn the_rust_written_catalog_holds_no_rows() { + assert!(catalog_rows("rust-members-empty-store.cc").is_empty()); +} diff --git a/packages/cultcache-ts/test/catalog-members.test.ts b/packages/cultcache-ts/test/catalog-members.test.ts new file mode 100644 index 00000000..a6023955 --- /dev/null +++ b/packages/cultcache-ts/test/catalog-members.test.ts @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { test } from "node:test"; + +import { readSingleFileStore } from "../src/single-file-messagepack-backing-store"; + +// tests/vectors/catalog-members (variants:ruling:rs-catalog-member-rows-every-member): one record in two stores. The C# reference's +// publishes a catalog row for each of the 29 members, every one of which members.json spells; the one cultcache-rs wrote before it +// wrote member rows publishes members []. A reader takes both and pulls the one record m:1. + +function findVectors(from: string): string { + for (let dir = from; ; dir = dirname(dir)) { + if (existsSync(join(dir, "tests", "vectors", "catalog-members"))) return join(dir, "tests", "vectors", "catalog-members"); + if (resolve(dir, "..") === dir) throw new Error("tests/vectors/catalog-members not found above the test."); + } +} +const vectors = findVectors(__dirname); + +// [slot, member, typeName, isReference, isMany, targetSchemaName, isName, indexAlias] +const table = JSON.parse(readFileSync(join(vectors, "members.json"), "utf8")) as unknown[][]; + +test("the C# written store publishes every row of the shared table and one record m:1", () => { + const { envelopes } = readSingleFileStore(join(vectors, "csharp-members-store.cc")); + assert.deepEqual(envelopes.map((envelope) => envelope.key), ["m:1"]); + const entry = envelopes[0].catalogEntry; + assert.equal(entry?.schemaName, "tests.catalog_members"); + assert.equal(table.length, 29); + const rows = (entry?.members ?? []).map((member) => [ + member.slot, + member.memberName, + member.typeName, + member.isReference ?? false, + member.isMany ?? false, + member.targetSchemaName ?? null, + member.isName ?? false, + member.indexAlias ?? null, + ]); + assert.deepEqual(rows, table); +}); + +test("the Rust written store publishes members [] for tests.catalog_members and one record m:1", () => { + const { envelopes } = readSingleFileStore(join(vectors, "rust-members-empty-store.cc")); + assert.deepEqual(envelopes.map((envelope) => envelope.key), ["m:1"]); + assert.equal(envelopes[0].catalogEntry?.schemaName, "tests.catalog_members"); + assert.deepEqual(envelopes[0].catalogEntry?.members ?? [], []); +}); diff --git a/tests/GameCult.Caching.Tests/CatalogMemberVectorTests.cs b/tests/GameCult.Caching.Tests/CatalogMemberVectorTests.cs new file mode 100644 index 00000000..0d02e20d --- /dev/null +++ b/tests/GameCult.Caching.Tests/CatalogMemberVectorTests.cs @@ -0,0 +1,268 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using NUnit.Framework; + +namespace GameCult.Caching.Tests +{ + [MessagePackObject] + public sealed class CatalogMemberMark + { + [Key(0)] public string Label = string.Empty; + [Key(1)] public int Weight; + [Key(2)] [CultElementId] public string Id = string.Empty; + } + + [Union(0, typeof(CatalogMemberTextArm))] + [Union(1, typeof(CatalogMemberCountArm))] + public abstract class CatalogMemberArm { } + + [MessagePackObject] + public sealed class CatalogMemberTextArm : CatalogMemberArm + { + [Key(0)] public string Text = string.Empty; + [Key(1)] [CultElementId] public string Id = string.Empty; + } + + [MessagePackObject] + public sealed class CatalogMemberCountArm : CatalogMemberArm + { + [Key(0)] public int Count; + [Key(1)] [CultElementId] public string Id = string.Empty; + } + + public enum CatalogMemberKind + { + Plain = 0, + Fancy = 2, + } + + [CultDocument("tests.catalog_members", "tests.catalog_members.v1")] + [MessagePackObject] + public sealed class CatalogMembersDocument + { + [Key(0)] [CultName] public string Title = string.Empty; + [Key(1)] [CultIndex("sku")] public string Sku = string.Empty; + [Key(2)] public int Count; + [Key(3)] public ulong Total; + [Key(4)] public double Ratio; + [Key(5)] public float Scale; + [Key(6)] public bool Flag; + [Key(7)] public int? MaybeCount; + [Key(8)] public string? Note; + [Key(9)] public List Tags = new(); + [Key(10)] public string[] Labels = Array.Empty(); + [Key(11)] public byte[] Raw = Array.Empty(); + [Key(12)] public List Chunks = new(); + [Key(13)] public Dictionary Weights = new(); + [Key(14)] public CatalogMemberMark Mark = new(); + [Key(15)] public CatalogMemberArm? Arm; + // Slot 16 is a gap. + [Key(17)] public long Late; + [Key(18)] public List Items = new(); + [Key(19)] public CatalogMemberMark[] Marks = Array.Empty(); + [Key(20)] public Dictionary ByLabel = new(); + [Key(21)] public CatalogMemberMark? MaybeMark; + [Key(22)] public List Arms = new(); + [Key(23)] public List> Grid = new(); + [Key(24)] public Dictionary ByNumber = new(); + [Key(25)] public CatalogMemberKind Kind; + [Key(26)] public Guid Ident; + [Key(27)] public DateTime When; + [Key(28)] public decimal Price; + // The Rust counterpart is a field type no C# name describes (variants:ruling:rs-member-unnamed-object-fallback): the row is System.Object. + [Key(29)] public object? Opaque; + } + + // tests/vectors/catalog-members (variants:ruling:rs-catalog-member-rows-every-member): a record holding a value in every + // member shape, in two stores. csharp-members-store.cc is written by this reference, under CULTCACHE_WRITE_VECTORS=1, and + // carries one catalog row per member; every other run compares its bytes. rust-members-empty-store.cc is written by + // cultcache-rs as it stood at e503edf2, whose catalog entry holds members [], and is never regenerated; it is only read. + public class CatalogMemberVectorTests + { + private const string Vector = "catalog-members"; + + private static readonly CultDocumentRegistry Registry = CultDocumentRegistry.ForTypes(new[] { typeof(CatalogMembersDocument) }); + + private static CatalogMembersDocument Expected() => new() + { + Title = "Brass lantern", + Sku = "LAN-0042", + Count = -7, + Total = 10_000_000_000UL, + Ratio = 0.25, + Scale = 1.5f, + Flag = true, + MaybeCount = 3, + Note = "handle with care", + Tags = new List { "fragile", "lit" }, + Labels = new[] { "a", "b", "c" }, + Raw = new byte[] { 0, 1, 2, 254, 255 }, + Chunks = new List { new byte[] { 9, 8 }, new byte[] { 7 } }, + Weights = new Dictionary { ["brass"] = 12, ["glass"] = 3 }, + Mark = new CatalogMemberMark { Label = "stamp", Weight = 5, Id = "0000000000a0" }, + Arm = new CatalogMemberCountArm { Count = 21, Id = "0000000000a1" }, + Late = -9_000_000_000L, + Items = new List { new() { Label = "i0", Weight = 1, Id = "0000000000b0" }, new() { Label = "i1", Weight = 2, Id = "0000000000b1" } }, + Marks = new[] { new CatalogMemberMark { Label = "m0", Weight = 3, Id = "0000000000c0" } }, + ByLabel = new Dictionary { ["x"] = new() { Label = "bx", Weight = 4, Id = "0000000000d0" }, ["y"] = new() { Label = "by", Weight = 5, Id = "0000000000d1" } }, + MaybeMark = new CatalogMemberMark { Label = "maybe", Weight = 6, Id = "0000000000e0" }, + Arms = new List { new CatalogMemberTextArm { Text = "t", Id = "0000000000f0" }, new CatalogMemberCountArm { Count = 8, Id = "0000000000f1" } }, + Grid = new List> { new() { 1, 2 }, new() { 3 } }, + ByNumber = new Dictionary { [-1] = "neg", [7] = "seven" }, + Kind = CatalogMemberKind.Fancy, + Ident = new Guid("00112233-4455-6677-8899-aabbccddeeff"), + When = new DateTime(2026, 3, 4, 5, 6, 7, DateTimeKind.Utc), + Price = 12.50m, + Opaque = "opaque", + }; + + private static void AssertEqualToExpected(CatalogMembersDocument? actual) + { + var expected = Expected(); + Assert.That(actual, Is.Not.Null); + Assert.That(actual!.Title, Is.EqualTo(expected.Title)); + Assert.That(actual.Sku, Is.EqualTo(expected.Sku)); + Assert.That(actual.Count, Is.EqualTo(expected.Count)); + Assert.That(actual.Total, Is.EqualTo(expected.Total)); + Assert.That(actual.Ratio, Is.EqualTo(expected.Ratio)); + Assert.That(actual.Scale, Is.EqualTo(expected.Scale)); + Assert.That(actual.Flag, Is.EqualTo(expected.Flag)); + Assert.That(actual.MaybeCount, Is.EqualTo(expected.MaybeCount)); + Assert.That(actual.Note, Is.EqualTo(expected.Note)); + Assert.That(actual.Tags, Is.EqualTo(expected.Tags)); + Assert.That(actual.Labels, Is.EqualTo(expected.Labels)); + Assert.That(actual.Raw, Is.EqualTo(expected.Raw)); + Assert.That(actual.Chunks, Is.EqualTo(expected.Chunks)); + Assert.That(actual.Weights, Is.EquivalentTo(expected.Weights)); + Assert.That(actual.Mark.Label, Is.EqualTo(expected.Mark.Label)); + Assert.That(actual.Mark.Weight, Is.EqualTo(expected.Mark.Weight)); + Assert.That(actual.Arm, Is.TypeOf()); + Assert.That(((CatalogMemberCountArm)actual.Arm!).Count, Is.EqualTo(21)); + Assert.That(actual.Late, Is.EqualTo(expected.Late)); + Assert.That(actual.Items.Select(m => (m.Label, m.Weight)), Is.EqualTo(expected.Items.Select(m => (m.Label, m.Weight)))); + Assert.That(actual.Marks.Select(m => (m.Label, m.Weight)), Is.EqualTo(expected.Marks.Select(m => (m.Label, m.Weight)))); + Assert.That(actual.ByLabel.Select(p => (p.Key, p.Value.Label, p.Value.Weight)), Is.EqualTo(expected.ByLabel.Select(p => (p.Key, p.Value.Label, p.Value.Weight)))); + Assert.That(actual.MaybeMark!.Label, Is.EqualTo("maybe")); + Assert.That(actual.Arms.Select(a => a.GetType()), Is.EqualTo(new[] { typeof(CatalogMemberTextArm), typeof(CatalogMemberCountArm) })); + Assert.That(((CatalogMemberTextArm)actual.Arms[0]).Text, Is.EqualTo("t")); + Assert.That(((CatalogMemberCountArm)actual.Arms[1]).Count, Is.EqualTo(8)); + Assert.That(actual.Grid, Is.EqualTo(expected.Grid)); + Assert.That(actual.ByNumber, Is.EquivalentTo(expected.ByNumber)); + Assert.That(actual.Kind, Is.EqualTo(expected.Kind)); + Assert.That(actual.Ident, Is.EqualTo(expected.Ident)); + Assert.That(actual.When, Is.EqualTo(expected.When)); + Assert.That(actual.Price, Is.EqualTo(expected.Price)); + Assert.That(actual.Opaque, Is.EqualTo("opaque")); + } + + private static byte[] StoreBytes() + { + var directory = Path.Combine(Path.GetTempPath(), $"cultlib-cmv-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directory); + try + { + var path = Path.Combine(directory, "store.cc"); + using (var cache = CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = Registry, StoreFlushOnDispose = true })) + { + cache.Clock = () => VectorFiles.StoredAt; + cache.UpsertAsync(typeof(CatalogMembersDocument), Expected(), new CultRecordKey("m:1")).GetAwaiter().GetResult(); + cache.FlushAsync().GetAwaiter().GetResult(); + } + + return File.ReadAllBytes(path); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + private static CatalogMembersDocument? ReadM1(string name, out CultSchemaMigrationReport[] reports) + { + var directory = Path.Combine(Path.GetTempPath(), $"cultlib-cmr-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directory); + try + { + var path = Path.Combine(directory, "store.cc"); + File.WriteAllBytes(path, VectorFiles.Committed(Vector, name)); + var store = new SingleFileMessagePackBackingStore(path); + using var cache = new CultCache(); + cache.AddBackingStore(store); + cache.PullAllBackingStoresAsync().GetAwaiter().GetResult(); + reports = store.LastSchemaMigrationReports.ToArray(); + return cache.Get(new CultRecordKey("m:1")); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + // The expected catalog rows, one table every runtime reads (members.json): [slot, member, typeName, isReference, isMany, targetSchemaName, isName, indexAlias]. + private static List ExpectedRows() + { + using var document = System.Text.Json.JsonDocument.Parse(VectorFiles.Committed(Vector, "members.json")); + return document.RootElement.EnumerateArray().Select(row => new object?[] + { + row[0].GetInt32(), row[1].GetString(), row[2].GetString(), row[3].GetBoolean(), row[4].GetBoolean(), + row[5].ValueKind == System.Text.Json.JsonValueKind.Null ? null : row[5].GetString(), row[6].GetBoolean(), + row[7].ValueKind == System.Text.Json.JsonValueKind.Null ? null : row[7].GetString(), + }).ToList(); + } + + private static List CatalogRows(string name) + { + var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(VectorFiles.Committed(Vector, name)); + return snapshot.SchemaCatalog.Single().Members + .Select(m => new object?[] { m.Slot, m.MemberName, m.TypeName, m.IsReference, m.IsMany, m.TargetSchemaName, m.IsName, m.IndexAlias }) + .ToList(); + } + + [Test] + public void TheCSharpStoreIsTheReferencesBytesAndReadsBack() + { + VectorFiles.Check(Vector, "csharp-members-store.cc", StoreBytes()); + AssertEqualToExpected(ReadM1("csharp-members-store.cc", out var reports)); + Assert.That(reports.SelectMany(report => report.Warnings), Is.Empty); + } + + [Test] + public void TheCSharpStoreCatalogHoldsEveryRowOfTheSharedTable() + { + var expected = ExpectedRows(); + Assert.That(expected, Has.Count.EqualTo(29)); + var actual = CatalogRows("csharp-members-store.cc"); + Assert.That(actual, Has.Count.EqualTo(expected.Count)); + for (var i = 0; i < expected.Count; i++) Assert.That(actual[i], Is.EqualTo(expected[i]), "row " + i); + } + + [Test] + public void TheRustStoreCatalogHoldsNoRows() + { + Assert.That(CatalogRows("rust-members-empty-store.cc"), Is.Empty); + } + + [Test] + public void MembersEmptyRustStoreStillLoads() + { + AssertEqualToExpected(ReadM1("rust-members-empty-store.cc", out var reports)); + // The reader loads a members-[] entry with warnings and no refusal. Counts per code, with the reason for each: + // compatible_schema_id_drift (1): the Rust entry's id is its schema name, not the fingerprint this type derives. + // content_hash_drift (1): the Rust entry's content hash is the schema name too, not the hash of the local canonical schema. + // defaulted_missing_slot (29): the entry lists no members, so each of this type's 29 members is absent from the persisted schema. + var warnings = reports.SelectMany(report => report.Warnings).GroupBy(warning => warning.Code).ToDictionary(group => group.Key, group => group.Count()); + Assert.That(warnings, Is.EquivalentTo(new Dictionary + { + ["compatible_schema_id_drift"] = 1, + ["content_hash_drift"] = 1, + ["defaulted_missing_slot"] = 29, + })); + } + } +} diff --git a/tests/vectors/catalog-members/README.md b/tests/vectors/catalog-members/README.md new file mode 100644 index 00000000..2d118573 --- /dev/null +++ b/tests/vectors/catalog-members/README.md @@ -0,0 +1,62 @@ +# catalog-members vector + +Two stores holding the same record, `m:1` of type `tests.catalog_members` (version `tests.catalog_members.v1`), with a value in every slot. +`variants:ruling:rs-catalog-member-rows-every-member` is the ruling they serve: cultcache-rs writes a catalog row for every member, and +every runtime keeps reading a store whose Rust-written entry holds `members []`. + +- `csharp-members-store.cc` is written by the C# reference (`CatalogMemberVectorTests`, under `CULTCACHE_WRITE_VECTORS=1`; every other run compares + the bytes). Its catalog entry carries the 29 rows of `members.json`, in slot order, which is the order C# discovers members in. +- `members.json` is the one expected table: `[slot, member, typeName, isReference, isMany, targetSchemaName, isName, indexAlias]` per row. C#, Rust, + TypeScript and Python each read the catalog rows of `csharp-members-store.cc` and compare every row to it; none picks rows by hand. +- `rust-members-empty-store.cc` is written by cultcache-rs at base e503edf2 (`packages/cultcache-rs/tests/catalog_members.rs`, `the_members_empty_store_vector`, + under `CULTCACHE_WRITE_VECTORS=1`). It is the one store in this folder C# does not write, and it is regenerated only by a reviewed commit with the Rust + source of e503edf2: it pins the bytes old Rust wrote, and a later Rust writes member rows. A Rust-written entry has id = schema name = `tests.catalog_members`, + version `tests.catalog_members.v1`, and `members []`. Its payload spells the slots through the Rust mirror below. + +The type holds: a name (Title), a unique index (Sku), the scalar leaves, a nullable struct, a nullable string, a list, an array, a byte array, a list of byte arrays, +a dictionary, a record (`Mark`: 0 Label, 1 Weight, 2 Id), a union (`Arm`: arm 0 `CatalogMemberTextArm {Text, Id}`, arm 1 `CatalogMemberCountArm {Count, Id}`), a gap at slot 16, +a slot above it (Late), and slots 18-29: list, array and map of records, a record, a list of unions, a nested list, a map keyed by int, an enum, a Guid, a DateTime, +a decimal, and an object. A record in a collection carries a `[CultElementId]` member, so the records and arms have an Id slot. + +What C# cannot express: a nullable record is the record's own type name (`MaybeMark` has no row of its own shape; nullable annotations on reference types are not +in the typeName, and `MaybeCount` is the nullable struct row); a field type that names nothing in Rust is spelled in C# as `object` (`Opaque`, row `System.Object`), +the row the library cut writes for a Rust field with no `type_name` (`variants:ruling:rs-member-unnamed-object-fallback`). + +The Rust mirror reads the C# bytes: Guid and decimal as their strings, the enum as its int, DateTime as the timestamp extension (kept as bytes), `Opaque` as a newtype of String. + +Rows (slot, member, typeName): + +| slot | member | typeName | role | +| --- | --- | --- | --- | +| 0 | Title | `System.String` | name | +| 1 | Sku | `System.String` | index `sku` | +| 2 | Count | `System.Int32` | | +| 3 | Total | `System.UInt64` | | +| 4 | Ratio | `System.Double` | | +| 5 | Scale | `System.Single` | | +| 6 | Flag | `System.Boolean` | | +| 7 | MaybeCount | `System.Nullable` | | +| 8 | Note | `System.String` | | +| 9 | Tags | `System.Collections.Generic.List` | | +| 10 | Labels | `System.String[]` | | +| 11 | Raw | `System.Byte[]` | | +| 12 | Chunks | `System.Collections.Generic.List` | | +| 13 | Weights | `System.Collections.Generic.Dictionary` | | +| 14 | Mark | `GameCult.Caching.Tests.CatalogMemberMark` | | +| 15 | Arm | `GameCult.Caching.Tests.CatalogMemberArm` | | +| 17 | Late | `System.Int64` | | +| 18 | Items | `System.Collections.Generic.List` | | +| 19 | Marks | `GameCult.Caching.Tests.CatalogMemberMark[]` | | +| 20 | ByLabel | `System.Collections.Generic.Dictionary` | | +| 21 | MaybeMark | `GameCult.Caching.Tests.CatalogMemberMark` | | +| 22 | Arms | `System.Collections.Generic.List` | | +| 23 | Grid | `System.Collections.Generic.List>` | | +| 24 | ByNumber | `System.Collections.Generic.Dictionary` | | +| 25 | Kind | `GameCult.Caching.Tests.CatalogMemberKind` | | +| 26 | Ident | `System.Guid` | | +| 27 | When | `System.DateTime` | | +| 28 | Price | `System.Decimal` | | +| 29 | Opaque | `System.Object` | | + +Readers: C# loads both stores typed (the Rust one with `compatible_schema_id_drift` x1, `content_hash_drift` x1 and `defaulted_missing_slot` x29, no refusal) and reads the catalog rows of both; +Rust reads both records and the rows of both (raw catalog); TypeScript and Python read both stores and compare all 29 rows and 0 rows. diff --git a/tests/vectors/catalog-members/csharp-members-store.cc b/tests/vectors/catalog-members/csharp-members-store.cc new file mode 100644 index 0000000000000000000000000000000000000000..c6711d011f965041d2b169a59da3cc9e0921eb75 GIT binary patch literal 6942 zcmd5>-*4MQ98c2yWCO%t{2nS15(wJp&Q6>-LYvlBl!~rHYhVx4Kxg}$m^t>aoox}? zOaFjLO_1nom$)4;eh3MPmx-zyFYo{o5>n6}5&R82Ksnzzw%25xrzsXuq{R2V@7?F_ zzW4onzhAe%ksG=rBe{liwqsg2cY$C2q&I8V5LXb&90n>c6jV;mDa~EJR zuTtbeu_P9XMP4Wh5CWhoPy|>JRT+sGDnhZKiXz02gII)Ip3e&k6nGVj#eAVq{Qc0< zM_HRJs*V;=9cRngp;Klj{7&x@RGMkrtsj9#y87s|Nn+?Mmz%pkzJU5yx*@lD< zkW@@!e*;L~Ay9;TB2e-HlvBvj%mFAfW<#R(GXg`|wkw4I%A$;h*(|ZxgrEokls9zb zU6VU+&y;EE7#WEiP%(gV0yQN(+;kVnl|KYF%f!YFJ2#6BY-w_CUbCJ4o-vo0%%;K6KhGlx>w{<+nlon;IYSsa=~L+9 zz|KuI9h?-Bh?A~0jB|qs)yDvm|_&CJ|U}nuK7)^X4ivV47wD(+L_c`5L3A1{iX~ajSlRAelk}7(-7zkA`@{ zsjo450^-7~Wlq6E65QDawWS1*gj9IC zhP^!L&irYH@MA?I)sKxWs$xftA;SqE|-=m`XW}HV4~eFEgSSji?mw6M0>hk8vms~lb^ja(caI( zwEBkMVR$yp`tR#{X>KqHEu%5X{;rpH_HzCp_wvEM|6;lit+6!lD_^;v{W0l*4#~>; zQ?mSq2@bAJ(#sgla}7p4wwi1FasAjVn!xx$Va+fY|wipj$ib8GOb5D zgjstp$5A33na*QfFUXD}}XA9uY6yZ34wm|oX2XPM#? z>wZkwdv6Cwci-l?^Z7Ure;UMS_j?XccDOy=xHf-$VG@8m_xI1KR4P+B@JH&WW51BUA0h7PJ0!tN~`j%-Kliu->ufI%>I41(tDR&$(!Y%Th+", false, false, null, false, null], +[8, "Note", "System.String", false, false, null, false, null], +[9, "Tags", "System.Collections.Generic.List", false, false, null, false, null], +[10, "Labels", "System.String[]", false, false, null, false, null], +[11, "Raw", "System.Byte[]", false, false, null, false, null], +[12, "Chunks", "System.Collections.Generic.List", false, false, null, false, null], +[13, "Weights", "System.Collections.Generic.Dictionary", false, false, null, false, null], +[14, "Mark", "GameCult.Caching.Tests.CatalogMemberMark", false, false, null, false, null], +[15, "Arm", "GameCult.Caching.Tests.CatalogMemberArm", false, false, null, false, null], +[17, "Late", "System.Int64", false, false, null, false, null], +[18, "Items", "System.Collections.Generic.List", false, false, null, false, null], +[19, "Marks", "GameCult.Caching.Tests.CatalogMemberMark[]", false, false, null, false, null], +[20, "ByLabel", "System.Collections.Generic.Dictionary", false, false, null, false, null], +[21, "MaybeMark", "GameCult.Caching.Tests.CatalogMemberMark", false, false, null, false, null], +[22, "Arms", "System.Collections.Generic.List", false, false, null, false, null], +[23, "Grid", "System.Collections.Generic.List>", false, false, null, false, null], +[24, "ByNumber", "System.Collections.Generic.Dictionary", false, false, null, false, null], +[25, "Kind", "GameCult.Caching.Tests.CatalogMemberKind", false, false, null, false, null], +[26, "Ident", "System.Guid", false, false, null, false, null], +[27, "When", "System.DateTime", false, false, null, false, null], +[28, "Price", "System.Decimal", false, false, null, false, null], +[29, "Opaque", "System.Object", false, false, null, false, null] +] diff --git a/tests/vectors/catalog-members/rust-members-empty-store.cc b/tests/vectors/catalog-members/rust-members-empty-store.cc new file mode 100644 index 0000000000000000000000000000000000000000..423302ecdeb3c6af0ca928618ba7dda2cad96b36 GIT binary patch literal 683 zcmZ{ePixdb7{(`AYb*8YRhHnFEjk+nfLc(hioepjIseVxELnT*e2=o zBLQ6S2BU(8!~RADkp~H{rpJ|8wWd0L_Gr)I$`;Wz8iD0nmEWz~7omH~8w}&ia!RA3 z7yT^v!NVtMwf1THY#ON|lL)EP}c9`q904?>uRfyi>2 zdpVoUA;bJz%9(j>VP?#a3-8==z37MPsAUBgG}@edh5rx5(vUZFKu*4vW%=jV{!b*c zNq`OQ(Zh-mQzssCV9R zK?g)i!%S=AavDQ_zTmJ8v3Yh2V?rFK*|b}&cH8cBx?Ou|X?fYE)bkkgeSlu?TNxa@ RdtVTz(Z(-^oAmJ(`~wIW_T>No literal 0 HcmV?d00001