From 246a7ea7d43f0166a25b2c01e741254900014201 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 19:39:21 +0100 Subject: [PATCH] cultcache-py: map payloads decode under msgpack's pure-Python fallback The object_pairs_hook took its pairs as a list; msgpack's fallback passes a generator, so len() failed and every map payload was unreadable with a pure-Python msgpack (a Blender extension wheel, MSGPACK_PUREPYTHON=1). Reported by Nibu while bundling msgpack into the Brokkr add-on. Co-Authored-By: Claude Opus 5.5 --- packages/cultcache-py/CHANGELOG.md | 4 +++ .../src/cultcache_py/documents.py | 6 +++-- .../cultcache-py/tests/test_payload_codec.py | 27 +++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/packages/cultcache-py/CHANGELOG.md b/packages/cultcache-py/CHANGELOG.md index 738be0b0..3319863f 100644 --- a/packages/cultcache-py/CHANGELOG.md +++ b/packages/cultcache-py/CHANGELOG.md @@ -7,6 +7,10 @@ - Breaking: `define_document_type` writes and reads MessagePack payloads by default (`cultlib-gaps:ruling:py-msgpack-default`); it wrote JSON until 0.3. A definition's `payload_codec` (`PayloadCodec`, with `MESSAGEPACK_PAYLOAD_CODEC` and `JSON_PAYLOAD_CODEC` exported) owns its payload format, replacing the `payload_encoder` and `payload_decoder` parameters and fields, so no definition carries a second author of the format. A store written by 0.3 or earlier holds JSON: define its types with `payload_codec=JSON_PAYLOAD_CODEC` to read them, or write a new MessagePack store with `convert(source, destination, definitions)`, which never writes its source. The MessagePack codec takes the keys, integers, timestamps and nesting the C# reference's object reader takes and refuses the rest on read and on write (`CultCachePayloadFormatError`, `PayloadCodecFault`; see the README, Payload format); the single-file store's reader takes the same map keys. A 0.3 JSON payload that is an object or list is refused by count as a payload with bytes after its first MessagePack value, a `ValueError`. `define_database_entry_type` inherits the checked codec too: main wrote `{b'k': 1}` in an untyped slot, which is now refused on write, and a bin map key in an entry payload is refused on read where main read it, so a main-era store with a bin-keyed entry fails to load. The checked codec walks each tree twice (the depth walk, then the carried-value check), which roughly doubles entry and document codec cost; the double walk is left in place. The JSON codec's `depth_faults=(RecursionError,)` gives a JSON payload nested past the interpreter's stack the typed `CultCachePayloadDepthError`, which resolves the deferred `cut-union-bounds-py.s2.depth-typed-refusal-lost` for the JSON codec only. This is the same minor bump as the rest of this section: 0.4.0 is not yet tagged. - `parse_stored_at` (was `_parse_stored_at`) is public: cultmesh-py judges a peer's `storedAt` by it. A peer's `document_put_raw` whose `storedAt` is missing, empty or not a stamp is refused `message_invalid` (field `document`) and nothing is minted or stored (variants:ruling:raw-put-without-stamp-refused). A subscribed server's stampless put now raises `ValueError` from `CultMeshClient.read_next_change` instead of being stored under a minted stamp. +### Fixed + +- MessagePack payloads decode under msgpack's pure-Python fallback (`MSGPACK_PUREPYTHON=1`, or a pure-Python wheel such as an embedded interpreter ships): the map hook took the pairs as a list, and the fallback passes a generator, so every map payload failed. + ### Added - `CultCacheError` is exported from the package root (`from cultcache_py import CultCacheError`); it was reachable only from the private `cultcache_py.cache` module. diff --git a/packages/cultcache-py/src/cultcache_py/documents.py b/packages/cultcache-py/src/cultcache_py/documents.py index ef376eff..7a171292 100644 --- a/packages/cultcache-py/src/cultcache_py/documents.py +++ b/packages/cultcache-py/src/cultcache_py/documents.py @@ -248,9 +248,11 @@ def _key_image(key: Any) -> Any: return _NAN_KEY if isinstance(key, float) and key != key else key -def _checked_map(pairs: list[tuple[Any, Any]]) -> dict[Any, Any]: +def _checked_map(pairs: Iterable[tuple[Any, Any]]) -> dict[Any, Any]: """The read hook of every MessagePack map: the keys the C# reference's object reader accepts (str, int, float, - bool, timestamp) and no duplicate.""" + bool, timestamp) and no duplicate. msgpack's C extension passes a list and its pure-Python fallback a generator, + so the pairs are taken once.""" + pairs = list(pairs) for key, _ in pairs: if not isinstance(key, _KEY_TYPES): raise PayloadCodecFault("map_key_kind", _node_kind(key)) diff --git a/packages/cultcache-py/tests/test_payload_codec.py b/packages/cultcache-py/tests/test_payload_codec.py index bd1720d9..45b35bd0 100644 --- a/packages/cultcache-py/tests/test_payload_codec.py +++ b/packages/cultcache-py/tests/test_payload_codec.py @@ -1061,5 +1061,32 @@ class ConvertTests(unittest.TestCase): self.assertTrue(destination.exists()) +PURE_PYTHON_PROBE = """ +import msgpack, msgpack.fallback +assert msgpack.Unpacker is msgpack.fallback.Unpacker, "msgpack is not on its pure-Python fallback" +from cultcache_py import MESSAGEPACK_PAYLOAD_CODEC, PayloadCodecFault +value = {"name": "hull", "parts": [{"id": 1, "mass": 2.5}, {"id": 2, "tags": {"a": True}}]} +assert MESSAGEPACK_PAYLOAD_CODEC.decode(msgpack.packb(value)) == value +try: + MESSAGEPACK_PAYLOAD_CODEC.decode(bytes.fromhex("82 a1 61 01 a1 61 02")) +except PayloadCodecFault as fault: + assert fault.code == "duplicate_map_key", fault.code +else: + raise AssertionError("a duplicate key was read") +""" + + +class PurePythonMsgpackTests(unittest.TestCase): + def test_maps_decode_and_refuse_duplicates_on_the_pure_python_fallback(self) -> None: + # msgpack's C extension hands object_pairs_hook a list, its fallback a generator; the map hook takes either. + import subprocess + import sys + + source = str(Path(__file__).resolve().parents[1] / "src") + env = dict(os.environ, MSGPACK_PUREPYTHON="1", PYTHONPATH=os.pathsep.join(filter(None, [source, os.environ.get("PYTHONPATH")]))) + run = subprocess.run([sys.executable, "-c", PURE_PYTHON_PROBE], env=env, capture_output=True, text=True) + self.assertEqual(run.returncode, 0, run.stderr) + + if __name__ == "__main__": unittest.main() -- 2.47.3