From 4ca8a654e559e23ceb3fd1bb0458defd7eadaf5b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:39:14 +0100 Subject: [PATCH 1/5] daemon: MessagePack payloads only; strict one-value decode; delete put_json_document Co-Authored-By: Claude Sonnet 5.5 --- brokkr-daemon/src/main.rs | 182 +++++++++++++++++++++++++------------- 1 file changed, 122 insertions(+), 60 deletions(-) diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index 48600c5..be9fbc0 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -767,7 +767,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { &source.local_position, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -843,7 +843,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "scale": source.local_scale, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -874,7 +874,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "visible": source.active_self, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -924,7 +924,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { &parent_name, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -961,7 +961,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { material, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -1013,7 +1013,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "value": property.value, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -1368,8 +1368,8 @@ fn run_sync_once(args: &SyncArgs) -> Result { "sync/receipts/{}", receipt["receiptId"].as_str().unwrap_or("sync-receipt") ); - unity_store.put_json_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; - blender_store.put_json_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; + unity_store.put_messagepack_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; + blender_store.put_messagepack_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; report.receipts_written += 2; } @@ -1401,17 +1401,6 @@ impl MirrorStore { Ok(documents) } - fn put_json_document(&mut self, schema: &str, key: &str, value: &Value) -> Result<()> { - let payload = serde_json::to_vec(value)?; - self.store.push(&CultCacheEnvelope { - key: key.to_string(), - r#type: schema.to_string(), - payload, - stored_at: chrono_like_now(), - schema_id: Some(schema.to_string()), - }) - } - fn put_messagepack_document(&mut self, schema: &str, key: &str, value: &Value) -> Result<()> { let payload = rmp_serde::to_vec(value)?; self.store.push(&CultCacheEnvelope { @@ -1425,14 +1414,18 @@ impl MirrorStore { } fn decode_payload(envelope: &CultCacheEnvelope) -> Result { - serde_json::from_slice(&envelope.payload) - .or_else(|_| rmp_serde::from_slice(&envelope.payload)) - .with_context(|| { - format!( - "payload is neither MessagePack nor JSON for {}", - envelope.key - ) - }) + let mut cursor = io::Cursor::new(envelope.payload.as_slice()); + let value: Value = rmp_serde::decode::from_read(&mut cursor) + .with_context(|| format!("payload is not a MessagePack value for {}", envelope.key))?; + let trailing = envelope.payload.len() as u64 - cursor.position(); + if trailing != 0 { + return Err(anyhow!( + "payload for {} is not exactly one MessagePack value: {} trailing byte(s)", + envelope.key, + trailing + )); + } + Ok(value) } fn parse_object_binding(value: &Value) -> Option { @@ -2699,7 +2692,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2714,7 +2707,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2729,7 +2722,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-transform", &json!({ @@ -2746,7 +2739,7 @@ mod tests { }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2772,7 +2765,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2787,7 +2780,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2802,7 +2795,7 @@ mod tests { "authority": "unity-to-blender" }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ "objects": [] }), @@ -2815,12 +2808,12 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ "sceneObjects": [] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2834,7 +2827,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2856,7 +2849,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2883,7 +2876,7 @@ mod tests { ] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-rig", &json!({ @@ -2898,7 +2891,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2913,7 +2906,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-parent", &json!({ @@ -2929,7 +2922,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2963,7 +2956,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2979,7 +2972,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2994,7 +2987,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-material", &json!({ @@ -3010,7 +3003,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3033,7 +3026,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3048,7 +3041,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3063,7 +3056,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-active", &json!({ @@ -3079,7 +3072,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3106,7 +3099,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3131,7 +3124,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3146,7 +3139,7 @@ mod tests { "authority": "unity-to-blender" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-component-speed", &json!({ @@ -3162,7 +3155,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3189,7 +3182,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3204,7 +3197,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3219,7 +3212,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-custom-intensity", &json!({ @@ -3235,7 +3228,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3261,7 +3254,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.timeline_binding.v0", "sync/bindings/timelines/timeline-camera", &json!({ @@ -3280,7 +3273,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3329,4 +3322,73 @@ mod tests { ); Ok(()) } + + #[test] + fn decode_payload_refuses_trailing_bytes() -> Result<()> { + let mut payload = rmp_serde::to_vec(&json!({"a": 1}))?; + let clean = CultCacheEnvelope { + key: "k/clean".to_string(), + r#type: "t".to_string(), + payload: payload.clone(), + stored_at: String::new(), + schema_id: None, + }; + assert_eq!(decode_payload(&clean)?, json!({"a": 1})); + + payload.push(0xc0); + let dirty = CultCacheEnvelope { + key: "k/dirty".to_string(), + payload, + ..clean + }; + let message = format!("{:#}", decode_payload(&dirty).unwrap_err()); + assert!(message.contains("k/dirty"), "{message}"); + assert!(message.contains("1 trailing byte"), "{message}"); + assert!(!message.contains("c0"), "{message}"); + Ok(()) + } + + #[test] + fn decode_payload_refuses_json_payload() -> Result<()> { + let receipt = json!({"schema": "brokkr.sync.receipt.v0", "status": "ok"}); + let envelope = CultCacheEnvelope { + key: "sync/receipts/json".to_string(), + r#type: "brokkr.sync.receipt.v0".to_string(), + payload: serde_json::to_vec(&receipt)?, + stored_at: String::new(), + schema_id: None, + }; + assert!(decode_payload(&envelope).is_err()); + Ok(()) + } + + #[test] + fn sync_once_writes_messagepack_receipts() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_sync_stores(&unity_path, &blender_path, "unity-to-blender")?; + run_sync_once(&SyncArgs { + unity_cache: unity_path.clone(), + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + for path in [&unity_path, &blender_path] { + let store = SingleFileMessagePackBackingStore::new(path); + let envelopes = store.pull_all()?; + let receipt = envelopes + .iter() + .find(|envelope| envelope.r#type == "brokkr.sync.receipt.v0") + .expect("store should hold the daemon sync receipt"); + let lead = receipt.payload.first().copied().unwrap_or(0); + assert!( + (0x80..=0x8f).contains(&lead) || lead == 0xde || lead == 0xdf, + "receipt payload should be a MessagePack map, led by {lead:#04x}" + ); + assert!(serde_json::from_slice::(&receipt.payload).is_err()); + assert!(decode_payload(receipt)?.is_object()); + } + Ok(()) + } } -- 2.47.3 From 1458bd717e1aadcc2b6a9c2f87186b30a49d0f5c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:41:16 +0100 Subject: [PATCH 2/5] Blender bridge: bridge_documents, convert_store, MessagePack-default guard; tests, check.ps1, install doc Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/blender_target.py | 38 ++++-- surfaces/blender/docs/install.md | 12 ++ surfaces/blender/tests/test_store_convert.py | 109 ++++++++++++++++++ tools/check.ps1 | 3 + 4 files changed, 152 insertions(+), 10 deletions(-) create mode 100644 surfaces/blender/tests/test_store_convert.py diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 0c49412..1279f97 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -1026,16 +1026,7 @@ class BrokkrBlenderTarget: return self._node, self._documents cultmesh, cultcache = _load_cultmesh(cultlib_py_src) - documents = { - "host_snapshot": cultcache.define_document_type(HOST_SNAPSHOT_SCHEMA), - "command_intent": cultcache.define_document_type(COMMAND_INTENT_SCHEMA), - "command_receipt": cultcache.define_document_type(COMMAND_RECEIPT_SCHEMA), - "sync_session": cultcache.define_document_type(SYNC_SESSION_SCHEMA), - "sync_object_binding": cultcache.define_document_type(SYNC_OBJECT_BINDING_SCHEMA), - "sync_var": cultcache.define_document_type(SYNC_VAR_SCHEMA), - "sync_timeline_binding": cultcache.define_document_type(SYNC_TIMELINE_BINDING_SCHEMA), - "sync_receipt": cultcache.define_document_type(SYNC_RECEIPT_SCHEMA), - } + documents = bridge_documents(cultcache) node = cultmesh.CultMesh.start_node(path, runtime_id=runtime_id) for document in documents.values(): node.database.register_document(document) @@ -1095,6 +1086,28 @@ class BrokkrBlenderTarget: }) +def bridge_documents(cultcache: Any) -> dict[str, Any]: + """The bridge's eight document definitions, under cultcache-py's default (MessagePack) payload codec.""" + return { + "host_snapshot": cultcache.define_document_type(HOST_SNAPSHOT_SCHEMA), + "command_intent": cultcache.define_document_type(COMMAND_INTENT_SCHEMA), + "command_receipt": cultcache.define_document_type(COMMAND_RECEIPT_SCHEMA), + "sync_session": cultcache.define_document_type(SYNC_SESSION_SCHEMA), + "sync_object_binding": cultcache.define_document_type(SYNC_OBJECT_BINDING_SCHEMA), + "sync_var": cultcache.define_document_type(SYNC_VAR_SCHEMA), + "sync_timeline_binding": cultcache.define_document_type(SYNC_TIMELINE_BINDING_SCHEMA), + "sync_receipt": cultcache.define_document_type(SYNC_RECEIPT_SCHEMA), + } + + +def convert_store(source: str, destination: str, cultlib_py_src: str = "") -> int: + """Write the records of an older (JSON payload) bridge store to a new MessagePack file and return the count. + The destination must not exist and the source is never written: stop every writer, convert, then swap the files.""" + _cultmesh, cultcache = _load_cultmesh(cultlib_py_src) + return cultcache.convert( + cultcache.SingleFileMessagePackBackingStore(source), destination, bridge_documents(cultcache).values()) + + def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: packages = Path(cultlib_py_src or DEFAULT_CULTLIB_PY_SRC) for name in CULTLIB_PY_PACKAGES: @@ -1111,6 +1124,11 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." ) from exc + if not hasattr(cultcache_py, "convert"): + raise RuntimeError( + "Brokkr Blender target requires CultLib's cultcache-py with the MessagePack payload default " + "(CultLib main after the py-msgpack-default merge); the cultcache-py found here predates it. " + "Update the CultLib checkout named by CultLib Python Source.") return cultmesh_py, cultcache_py diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index f27093b..842f886 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -16,6 +16,18 @@ directory; the add-on puts each package's `src` on `sys.path`: F:/Projects/CultLib/packages ``` +That CultLib checkout must carry cultcache-py's MessagePack payload default +(CultLib main after the py-msgpack-default merge); the add-on refuses an older +one. A `.brokkr/blender-editor.ccmp` written under the JSON default is +converted into a new file, never in place: close Blender, stop the daemon, +convert, check the new file opens, then swap it in for the original: + +```text +py -3 -c "import sys; sys.path.insert(0, r'/surfaces/blender/brokkr_bridge'); import blender_target as t; print(t.convert_store(r'/blender-editor.ccmp', r'/blender-editor.mp.ccmp'))" +``` + +The command prints the record count and leaves the source unwritten. + The default node cache is: ```text diff --git a/surfaces/blender/tests/test_store_convert.py b/surfaces/blender/tests/test_store_convert.py new file mode 100644 index 0000000..48fc8da --- /dev/null +++ b/surfaces/blender/tests/test_store_convert.py @@ -0,0 +1,109 @@ +"""convert_store and the CultLib guard. No Blender, no bpy. + +Run: CULTLIB_PACKAGES= python3 -m unittest discover -s surfaces/blender/tests -v +Needs the msgpack package and CultLib main with cultcache-py's MessagePack payload default. +""" +from __future__ import annotations + +import hashlib +import os +import sys +import tempfile +import types +import unittest +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(ADDON)] +sys.modules.setdefault("brokkr_bridge", package) + +from brokkr_bridge import blender_target as bt # noqa: E402 + +PACKAGES = os.environ.get("CULTLIB_PACKAGES", "") + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +@unittest.skipUnless(PACKAGES and Path(PACKAGES).is_dir(), "set CULTLIB_PACKAGES to CultLib's packages directory") +class ConvertStoreTests(unittest.TestCase): + def setUp(self): + self.cultmesh, self.cultcache = bt._load_cultmesh(PACKAGES) + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.dir = Path(self.temp.name) + self.source = self.dir / "blender-editor.ccmp" + self.records = {} + old_definitions = [ + self.cultcache.define_document_type(d.type, payload_codec=self.cultcache.JSON_PAYLOAD_CODEC) + for d in bt.bridge_documents(self.cultcache).values() + ] + node = self.cultmesh.CultMesh.start_node(str(self.source), runtime_id="brokkr-test") + for definition in old_definitions: + node.database.register_document(definition) + key = f"test/{definition.type}" + value = {"schema": definition.type, "id": key, "n": 7, "nested": {"a": [1, 2, "é"]}} + node.database.put(definition, key, value) + self.records[(definition.type, key)] = value + # What the old daemon wrote: a raw JSON receipt envelope. + receipt = {"schema": bt.SYNC_RECEIPT_SCHEMA, "receiptId": "r1", "status": "ok"} + store = self.cultcache.SingleFileMessagePackBackingStore(self.source) + import json + store.push(self.cultcache.CultCacheEnvelope( + key="sync/receipts/r1", type=bt.SYNC_RECEIPT_SCHEMA, payload=json.dumps(receipt).encode(), + stored_at="2026-11-27T00:00:00Z", schema_id=bt.SYNC_RECEIPT_SCHEMA)) + self.records[(bt.SYNC_RECEIPT_SCHEMA, "sync/receipts/r1")] = receipt + + def test_converted_store_opens_under_default(self): + import msgpack + before = sha256(self.source) + destination = self.dir / "blender-editor.mp.ccmp" + count = bt.convert_store(str(self.source), str(destination), PACKAGES) + self.assertEqual(count, len(self.records)) + self.assertEqual(sha256(self.source), before) + + node = self.cultmesh.CultMesh.start_node(str(destination), runtime_id="brokkr-test-new") + documents = bt.bridge_documents(self.cultcache) + for document in documents.values(): + node.database.register_document(document) + node.database.pull() + snapshot = node.database.snapshot() + for (schema, key), value in self.records.items(): + self.assertEqual(snapshot[schema][key], value, (schema, key)) + for envelope in self.cultcache.SingleFileMessagePackBackingStore(destination).pull_all(): + decoded = msgpack.unpackb(envelope.payload, raw=False) # raises ExtraData on a trailing byte + self.assertIsInstance(decoded, dict, envelope.key) + + def test_convert_store_writes_only_a_new_file(self): + destination = self.dir / "new.ccmp" + bt.convert_store(str(self.source), str(destination), PACKAGES) + source_bytes, destination_bytes = self.source.read_bytes(), destination.read_bytes() + with self.assertRaises(Exception) as caught: + bt.convert_store(str(self.source), str(destination), PACKAGES) + self.assertIn("destination_exists", str(caught.exception)) + self.assertEqual(self.source.read_bytes(), source_bytes) + self.assertEqual(destination.read_bytes(), destination_bytes) + + +class LoadGuardTests(unittest.TestCase): + def test_load_cultmesh_refuses_json_default_cultcache(self): + names = ("cultcache_py", "cultmesh_py") + saved = {name: sys.modules.get(name) for name in names} + try: + sys.modules["cultcache_py"] = types.ModuleType("cultcache_py") # no convert + sys.modules["cultmesh_py"] = types.ModuleType("cultmesh_py") + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh("") + self.assertIn("MessagePack payload default", str(caught.exception)) + finally: + for name, module in saved.items(): + if module is None: + sys.modules.pop(name, None) + else: + sys.modules[name] = module + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/check.ps1 b/tools/check.ps1 index c5d8dbb..e0aba41 100644 --- a/tools/check.ps1 +++ b/tools/check.ps1 @@ -88,6 +88,9 @@ try { } & $pythonExe -c "import sys, tempfile; sys.path.insert(0, r'surfaces\blender\brokkr_bridge'); import blender_target; cultmesh, cultcache = blender_target._load_cultmesh(r'$cultLibPackages'); doc = cultcache.define_document_type('brokkr.check.v0'); node = cultmesh.CultMesh.start_node(tempfile.NamedTemporaryFile(suffix='.ccmp').name, runtime_id='brokkr-check'); node.database.register_document(doc); node.database.put(doc, 'check', {'ok': True}); assert node.database.snapshot()['brokkr.check.v0']['check']['ok'] is True; server = cultmesh.CultMesh.serve_node(node, host='127.0.0.1', port=0); assert server.port > 0; server.stop()" Assert-NativeSuccess "Blender adapter CultMesh import" + $env:CULTLIB_PACKAGES = $cultLibPackages + & $pythonExe -m unittest discover -s surfaceslender ests + Assert-NativeSuccess "Blender adapter unit tests" } finally { Pop-Location -- 2.47.3 From 995d98e1bb18f69e5f4c8446bce926b3a4a0c79c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:58:41 +0100 Subject: [PATCH 3/5] daemon: decode through cultcache-rs at CultLib baf4ecf7; convert_store carries MessagePack records; active-state tests Co-Authored-By: Claude Sonnet 5.5 --- brokkr-daemon/Cargo.toml | 2 +- brokkr-daemon/src/main.rs | 132 +++++++++++------- .../blender/brokkr_bridge/blender_target.py | 19 ++- surfaces/blender/docs/install.md | 2 +- surfaces/blender/tests/test_store_convert.py | 20 +++ 5 files changed, 123 insertions(+), 52 deletions(-) diff --git a/brokkr-daemon/Cargo.toml b/brokkr-daemon/Cargo.toml index 5839b77..58bbccf 100644 --- a/brokkr-daemon/Cargo.toml +++ b/brokkr-daemon/Cargo.toml @@ -6,7 +6,7 @@ publish = false [dependencies] anyhow = "1" -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c2a9a6e526390808ef195759056fda0b9a55d8a3", package = "cultcache-rs" } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" } rmp-serde = "1.3" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index be9fbc0..557389b 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -1390,7 +1390,7 @@ impl MirrorStore { fn documents(&mut self) -> Result> { let mut documents = Vec::new(); for envelope in self.store.pull_all()? { - let value = decode_payload(&envelope).with_context(|| { + let value = cultcache_rs::decode_payload::(&envelope.payload).with_context(|| { format!("failed to decode {} at {}", envelope.r#type, envelope.key) })?; documents.push(CacheDocument { @@ -1409,25 +1409,11 @@ impl MirrorStore { payload, stored_at: chrono_like_now(), schema_id: Some(schema.to_string()), - }) + })?; + Ok(()) } } -fn decode_payload(envelope: &CultCacheEnvelope) -> Result { - let mut cursor = io::Cursor::new(envelope.payload.as_slice()); - let value: Value = rmp_serde::decode::from_read(&mut cursor) - .with_context(|| format!("payload is not a MessagePack value for {}", envelope.key))?; - let trailing = envelope.payload.len() as u64 - cursor.position(); - if trailing != 0 { - return Err(anyhow!( - "payload for {} is not exactly one MessagePack value: {} trailing byte(s)", - envelope.key, - trailing - )); - } - Ok(value) -} - fn parse_object_binding(value: &Value) -> Option { Some(ObjectBinding { binding_id: field_string(value, 1, "bindingId")?, @@ -3323,42 +3309,94 @@ mod tests { Ok(()) } - #[test] - fn decode_payload_refuses_trailing_bytes() -> Result<()> { - let mut payload = rmp_serde::to_vec(&json!({"a": 1}))?; - let clean = CultCacheEnvelope { - key: "k/clean".to_string(), - r#type: "t".to_string(), - payload: payload.clone(), - stored_at: String::new(), - schema_id: None, - }; - assert_eq!(decode_payload(&clean)?, json!({"a": 1})); - - payload.push(0xc0); - let dirty = CultCacheEnvelope { - key: "k/dirty".to_string(), + fn raw_envelope(key: &str, payload: Vec) -> CultCacheEnvelope { + CultCacheEnvelope { + key: key.to_string(), + r#type: "brokkr.sync.receipt.v0".to_string(), payload, - ..clean - }; - let message = format!("{:#}", decode_payload(&dirty).unwrap_err()); + stored_at: chrono_like_now(), + schema_id: Some("brokkr.sync.receipt.v0".to_string()), + } + } + + #[test] + fn store_read_refuses_trailing_bytes() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("store.ccmp"); + let mut raw = SingleFileMessagePackBackingStore::new(&path); + let clean = rmp_serde::to_vec(&json!({"a": 1}))?; + raw.push(&raw_envelope("k/clean", clean.clone()))?; + let documents = MirrorStore::open(&path)?.documents()?; + assert_eq!(documents.len(), 1); + assert_eq!(documents[0].value, json!({"a": 1})); + + let mut dirty = clean; + dirty.push(0xc0); + raw.push(&raw_envelope("k/dirty", dirty))?; + let message = format!("{:#}", MirrorStore::open(&path)?.documents().unwrap_err()); assert!(message.contains("k/dirty"), "{message}"); - assert!(message.contains("1 trailing byte"), "{message}"); - assert!(!message.contains("c0"), "{message}"); + assert!(!message.to_lowercase().contains("c0"), "{message}"); Ok(()) } #[test] - fn decode_payload_refuses_json_payload() -> Result<()> { + fn store_read_refuses_json_payload() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("store.ccmp"); let receipt = json!({"schema": "brokkr.sync.receipt.v0", "status": "ok"}); - let envelope = CultCacheEnvelope { - key: "sync/receipts/json".to_string(), - r#type: "brokkr.sync.receipt.v0".to_string(), - payload: serde_json::to_vec(&receipt)?, - stored_at: String::new(), - schema_id: None, - }; - assert!(decode_payload(&envelope).is_err()); + SingleFileMessagePackBackingStore::new(&path) + .push(&raw_envelope("sync/receipts/json", serde_json::to_vec(&receipt)?))?; + let message = format!("{:#}", MirrorStore::open(&path)?.documents().unwrap_err()); + assert!(message.contains("sync/receipts/json"), "{message}"); + Ok(()) + } + + #[test] + fn sync_once_writes_unity_active_state_to_blender_visibility_command() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + let command = MirrorStore::open(&blender_path)? + .documents()? + .into_iter() + .find(|document| document.key.starts_with("blender/commands/")) + .expect("Brokkr should emit a Blender visibility command"); + assert_eq!(command.value["action"], "setObjectVisibility"); + assert_eq!(command.value["targetObjectName"], "Cube"); + assert_eq!(command.value["visible"], true); + Ok(()) + } + + #[test] + fn dry_run_counts_active_state_command_but_writes_none() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: true, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + assert!( + MirrorStore::open(&blender_path)? + .documents()? + .iter() + .all(|document| !document.key.starts_with("blender/commands/")), + "a dry run must not write a command intent" + ); Ok(()) } @@ -3387,7 +3425,7 @@ mod tests { "receipt payload should be a MessagePack map, led by {lead:#04x}" ); assert!(serde_json::from_slice::(&receipt.payload).is_err()); - assert!(decode_payload(receipt)?.is_object()); + assert!(cultcache_rs::decode_payload::(&receipt.payload)?.is_object()); } Ok(()) } diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 1279f97..677f03d 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -1101,11 +1101,24 @@ def bridge_documents(cultcache: Any) -> dict[str, Any]: def convert_store(source: str, destination: str, cultlib_py_src: str = "") -> int: - """Write the records of an older (JSON payload) bridge store to a new MessagePack file and return the count. - The destination must not exist and the source is never written: stop every writer, convert, then swap the files.""" + """Write the records of a bridge store to a new MessagePack file and return the count converted. + JSON payloads (the old default) are converted; MessagePack payloads, such as records the new daemon already + appended to the old store, are carried through. The destination must not exist and the source is never written: + stop every writer, convert, then swap the files.""" _cultmesh, cultcache = _load_cultmesh(cultlib_py_src) + json_codec, msgpack_codec = cultcache.JSON_PAYLOAD_CODEC, cultcache.MESSAGEPACK_PAYLOAD_CODEC + + def decode_either(payload: bytes) -> Any: + # A JSON object or array never starts like a MessagePack map or array, so a payload JSON refuses is MessagePack. + try: + return json_codec.decode(payload) + except Exception: + return msgpack_codec.decode(payload) + + either = cultcache.PayloadCodec("JSON or MessagePack", json_codec.encode, decode_either) return cultcache.convert( - cultcache.SingleFileMessagePackBackingStore(source), destination, bridge_documents(cultcache).values()) + cultcache.SingleFileMessagePackBackingStore(source), destination, bridge_documents(cultcache).values(), + source_codec=either) def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 842f886..3b3a93d 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -26,7 +26,7 @@ convert, check the new file opens, then swap it in for the original: py -3 -c "import sys; sys.path.insert(0, r'/surfaces/blender/brokkr_bridge'); import blender_target as t; print(t.convert_store(r'/blender-editor.ccmp', r'/blender-editor.mp.ccmp'))" ``` -The command prints the record count and leaves the source unwritten. +The command prints the record count and leaves the source unwritten. Records a new daemon already appended (MessagePack) are carried into the new file. The default node cache is: diff --git a/surfaces/blender/tests/test_store_convert.py b/surfaces/blender/tests/test_store_convert.py index 48fc8da..17d6506 100644 --- a/surfaces/blender/tests/test_store_convert.py +++ b/surfaces/blender/tests/test_store_convert.py @@ -76,6 +76,26 @@ class ConvertStoreTests(unittest.TestCase): decoded = msgpack.unpackb(envelope.payload, raw=False) # raises ExtraData on a trailing byte self.assertIsInstance(decoded, dict, envelope.key) + def test_mixed_store_converts_json_and_carries_messagepack(self): + import msgpack + # What the new daemon appends to an old store before the operator converts it. + appended = {"schema": bt.SYNC_RECEIPT_SCHEMA, "receiptId": "r2", "status": "ok"} + self.cultcache.SingleFileMessagePackBackingStore(self.source).push(self.cultcache.CultCacheEnvelope( + key="sync/receipts/r2", type=bt.SYNC_RECEIPT_SCHEMA, payload=msgpack.packb(appended), + stored_at="2026-11-27T01:00:00Z", schema_id=bt.SYNC_RECEIPT_SCHEMA)) + before = sha256(self.source) + destination = self.dir / "mixed.mp.ccmp" + self.assertEqual(bt.convert_store(str(self.source), str(destination), PACKAGES), len(self.records) + 1) + self.assertEqual(sha256(self.source), before) + node = self.cultmesh.CultMesh.start_node(str(destination), runtime_id="brokkr-test-mixed") + for document in bt.bridge_documents(self.cultcache).values(): + node.database.register_document(document) + node.database.pull() + snapshot = node.database.snapshot() + self.assertEqual(snapshot[bt.SYNC_RECEIPT_SCHEMA]["sync/receipts/r2"], appended) + for (schema, key), value in self.records.items(): + self.assertEqual(snapshot[schema][key], value, (schema, key)) + def test_convert_store_writes_only_a_new_file(self): destination = self.dir / "new.ccmp" bt.convert_store(str(self.source), str(destination), PACKAGES) -- 2.47.3 From b1fa30da86c7bcc8142e65e3d8dbfda96e418d5f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 19:00:22 +0100 Subject: [PATCH 4/5] Cargo.lock: cultcache-rs at CultLib baf4ecf7 Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 134 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 130 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6736cc7..dabf833 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,15 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -29,6 +38,15 @@ version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "brokkr-daemon" version = "0.1.0" @@ -83,10 +101,29 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cultcache-rs" -version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=c2a9a6e526390808ef195759056fda0b9a55d8a3#c2a9a6e526390808ef195759056fda0b9a55d8a3" +version = "0.3.1" +source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" dependencies = [ "anyhow", "chrono", @@ -97,20 +134,33 @@ dependencies = [ "serde", "serde_bytes", "serde_json", + "serde_stacker", + "sha2", + "stacker", "uuid", "windows-sys 0.59.0", ] [[package]] name = "cultcache-rs-derive" -version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=c2a9a6e526390808ef195759056fda0b9a55d8a3#c2a9a6e526390808ef195759056fda0b9a55d8a3" +version = "0.2.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" dependencies = [ "proc-macro2", "quote", "syn", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -179,6 +229,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.4.2" @@ -311,6 +371,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -342,6 +411,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quote" version = "1.0.45" @@ -463,6 +542,28 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_stacker" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a" +dependencies = [ + "serde", + "serde_core", + "stacker", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -475,6 +576,19 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "syn" version = "2.0.117" @@ -499,6 +613,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -522,6 +642,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" -- 2.47.3 From f90c8d6f6edc39c733aaba16f3130409c9d370cf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 19:02:07 +0100 Subject: [PATCH 5/5] daemon: rustfmt the changed lines Co-Authored-By: Claude Sonnet 5.5 --- brokkr-daemon/src/main.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index 557389b..f83e29b 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -1390,9 +1390,10 @@ impl MirrorStore { fn documents(&mut self) -> Result> { let mut documents = Vec::new(); for envelope in self.store.pull_all()? { - let value = cultcache_rs::decode_payload::(&envelope.payload).with_context(|| { - format!("failed to decode {} at {}", envelope.r#type, envelope.key) - })?; + let value = + cultcache_rs::decode_payload::(&envelope.payload).with_context(|| { + format!("failed to decode {} at {}", envelope.r#type, envelope.key) + })?; documents.push(CacheDocument { key: envelope.key, value, @@ -3344,8 +3345,10 @@ mod tests { let temp = tempfile::tempdir()?; let path = temp.path().join("store.ccmp"); let receipt = json!({"schema": "brokkr.sync.receipt.v0", "status": "ok"}); - SingleFileMessagePackBackingStore::new(&path) - .push(&raw_envelope("sync/receipts/json", serde_json::to_vec(&receipt)?))?; + SingleFileMessagePackBackingStore::new(&path).push(&raw_envelope( + "sync/receipts/json", + serde_json::to_vec(&receipt)?, + ))?; let message = format!("{:#}", MirrorStore::open(&path)?.documents().unwrap_err()); assert!(message.contains("sync/receipts/json"), "{message}"); Ok(()) -- 2.47.3