Research: Python typed-leaves probes (C# opens a leaf-cataloged Python store; prototype leaves hold the numeric vectors)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-11 19:47:37 +02:00
commit 9d7b584285
7 changed files with 311 additions and 0 deletions

View file

@ -0,0 +1,100 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using MessagePack;
using NUnit.Framework;
namespace GameCult.Caching.Tests.PyLeavesProbe
{
[MessagePackObject] public sealed class ProbeInner { [Key(0)] public string N = ""; [Key(1)] public float W; }
[Union(0, typeof(ProbeCircle))] public interface IProbeShape { }
[MessagePackObject] public sealed class ProbeCircle : IProbeShape { [Key(0)] public float R; }
[CultDocument("cultcache.py-leaves-probe", "cultcache.py_leaves_probe.v1")]
[MessagePackObject]
public sealed class ProbeDoc
{
[Key(0)] [CultName] public string Id = "";
[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 ProbeInner? Nested;
[Key(12)] public List<ProbeInner> Items = new();
[Key(13)] public IProbeShape? Shape;
[Key(14)] public float[] Floats = Array.Empty<float>();
[Key(15)] public float? MaybeF;
}
[MessagePackObject] public sealed class S1 { [Key(0)] public string? V; }
[MessagePackObject] public sealed class B1 { [Key(0)] public bool V; }
[MessagePackObject] public sealed class Y1 { [Key(0)] public byte[]? V; }
[MessagePackObject] public sealed class O1 { [Key(0)] public object? V; }
[MessagePackObject] public sealed class LS1 { [Key(0)] public List<string>? V; }
[MessagePackObject] public sealed class NI1 { [Key(0)] public int? V; }
[MessagePackObject] public sealed class R1 { [Key(0)] public ProbeInner? V; }
[MessagePackObject] public sealed class U1 { [Key(0)] public IProbeShape? V; }
[MessagePackObject] public sealed class LI1 { [Key(0)] public List<int>? V; }
public class PyLeavesProbeTests
{
static readonly MessagePackSerializerOptions Options = CultDocumentMessagePackSerialization.OptionsFor(typeof(PyLeavesProbeTests).Assembly);
[Test]
public void TypeNames()
{
var names = typeof(CultCache).Assembly.GetType("GameCult.Caching.CultSchemaTypeNames")!.GetMethod("FromType")!;
foreach (var t in new[] { typeof(string), typeof(bool), typeof(byte[]), typeof(int), typeof(long), typeof(float), typeof(double),
typeof(int?), typeof(bool?), typeof(float?), typeof(List<string>), typeof(string[]), typeof(List<int?>), typeof(object),
typeof(ProbeInner), typeof(List<ProbeInner>), typeof(IProbeShape), typeof(float[]), typeof(List<List<string>>),
typeof(Dictionary<string, int>), typeof(byte[][]) , typeof(List<byte[]>)})
TestContext.Out.WriteLine($"TYPENAME {t} => {names.Invoke(null, new object[] { t })}");
}
[TestCase("a-leaf-catalog.cc")]
[TestCase("b-wrong-leaf.cc")]
public async Task OpenPythonStore(string file)
{
var path = Path.Combine("/tmp/pyst", file);
try
{
var cache = new CultCache();
cache.AddBackingStore(new SingleFileMessagePackBackingStore(path));
await cache.PullAllBackingStoresAsync();
var doc = cache.AllEntries.OfType<ProbeDoc>().Single();
var bytes = MessagePackSerializer.Serialize(doc, Options);
TestContext.Out.WriteLine($"OPEN {file} OK id={doc.Id} F={doc.F:R} Shape={doc.Shape?.GetType().Name} Any={doc.Any?.GetType().Name} items={doc.Items.Count}");
TestContext.Out.WriteLine($"CSHARP-REWRITE {file} {Convert.ToHexString(bytes).ToLowerInvariant()}");
}
catch (Exception e)
{
TestContext.Out.WriteLine($"OPEN {file} REFUSED {e.GetType().Name}: {e.Message.Split('\n')[0]}");
}
}
static readonly string[] Values = { "05", "ff", "cb3ff8000000000000", "ca3fc00000", "c0", "c2", "c3", "a161", "d90161", "c40100", "90", "9101", "91a161", "80", "81a161a162", "920091ca3f800000" };
static string Try<T>(byte[] p) { try { var v = MessagePackSerializer.Deserialize<T>(p, Options); return "ok"; } catch { return "--"; } }
[Test]
public void ScalarReads()
{
foreach (var v in Values)
{
var p = Convert.FromHexString("91" + v);
TestContext.Out.WriteLine($"READ {v,-22} string={Try<S1>(p)} bool={Try<B1>(p)} bytes={Try<Y1>(p)} object={Try<O1>(p)} list<string>={Try<LS1>(p)} int?={Try<NI1>(p)} record={Try<R1>(p)} union={Try<U1>(p)} list<int>={Try<LI1>(p)}");
}
}
}
}

View file

@ -0,0 +1,17 @@
# Python typed leaves: probe evidence (2026-10-11)
Serves `cultlib-gaps:ruling:py-slot-typed-leaves` and the specs
`cultlib-gaps:cut_spec:cut-leaf-vectors-cs.r1` and `cut-py-typed-leaves.r1`.
Run by the Imagination pass `imagination-cl-py-typed-leaves` on Yggdrasil at CultLib main 4ec4bfb7.
- `write_probe_stores.py` + `PyLeavesProbe.cs`: a Python store whose catalog uses the leaf type names
(from `CultSchemaTypeNames.FromType`) is opened by the C# reference and its payload rewritten byte-identical,
float32 included (except inside an `object` slot, where C# itself rewrites a fixint as uint8). Negative control:
one slot named Int64 where C# has Int32 is refused ("slot 3 changed type").
- `proto_leaves.py` + `run_vectors.py`: prototype leaves reproduce the C# numeric-leaves vectors (160 reads, 46 writes,
the mixed record). `truth.py`: what C# accepts per slot type (byte[] accepts str; bool only false/true; record
accepts []; nil in an int slot refused).
- `perf.py`: float32 via a marker with packb-first fallback; a 1.5k-node record with float32 about 0.8 ms vs 0.1 ms.
- `job1.log`: the verify run.
Scripts are probes, not a suite; they are kept so the next pass can rerun them.

View file

@ -0,0 +1,22 @@
import sys, time, msgpack
sys.path.insert(0, sys.argv[1]); import proto_leaves as L
# a HullData-like record: 20 float32 slots, strings, nested list of 200 small records
rec = lambda i: ["part%d" % i, i, [L.Float32(0.5*i), L.Float32(1.5), L.Float32(2.5)], None]
tree = ["id", 3, [L.Float32(float(i)) for i in range(20)], [rec(i) for i in range(200)]]
plain = ["id", 3, [float(i) for i in range(20)], [["part%d" % i, i, [0.5*i,1.5,2.5], None] for i in range(200)]]
N=300
t=time.perf_counter(); [L.write(tree) for _ in range(N)]; a=time.perf_counter()-t
t=time.perf_counter(); [msgpack.packb(plain, use_bin_type=True) for _ in range(N)]; b=time.perf_counter()-t
t=time.perf_counter(); [msgpack.unpackb(msgpack.packb(plain)) for _ in range(N)]; c=time.perf_counter()-t
print(f"walk-writer {a/N*1e6:.0f} us/rec, packb {b/N*1e6:.0f} us/rec, ratio {a/b:.1f}x; size {len(L.write(tree))} vs {len(msgpack.packb(plain))}")
def pack_tree(t):
try: return msgpack.packb(t, use_bin_type=True)
except TypeError: return L.write(t)
assert pack_tree(plain) == L.write(plain) == msgpack.packb(plain, use_bin_type=True)
assert pack_tree(tree) == L.write(tree)
t=time.perf_counter(); [pack_tree(plain) for _ in range(N)]; p=time.perf_counter()-t
t=time.perf_counter(); [pack_tree(tree) for _ in range(N)]; q=time.perf_counter()-t
print(f"pack_tree plain {p/N*1e6:.0f} us, float32 tree {q/N*1e6:.0f} us")
try:
pack_tree([object()])
except TypeError as e: print("custom object:", e)

View file

@ -0,0 +1,87 @@
"""Scratch prototype of cultcache_py.leaves, to establish mechanisms against the C# vectors. Not for the repo."""
import math, struct, msgpack
class Refused(ValueError): pass
def kind(v):
if v is None: return "nil"
if isinstance(v, bool): return "a boolean"
if isinstance(v, int): return "an integer"
if isinstance(v, float): return "a float"
if isinstance(v, str): return "a string"
if isinstance(v, (bytes, bytearray, memoryview)): return "bytes"
if isinstance(v, (list, tuple)): return "an array"
if isinstance(v, dict): return "a map"
return type(v).__name__
def refuse(what, v): raise Refused(f"expected {what}, found {kind(v)}")
class Float32: # tree marker: written as MessagePack float 32
__slots__ = ("value",)
def __init__(self, v): self.value = v
def int_to_f32(v: int) -> float:
if abs(v) <= 2**53:
return f32(float(v))
m = abs(v); excess = m.bit_length() - 24
kept = m >> excess; rest = m - (kept << excess); half = 1 << (excess - 1)
if rest > half or (rest == half and kept & 1): kept += 1
r = float(kept) * 2.0**excess # kept<=2^24 exact; scaling exact unless overflow
return f32(-r if v < 0 else r)
def f32(x: float) -> float:
try:
return struct.unpack(">f", struct.pack(">f", x))[0]
except OverflowError:
return math.copysign(math.inf, x)
class Leaf:
def __init__(self, type_name, enc, dec, value_type=False):
self.type_name, self.encode, self.decode, self.value_type = type_name, enc, dec, value_type
def _int_leaf(name, what, lo, hi):
def enc(v):
if not isinstance(v, int) or isinstance(v, bool): refuse(what, v)
if not lo <= v <= hi: raise Refused(f"expected {what}, found an integer out of range")
return v
return Leaf(name, enc, enc, True)
int32 = _int_leaf("System.Int32", "an int32", -2**31, 2**31-1)
int64 = _int_leaf("System.Int64", "an int64", -2**63, 2**63-1)
def _f32_enc(v):
if isinstance(v, bool) or not isinstance(v, (int, float)): refuse("a float32", v)
return Float32(int_to_f32(v) if isinstance(v, int) else f32(v))
def _f32_dec(v):
if isinstance(v, bool) or not isinstance(v, (int, float)): refuse("a float32", v)
return int_to_f32(v) if isinstance(v, int) else f32(v)
float32 = Leaf("System.Single", _f32_enc, _f32_dec, True)
def _f64(v):
if isinstance(v, bool) or not isinstance(v, (int, float)): refuse("a float64", v)
return float(v) # int > 2^53 rounds once (Python int->float is correctly rounded)
float64 = Leaf("System.Double", _f64, _f64, True)
def _str(v):
if v is not None and not isinstance(v, str): refuse("a string", v)
return v
string = Leaf("System.String", _str, _str)
def _bool(v):
if not isinstance(v, bool): refuse("a boolean", v)
return v
boolean = Leaf("System.Boolean", _bool, _bool, True)
# writer: msgpack-python per value, float32 through a single-float packer, containers by header
_P = msgpack.Packer(use_bin_type=True)
_P32 = msgpack.Packer(use_bin_type=True, use_single_float=True)
def write(tree) -> bytes:
out = bytearray()
stack = [tree]
while stack:
n = stack.pop()
if isinstance(n, Float32): out += _P32.pack(n.value)
elif isinstance(n, list):
out += _P.pack_array_header(len(n)); stack.extend(reversed(n))
elif isinstance(n, dict):
out += _P.pack_map_header(len(n))
for k, v in reversed(list(n.items())): stack.append(v); stack.append(k)
else: out += _P.pack(n)
return bytes(out)

View file

@ -0,0 +1,25 @@
import sys, struct, msgpack, math
sys.path.insert(0, sys.argv[2])
import proto_leaves as L
d = sys.argv[1]
leaves = {"int32": L.int32, "int64": L.int64, "float32": L.float32, "float64": L.float64}
rows = msgpack.unpackb(open(d+"/reads.msgpack","rb").read(), raw=False)
bad = 0
for leaf, payload, ok, bits in rows:
raw = msgpack.unpackb(payload, raw=False)[0]
try:
v = leaves[leaf].decode(raw); got = True
b = struct.pack(">q", v) if leaf.startswith("int") else struct.pack(">d", v)
except L.Refused: got, b = False, b""
if got != ok or (ok and b != bits):
bad += 1; print("READ DIFF", leaf, payload.hex(), "C#", ok, bits.hex(), "py", got, b.hex())
print("reads", len(rows), "diffs", bad)
wr = msgpack.unpackb(open(d+"/writes.msgpack","rb").read(), raw=False)
bad = 0
for leaf, text, want in wr:
v = int(text) if leaf.startswith("int") else struct.unpack(">d", bytes.fromhex(text))[0]
got = L.write([leaves[leaf].encode(v)])
if got != want: bad += 1; print("WRITE DIFF", leaf, text, want.hex(), got.hex())
print("writes", len(wr), "diffs", bad)
mixed = L.write([L.string.encode("n1"), L.int32.encode(7), L.int64.encode(8), L.float32.encode(1.5), L.float64.encode(2.5)])
print("mixed equal:", mixed == open(d+"/mixed-record.msgpack","rb").read(), mixed.hex())

View file

@ -0,0 +1,18 @@
import msgpack, struct, sys
d = sys.argv[1]
rows = msgpack.unpackb(open(d+"/reads.msgpack","rb").read(), raw=False)
from collections import defaultdict
t = defaultdict(list)
for leaf, payload, ok, bits in rows:
tok = payload[1:].hex()
t[leaf].append((tok, ok, bits.hex()))
for leaf, cases in t.items():
print(leaf, "accepts", sum(ok for _,ok,_ in cases), "of", len(cases))
print(" refused:", [tok for tok,ok,_ in cases if not ok])
# float accepted from integer? int from float?
f = msgpack.unpackb(open(d+"/float32-nan.msgpack","rb").read(), raw=False)
for p, b in f:
v = msgpack.unpackb(p)[0]
bits = struct.pack(">d", v).hex()
repacked = msgpack.packb([v], use_single_float=True).hex()
print("nan in", p.hex(), "C# out", b.hex(), "py double", bits, "py repack f32", repacked)

View file

@ -0,0 +1,42 @@
"""Writes Python stores whose catalog carries the C# type names the proposed leaves would derive, for the C# reference to open."""
import sys, os
sys.path.insert(0, r"F:\Projects\CultLib\packages\cultcache-py\src"); sys.path.insert(0, os.path.dirname(__file__))
import proto_leaves as L
from cultcache_py import CultCache, SingleFileMessagePackBackingStore
from cultcache_py.documents import define_document_type
from cultcache_py.backing_store import CultCacheSchemaCatalogMember as M
NS = "GameCult.Caching.Tests.PyLeavesProbe"
LIST = "System.Collections.Generic.List<{}>"
MEMBERS = [ # slot, member, C# type name the leaf derives
(0, "Id", "System.String"), (1, "Flag", "System.Boolean"), (2, "Blob", "System.Byte[]"),
(3, "I", "System.Int32"), (4, "L", "System.Int64"), (5, "F", "System.Single"), (6, "D", "System.Double"),
(7, "MaybeI", "System.Nullable<System.Int32>"), (8, "Tags", LIST.format("System.String")),
(9, "Names", "System.String[]"), (10, "Any", "System.Object"), (11, "Nested", NS + ".ProbeInner"),
(12, "Items", LIST.format(NS + ".ProbeInner")), (13, "Shape", NS + ".IProbeShape"),
(14, "Floats", "System.Single[]"), (15, "MaybeF", "System.Nullable<System.Single>"),
]
F32 = lambda x: L.Float32(L.f32(x))
def payload(doc_id):
inner = lambda n, w: [n, F32(w)]
return [doc_id, True, b"\x01\x02", 7, 2**40, F32(0.1), 0.1, None, ["a", "b"], ["x"], {"k": [1, "two"]},
inner("n", 1.25), [inner("i0", 0.5), inner("i1", 2.0)], [0, [F32(3.5)]], [F32(1.0), F32(0.1)], F32(2.5)]
def write(path, members, tree_for):
doc = define_document_type(
"cultcache.py-leaves-probe", encode=lambda v: v, decode=lambda v: v,
payload_encoder=L.write, payload_decoder=lambda b: b, name=lambda v: v[0],
schema_name="cultcache.py-leaves-probe", schema_version="cultcache.py_leaves_probe.v1",
members=[M(slot=s, member_name=n, type_name=t, is_name=(s == 0)) for s, n, t in members])
if os.path.exists(path): os.remove(path)
cache = CultCache.builder().register_document_type(doc).add_generic_store(SingleFileMessagePackBackingStore(path)).build()
cache.pull_all_backing_stores()
tree = tree_for(os.path.basename(path))
cache.put(doc, tree[0], tree)
print(path, "payload", L.write(tree).hex())
out = sys.argv[1]
write(os.path.join(out, "a-leaf-catalog.cc"), MEMBERS, payload)
# negative control: the int32 slot cataloged as the int64 leaf would name it
wrong = [(s, n, "System.Int64" if s == 3 else t) for s, n, t in MEMBERS]
write(os.path.join(out, "b-wrong-leaf.cc"), wrong, payload)