diff --git a/packages/cultcache-py/README.md b/packages/cultcache-py/README.md index 41c3095c..f09e8be9 100644 --- a/packages/cultcache-py/README.md +++ b/packages/cultcache-py/README.md @@ -26,7 +26,7 @@ discovery, sessions, local server) build on it, mirroring `cultcache-rs` / second store, or a second generic store, raises `CultCacheError`; a write touches exactly one store and nothing is mirrored; once any store is attached, a write whose type has no home raises -- the JSONL store uses only the Python standard library for bootstrap consumers +- `define_document_type(...)` payloads are MessagePack by default; `JSON_PAYLOAD_CODEC` reads stores written by 0.3 and earlier - `define_database_entry_type(...)` emits Rust/C#-style slot-indexed MessagePack array payloads for cross-runtime `DatabaseEntry` contracts @@ -99,7 +99,7 @@ store. Backing stores persist envelopes, not caller domain objects. The cache decodes payloads through registered document definitions and rejects unknown type discriminators. This keeps Python's dynamic runtime from turning persistence into an open polymorphic sewer with a cheerful docstring. -`JsonLinesBackingStore` is the dependency-free control-plane store. It rewrites an atomic JSONL snapshot and base64-encodes payload bytes. It is designed for compact state spines, settings, ledgers, and bootstrap surfaces. +`JsonLinesBackingStore` is the control-plane store. It rewrites an atomic JSONL snapshot and base64-encodes the payload bytes its definition's codec wrote. It is designed for compact state spines, settings, ledgers, and bootstrap surfaces. `SingleFileMessagePackBackingStore` follows the shared CultCache v1 store shape used by the TypeScript, Rust, and C# runtimes: @@ -112,10 +112,28 @@ used by the TypeScript, Rust, and C# runtimes: Large corpora should use a sharded store or a real database. A single snapshot file is a scalpel, not a forklift. +## Payload format + +A definition's `payload_codec` owns its payload bytes. The default, +`MESSAGEPACK_PAYLOAD_CODEC`, writes MessagePack; a store holds no format marker, +so the registered definition decides how every record is read, and a record in +another format is refused with `CultCachePayloadFormatError`, never guessed at. + +- Map keys are `str` or `bytes`; any other key type is refused on write, because + the reader refuses it. Integers beyond 64 bits are refused on write. +- A store written by cultcache-py 0.3 or earlier holds JSON payloads. Read it by + defining the type with `payload_codec=JSON_PAYLOAD_CODEC`, then put each value + under the default definition to rewrite the store as MessagePack. +- A JSON payload that is a single digit (`0` to `9`) is also a valid one-byte + MessagePack integer and reads as 48 to 57 under the default. Documents that + are objects or lists never meet this. +- A `PayloadCodec` you build owns the nesting depth of nodes the library's walk + cannot see (anything that is not a mapping, sequence or set). + ## DatabaseEntry Slot Contract -For cross-runtime cache entries, use `define_database_entry_type(...)` instead -of the generic JSON formatter: +For cross-runtime cache entries, use `define_database_entry_type(...)`, which +fixes the MessagePack slot-array payload: ```python from dataclasses import dataclass diff --git a/packages/cultcache-py/src/cultcache_py/__init__.py b/packages/cultcache-py/src/cultcache_py/__init__.py index dbfac403..78eb7094 100644 --- a/packages/cultcache-py/src/cultcache_py/__init__.py +++ b/packages/cultcache-py/src/cultcache_py/__init__.py @@ -4,10 +4,14 @@ from . import leaves from .cache import CultCache, CultCacheBuilder from .documents import ( MAX_PAYLOAD_DEPTH, + JSON_PAYLOAD_CODEC, MAX_SLOT_KEY, + MESSAGEPACK_PAYLOAD_CODEC, CultCachePayloadDepthError, + CultCachePayloadFormatError, DatabaseEntryField, DocumentDefinition, + PayloadCodec, UnionArm, database_entry_field, define_database_entry_type, @@ -24,14 +28,18 @@ __all__ = [ "CultCache", "CultCacheBuilder", "CultCachePayloadDepthError", + "CultCachePayloadFormatError", "CultCacheEnvelope", "CultCacheSchemaCatalogEntry", "CultCacheSchemaCatalogMember", "DatabaseEntryField", "DocumentDefinition", + "JSON_PAYLOAD_CODEC", "JsonLinesBackingStore", "MAX_PAYLOAD_DEPTH", "MAX_SLOT_KEY", + "MESSAGEPACK_PAYLOAD_CODEC", + "PayloadCodec", "SingleFileMessagePackBackingStore", "SlotCodec", "UnionArm", diff --git a/packages/cultcache-py/src/cultcache_py/documents.py b/packages/cultcache-py/src/cultcache_py/documents.py index 91d09ab8..5eba68b4 100644 --- a/packages/cultcache-py/src/cultcache_py/documents.py +++ b/packages/cultcache-py/src/cultcache_py/documents.py @@ -6,6 +6,8 @@ from collections.abc import Mapping, Sequence, Set from itertools import chain from typing import Any, Callable, Generic, Iterable, TypeVar +import msgpack + from .backing_store import CultCacheSchemaCatalogEntry, CultCacheSchemaCatalogMember from .leaves import Float32, SlotCodec from .leaves import any as _any_leaf @@ -24,13 +26,6 @@ or skipped, the outermost one is depth 1; depth 256 is accepted and 257 refused, MAX_SLOT_KEY = 65535 """The largest slot key a record may define: the largest MessagePack array16 length.""" -try: - from msgpack.exceptions import StackError as _MsgpackStackError - - _STACK_FAULTS: tuple[type[BaseException], ...] = (_MsgpackStackError,) -except ModuleNotFoundError: - _STACK_FAULTS = () - _CONTAINERS = (Mapping, Sequence, Set) _SCALAR_SEQUENCES = (str, bytes, bytearray, memoryview) @@ -47,15 +42,52 @@ class CultCachePayloadDepthError(ValueError): ) -def _refuse_past_depth_limit(tree: Any, type_name: str, direction: str) -> None: - """The one nesting count. Walks a payload tree iteratively (every mapping, sequence and set that is not text or - bytes is a container), refusing the first container past `MAX_PAYLOAD_DEPTH`.""" +class CultCachePayloadFormatError(ValueError): + """A payload is not one value of its definition's codec (read), or holds a map key the codec cannot write (write). + Names the type, the codec, the direction and the fault's class or the key's type; never a payload byte or value.""" + + def __init__(self, type_name: str, codec: str, direction: str, message: str) -> None: + self.type_name = type_name + self.codec = codec + self.direction = direction + super().__init__(message) + + @classmethod + def unreadable(cls, type_name: str, codec: "PayloadCodec", fault: BaseException) -> "CultCachePayloadFormatError": + message = f"{type_name} payload is not one {codec.name} value ({type(fault).__name__}); refused on read." + if codec is MESSAGEPACK_PAYLOAD_CODEC: + message += ( + " A record written by cultcache-py 0.3 or earlier through define_document_type's JSON default is read by" + f" defining {type_name} with payload_codec=JSON_PAYLOAD_CODEC." + ) + return cls(type_name, codec.name, "read", message) + + @classmethod + def unwritable_key(cls, type_name: str, codec: "PayloadCodec", key: Any) -> "CultCachePayloadFormatError": + allowed = " or ".join(kind.__name__ for kind in codec.map_keys or ()) + message = ( + f"{type_name} payload has a map key of type {type(key).__name__}; " + f"{codec.name} payloads take {allowed} keys (refused on write)." + ) + return cls(type_name, codec.name, "write", message) + + +def _check_payload_tree(tree: Any, type_name: str, direction: str, codec: "PayloadCodec") -> None: + """The one walk over a payload tree. Iterative (every mapping, sequence and set that is not text or bytes is a + container): refuses the first container past `MAX_PAYLOAD_DEPTH`, and, on write, a map key the codec cannot write.""" stack = [(tree, 1)] if _is_container(tree) else [] while stack: node, depth = stack.pop() if depth > MAX_PAYLOAD_DEPTH: raise CultCachePayloadDepthError(type_name, direction) - children = chain(node.keys(), node.values()) if isinstance(node, Mapping) else node + if isinstance(node, Mapping): + if direction == "write" and codec.map_keys is not None: + for key in node: + if not isinstance(key, codec.map_keys): + raise CultCachePayloadFormatError.unwritable_key(type_name, codec, key) + children = chain(node.keys(), node.values()) + else: + children = node stack.extend((child, depth + 1) for child in children if _is_container(child)) @@ -77,30 +109,10 @@ def _default_decode(value: Any) -> Any: return value -def _json_payload_encoder(value: Any) -> bytes: - return json.dumps(value, ensure_ascii=False, sort_keys=True).encode("utf-8") - - -def _json_payload_decoder(payload: bytes) -> Any: - return json.loads(payload.decode("utf-8")) - - -def _msgpack() -> Any: - try: - import msgpack # type: ignore - except ModuleNotFoundError as exc: - raise RuntimeError( - "MessagePack payload encoding requires the optional 'msgpack' dependency. " - "Install with: python -m pip install cultcache-py[msgpack]" - ) from exc - return msgpack - - def _pack_tree(tree: Any) -> bytes: """The bytes of the tree the leaves produced. `packb` writes everything but a `Float32`, which it refuses with a TypeError; only then does an iterative walk pack each array and map header and each value, a `Float32` through a single-float packer.""" - msgpack = _msgpack() try: return msgpack.packb(tree, use_bin_type=True) # type: ignore[no-any-return] except TypeError: @@ -124,17 +136,41 @@ def _pack_tree(tree: Any) -> bytes: return b"".join(out) -def _messagepack_payload_decoder(payload: bytes) -> Any: - try: - import msgpack # type: ignore - except ModuleNotFoundError as exc: - raise RuntimeError( - "MessagePack payload decoding requires the optional 'msgpack' dependency. " - "Install with: python -m pip install cultcache-py[msgpack]" - ) from exc +@dataclass(frozen=True) +class PayloadCodec: + """A codec owns one payload format: how a tree becomes bytes and back, which of its decode faults mean the payload + nests past the interpreter's own stack, and which map keys it can write. A consumer-built codec owns the depth of + nodes the depth walk cannot see (anything that is not a Mapping, Sequence or Set).""" + + name: str + encode: Callable[[Any], bytes] + decode: Callable[[bytes], Any] + depth_faults: tuple[type[BaseException], ...] = () + map_keys: tuple[type, ...] | None = None + + +def _unpack_tree(payload: bytes) -> Any: return msgpack.unpackb(payload, raw=False) +def _dump_json(tree: Any) -> bytes: + return json.dumps(tree, ensure_ascii=False, sort_keys=True).encode("utf-8") + + +def _load_json(payload: bytes) -> Any: + return json.loads(payload.decode("utf-8")) + + +MESSAGEPACK_PAYLOAD_CODEC = PayloadCodec( + "MessagePack", _pack_tree, _unpack_tree, depth_faults=(msgpack.exceptions.StackError,), map_keys=(str, bytes) +) +"""The default payload format. `map_keys` is what `unpackb` (strict_map_key) reads back, so the default never writes a +record it cannot read.""" + +JSON_PAYLOAD_CODEC = PayloadCodec("JSON", _dump_json, _load_json, depth_faults=(RecursionError,)) +"""The 0.3 default, kept for stores written before MessagePack: it writes exactly the 0.3 bytes. Never a default.""" + + @dataclass(frozen=True) class DatabaseEntryField: name: str @@ -178,8 +214,7 @@ class DocumentDefinition(Generic[T]): global_document: bool = False name: str | Extractor[T] | None = None indexes: dict[str, str | Extractor[T]] = field(default_factory=dict) - payload_encoder: Callable[[Any], bytes] = _json_payload_encoder - payload_decoder: Callable[[bytes], Any] = _json_payload_decoder + payload_codec: PayloadCodec = MESSAGEPACK_PAYLOAD_CODEC schema_id: str | None = None schema_name: str | None = None schema_version: str | None = None @@ -197,15 +232,18 @@ class DocumentDefinition(Generic[T]): if self.validate: self.validate(value) tree = self.encode(value) - _refuse_past_depth_limit(tree, self.type, "write") - return self.payload_encoder(tree) + _check_payload_tree(tree, self.type, "write", self.payload_codec) + return self.payload_codec.encode(tree) def decode_payload(self, payload: bytes) -> T: + codec = self.payload_codec try: - tree = self.payload_decoder(payload) - except _STACK_FAULTS: + tree = codec.decode(payload) + except codec.depth_faults: raise CultCachePayloadDepthError(self.type, "read") from None - _refuse_past_depth_limit(tree, self.type, "read") + except ValueError as fault: + raise CultCachePayloadFormatError.unreadable(self.type, codec, fault) from None + _check_payload_tree(tree, self.type, "read", codec) value = self.decode(tree) if self.validate: self.validate(value) @@ -262,8 +300,7 @@ def define_document_type( global_document: bool = False, name: str | Extractor[T] | None = None, indexes: dict[str, str | Extractor[T]] | None = None, - payload_encoder: Callable[[Any], bytes] = _json_payload_encoder, - payload_decoder: Callable[[bytes], Any] = _json_payload_decoder, + payload_codec: PayloadCodec = MESSAGEPACK_PAYLOAD_CODEC, schema_id: str | None = None, schema_name: str | None = None, schema_version: str | None = None, @@ -272,6 +309,8 @@ def define_document_type( compatible_schema_ids: Iterable[str] | None = None, members: Iterable[CultCacheSchemaCatalogMember] | Callable[[], tuple[CultCacheSchemaCatalogMember, ...]] | None = None, ) -> DocumentDefinition[T]: + """Define a document type. Its payload is the MessagePack of what `encode` returns; pass + `payload_codec=JSON_PAYLOAD_CODEC` to read and rewrite a store written by cultcache-py 0.3 or earlier.""" return DocumentDefinition( type=type, encode=encode, @@ -280,8 +319,7 @@ def define_document_type( global_document=global_document, name=name, indexes=indexes or {}, - payload_encoder=payload_encoder, - payload_decoder=payload_decoder, + payload_codec=payload_codec, schema_id=schema_id, schema_name=schema_name, schema_version=schema_version, @@ -344,8 +382,6 @@ def define_database_entry_type( global_document=global_document, name=name, indexes=indexes, - payload_encoder=_pack_tree, - payload_decoder=_messagepack_payload_decoder, schema_id=schema_id, schema_name=schema_name, schema_version=schema_version, diff --git a/packages/cultcache-py/src/cultcache_py/stores.py b/packages/cultcache-py/src/cultcache_py/stores.py index 704a3851..42ed031c 100644 --- a/packages/cultcache-py/src/cultcache_py/stores.py +++ b/packages/cultcache-py/src/cultcache_py/stores.py @@ -7,6 +7,8 @@ import threading from pathlib import Path from typing import Any, Callable, TypeVar +import msgpack + from .backing_store import ( CultCacheEnvelope, CultCacheSchemaCatalogEntry, @@ -88,7 +90,6 @@ class SingleFileMessagePackBackingStore: self._lock = threading.RLock() def pull_all(self) -> list[CultCacheEnvelope]: - msgpack = self._msgpack() with self._lock: # An empty file is not a store (no writer leaves one), so it is decoded and refused. data = _read_store(self.path, Path.read_bytes) @@ -98,7 +99,7 @@ class SingleFileMessagePackBackingStore: snapshot = _decode_v1_snapshot(decoded) if snapshot is not None: return snapshot - return _decode_legacy_envelopes(decoded, msgpack) + return _decode_legacy_envelopes(decoded) def push(self, envelope: CultCacheEnvelope) -> None: with self._lock: @@ -119,23 +120,11 @@ class SingleFileMessagePackBackingStore: self._replace_all(existing) def _replace_all(self, envelopes: list[CultCacheEnvelope]) -> None: - msgpack = self._msgpack() self.path.parent.mkdir(parents=True, exist_ok=True) temp = self.path.with_suffix(self.path.suffix + ".tmp") temp.write_bytes(msgpack.packb(_encode_v1_snapshot(envelopes), use_bin_type=True)) temp.replace(self.path) - @staticmethod - def _msgpack() -> Any: - try: - import msgpack # type: ignore - except ModuleNotFoundError as exc: - raise RuntimeError( - "SingleFileMessagePackBackingStore requires the optional 'msgpack' dependency. " - "Install with: python -m pip install cultcache-py[msgpack]" - ) from exc - return msgpack - def _encode_v1_snapshot(envelopes: list[CultCacheEnvelope]) -> list[Any]: catalog_by_schema_id: dict[str, CultCacheSchemaCatalogEntry] = {} @@ -252,7 +241,7 @@ def _decode_v1_snapshot(decoded: Any) -> list[CultCacheEnvelope] | None: return envelopes -def _decode_legacy_envelopes(decoded: Any, msgpack: Any) -> list[CultCacheEnvelope]: +def _decode_legacy_envelopes(decoded: Any) -> list[CultCacheEnvelope]: if not isinstance(decoded, list): raise ValueError("CultCache MessagePack store is not a recognized snapshot") envelopes: list[CultCacheEnvelope] = [] @@ -380,7 +369,6 @@ def _normalize_payload(payload: Any) -> bytes: def _infer_schema_version_from_payload(payload: bytes) -> str | None: try: - msgpack = SingleFileMessagePackBackingStore._msgpack() decoded = msgpack.unpackb(payload, raw=False) except Exception: return None diff --git a/packages/cultcache-py/tests/test_payload_codec.py b/packages/cultcache-py/tests/test_payload_codec.py new file mode 100644 index 00000000..d05b4b6b --- /dev/null +++ b/packages/cultcache-py/tests/test_payload_codec.py @@ -0,0 +1,168 @@ +from __future__ import annotations + +import collections +import shutil +import tempfile +import unittest +from pathlib import Path + +from cultcache_py import ( + JSON_PAYLOAD_CODEC, + MESSAGEPACK_PAYLOAD_CODEC, + CultCache, + CultCacheEnvelope, + CultCachePayloadDepthError, + CultCachePayloadFormatError, + PayloadCodec, + SingleFileMessagePackBackingStore, + define_database_entry_type, + define_document_type, +) + +CANARY = "CANARY-payload-codec-5b81e0" +LEGACY_JSON = b'{"n": 1, "schema": "x"}' + + +def _store_with(path: Path, payload: bytes) -> SingleFileMessagePackBackingStore: + store = SingleFileMessagePackBackingStore(path) + store.push(CultCacheEnvelope.create(key="k", type="tests.legacy", payload=payload)) + return store + + +class PayloadCodecTests(unittest.TestCase): + def setUp(self) -> None: + self.directory = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.directory, True) + + def _cache(self, document, store) -> CultCache: + return CultCache.builder().register_document_type(document).add_generic_store(store).build() + + def test_the_default_is_messagepack_for_both_definitions(self) -> None: + document = define_document_type("tests.x") + self.assertIs(document.payload_codec, MESSAGEPACK_PAYLOAD_CODEC) + self.assertEqual(document.encode_payload({"a": [1]}), bytes.fromhex("81a1619101")) + self.assertIs(define_database_entry_type("tests.entry", [("a", 0)]).payload_codec, MESSAGEPACK_PAYLOAD_CODEC) + + def test_the_json_codec_writes_the_0_3_bytes(self) -> None: + written = JSON_PAYLOAD_CODEC.encode({"b": "é", "a": [1, 2]}) + self.assertEqual(written, b'{"a": [1, 2], "b": "\xc3\xa9"}') + self.assertEqual(JSON_PAYLOAD_CODEC.decode(written), {"a": [1, 2], "b": "é"}) + + def test_a_json_store_is_refused_typed_with_the_remedy_and_loads_nothing(self) -> None: + store = _store_with(self.directory / "legacy.cc", LEGACY_JSON) + document = define_document_type("tests.legacy") + cache = self._cache(document, store) + with self.assertRaises(CultCachePayloadFormatError) as caught: + cache.pull_all_backing_stores() + message = str(caught.exception) + self.assertEqual((caught.exception.type_name, caught.exception.codec, caught.exception.direction), ("tests.legacy", "MessagePack", "read")) + self.assertIn("tests.legacy", message) + self.assertIn("MessagePack", message) + self.assertIn("payload_codec=JSON_PAYLOAD_CODEC", message) + self.assertNotIn("schema", message) + self.assertEqual(cache.get_all(document), []) + + def test_a_json_store_opted_in_reads_and_migrates_to_messagepack(self) -> None: + path = self.directory / "legacy.cc" + store = _store_with(path, LEGACY_JSON) + legacy = define_document_type("tests.legacy", payload_codec=JSON_PAYLOAD_CODEC) + old = self._cache(legacy, store) + old.pull_all_backing_stores() + self.assertEqual(old.get(legacy, "k"), {"n": 1, "schema": "x"}) + modern = define_document_type("tests.legacy") + new = self._cache(modern, SingleFileMessagePackBackingStore(path)) + new.put(modern, "k", old.get(legacy, "k")) + reread = self._cache(modern, SingleFileMessagePackBackingStore(path)) + reread.pull_all_backing_stores() + self.assertEqual(reread.get(modern, "k"), {"n": 1, "schema": "x"}) + self.assertEqual(reread.get_envelope(modern, "k").payload, MESSAGEPACK_PAYLOAD_CODEC.encode({"n": 1, "schema": "x"})) + + def test_wrong_format_payloads_are_typed_refusals_on_both_sides(self) -> None: + document = define_document_type("tests.faults") + for payload in (b"[1,2]", b'"hi"', b"true", b"null", b"1.5", b"-3", b"12", b"\x93\x01\x02", b"\xc1", b"\xa2\xff\xfe"): + with self.subTest(payload=payload): + with self.assertRaises(CultCachePayloadFormatError): + document.decode_payload(payload) + json_document = define_document_type("tests.faults", payload_codec=JSON_PAYLOAD_CODEC) + with self.assertRaises(CultCachePayloadFormatError) as caught: + json_document.decode_payload(MESSAGEPACK_PAYLOAD_CODEC.encode({"a": 1})) + self.assertNotIn("JSON_PAYLOAD_CODEC", str(caught.exception)) + self.assertIn("JSON", str(caught.exception)) + + def test_the_refusals_never_echo_the_payload_or_the_key(self) -> None: + document = define_document_type("tests.canary") + with self.assertRaises(CultCachePayloadFormatError) as read: + document.decode_payload(('{"' + CANARY + '": 1}').encode()) + self.assertNotIn(CANARY, str(read.exception)) + with self.assertRaises(CultCachePayloadFormatError) as write: + define_document_type("tests.canary", encode=lambda value: value).encode_payload({7351904: CANARY}) + self.assertNotIn("7351904", str(write.exception)) + self.assertNotIn(CANARY, str(write.exception)) + self.assertIsNone(read.exception.__cause__) + + def test_a_one_digit_json_text_reads_as_a_messagepack_integer(self) -> None: + self.assertEqual(define_document_type("tests.digit").decode_payload(b"5"), 53) + + def test_depth_faults_belong_to_the_codec(self) -> None: + def deep(payload: bytes) -> object: + raise RecursionError + + declaring = define_document_type("tests.d", payload_codec=PayloadCodec("t", lambda tree: b"", deep, depth_faults=(RecursionError,))) + with self.assertRaises(CultCachePayloadDepthError): + declaring.decode_payload(b"x") + silent = define_document_type("tests.d", payload_codec=PayloadCodec("t", lambda tree: b"", deep)) + with self.assertRaises(RecursionError) as caught: + silent.decode_payload(b"x") + self.assertNotIsInstance(caught.exception, CultCachePayloadDepthError) + + def test_a_codec_decode_fault_that_is_a_value_error_is_a_format_error_naming_its_class(self) -> None: + def refuse(payload: bytes) -> object: + raise KeyError(CANARY) + + document = define_document_type("tests.v", payload_codec=PayloadCodec("t", lambda tree: b"", lambda payload: int("x"))) + with self.assertRaises(CultCachePayloadFormatError) as caught: + document.decode_payload(b"x") + self.assertIn("(ValueError)", str(caught.exception)) + passthrough = define_document_type("tests.v", payload_codec=PayloadCodec("t", lambda tree: b"", refuse)) + with self.assertRaises(KeyError): + passthrough.decode_payload(b"x") + + def test_map_keys_the_default_cannot_read_back_are_refused_on_write(self) -> None: + document = define_document_type("tests.keys", encode=lambda value: value) + for tree, key_type in (({1: "a"}, "int"), ({True: 1}, "bool"), ({"a": {2: 3}}, "int"), ({"a": [{1.5: 1}]}, "float")): + with self.subTest(tree=tree): + with self.assertRaises(CultCachePayloadFormatError) as caught: + document.encode_payload(tree) + self.assertEqual( + str(caught.exception), + f"tests.keys payload has a map key of type {key_type}; MessagePack payloads take str or bytes keys (refused on write).", + ) + tree = {"a": 1, b"b": {"c": [2]}} + self.assertEqual(document.decode_payload(document.encode_payload(tree)), tree) + legacy = define_document_type("tests.keys", encode=lambda value: value, payload_codec=JSON_PAYLOAD_CODEC) + self.assertEqual(legacy.encode_payload({1: "a"}), b'{"1": "a"}') + + def test_a_refused_key_reaches_no_store(self) -> None: + document = define_document_type("tests.keys", encode=lambda value: value) + store = SingleFileMessagePackBackingStore(self.directory / "keys.cc") + cache = self._cache(document, store) + with self.assertRaises(CultCachePayloadFormatError): + cache.put(document, "k", {1: "a"}) + self.assertEqual(store.pull_all(), []) + + def test_the_library_codecs_refuse_nodes_the_depth_walk_cannot_see(self) -> None: + class OnlyIter: + def __iter__(self): + return iter([1]) + + nodes = (OnlyIter(), collections.deque([1]), collections.UserDict(a=1), frozenset([1])) + for codec in (MESSAGEPACK_PAYLOAD_CODEC, JSON_PAYLOAD_CODEC): + document = define_document_type("tests.unseen", encode=lambda value: value, payload_codec=codec) + for node in nodes: + with self.subTest(codec=codec.name, node=type(node).__name__): + with self.assertRaises(TypeError): + document.encode_payload({"a": node}) + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/cultcache-py/tests/test_union_parity.py b/packages/cultcache-py/tests/test_union_parity.py index e6fe6c2f..7193d0c5 100644 --- a/packages/cultcache-py/tests/test_union_parity.py +++ b/packages/cultcache-py/tests/test_union_parity.py @@ -15,8 +15,10 @@ from cultcache_py import ( MAX_PAYLOAD_DEPTH, MAX_SLOT_KEY, CultCache, + JSON_PAYLOAD_CODEC, CultCachePayloadDepthError, DatabaseEntryField, + PayloadCodec, SlotCodec, SingleFileMessagePackBackingStore, UnionArm, @@ -560,17 +562,18 @@ class BoundsVectorTests(unittest.TestCase): with self.assertRaises(CultCachePayloadDepthError) as caught: tree.encode_payload(_nest(5000)) self.assertIn("refused on write", str(caught.exception)) - document = define_document_type("tests.json_tree") - with self.assertRaises(CultCachePayloadDepthError) as read: - document.decode_payload(b"[" * 300 + b"]" * 300) - self.assertIn("refused on read", str(read.exception)) + for codec, deep in ((None, b"\x91" * 300 + b"\xc0"), (JSON_PAYLOAD_CODEC, b"[" * 300 + b"]" * 300)): + document = define_document_type("tests.json_tree") if codec is None else define_document_type("tests.json_tree", payload_codec=codec) + with self.assertRaises(CultCachePayloadDepthError) as read: + document.decode_payload(deep) + self.assertIn("refused on read", str(read.exception)) def test_a_codec_that_exhausts_the_interpreter_stack_keeps_its_own_recursion_error_on_each_side(self) -> None: def boom(value: object) -> object: return boom(value) document = define_document_type("tests.boom", encode=boom, decode=boom) - for run in (lambda: document.encode_payload("x"), lambda: document.decode_payload(b'"x"')): + for run in (lambda: document.encode_payload("x"), lambda: document.decode_payload(b"\xa1x")): try: run() except RecursionError as caught: @@ -585,11 +588,11 @@ class BoundsVectorTests(unittest.TestCase): "tests.union_surface payload nests 257 containers deep; the limit is 256 (refused on read).", ) - def test_a_json_payload_past_the_interpreters_own_stack_keeps_the_decoders_recursion_error(self) -> None: - document = define_document_type("tests.json_tree") - with self.assertRaises(RecursionError) as caught: + def test_json_text_past_the_interpreters_own_stack_is_the_depth_refusal(self) -> None: + document = define_document_type("tests.json_tree", payload_codec=JSON_PAYLOAD_CODEC) + with self.assertRaises(CultCachePayloadDepthError) as caught: document.decode_payload(b"[" * 100000) - self.assertNotIsInstance(caught.exception, CultCachePayloadDepthError) + self.assertIn("refused on read", str(caught.exception)) def test_a_refusal_reports_the_depth_where_the_walk_stopped_whatever_the_payloads_real_depth(self) -> None: document = define_document_type("tests.json_tree", encode=lambda value: value) @@ -598,7 +601,7 @@ class BoundsVectorTests(unittest.TestCase): document.encode_payload(_nest(depth)) self.assertEqual((write.exception.depth, write.exception.limit), (257, 256), depth) with self.assertRaises(CultCachePayloadDepthError) as read: - document.decode_payload(b"[" * depth + b"]" * depth) + document.decode_payload(b"\x91" * depth + b"\xc0") self.assertEqual((read.exception.depth, read.exception.limit), (257, 256), depth) def test_the_validator_sees_the_value_on_write_and_the_decoded_value_on_read(self) -> None: @@ -615,6 +618,9 @@ class BoundsVectorTests(unittest.TestCase): document.encode_payload(loop) +_STUB_CODEC = PayloadCodec("test", lambda tree: b"ok", lambda payload: payload) + + def _nest(depth: int, mixed: bool = False) -> object: value: object = "leaf" for level in range(depth): @@ -631,18 +637,19 @@ class PayloadDepthRuleTests(unittest.TestCase): def test_the_limit_is_256_and_depth_256_is_accepted_on_read_and_write_while_257_is_refused(self) -> None: self.assertEqual(MAX_PAYLOAD_DEPTH, 256) - document = define_document_type("tests.json_tree", encode=lambda value: value) - for mixed in (False, True): - at_limit = _nest(256, mixed) - self.assertEqual(document.decode_payload(document.encode_payload(at_limit)), at_limit) - past = _nest(257, mixed) - with self.assertRaises(CultCachePayloadDepthError): - document.encode_payload(past) - with self.assertRaises(CultCachePayloadDepthError): - document.decode_payload(document.payload_encoder(past)) + for codec in (None, JSON_PAYLOAD_CODEC): + document = define_document_type("tests.json_tree", encode=lambda value: value, **({} if codec is None else {"payload_codec": codec})) + for mixed in (False, True): + at_limit = _nest(256, mixed) + self.assertEqual(document.decode_payload(document.encode_payload(at_limit)), at_limit) + past = _nest(257, mixed) + with self.assertRaises(CultCachePayloadDepthError): + document.encode_payload(past) + with self.assertRaises(CultCachePayloadDepthError): + document.decode_payload(document.payload_codec.encode(past)) def test_a_tuple_and_a_container_dict_key_count_as_containers(self) -> None: - document = define_document_type("tests.tuple_tree", encode=lambda value: value, payload_encoder=lambda tree: b"ok") + document = define_document_type("tests.tuple_tree", encode=lambda value: value, payload_codec=_STUB_CODEC) self.assertEqual(document.encode_payload(_as_tuple(_nest(256))), b"ok") with self.assertRaises(CultCachePayloadDepthError): document.encode_payload(_as_tuple(_nest(257))) @@ -658,19 +665,21 @@ class PayloadDepthRuleTests(unittest.TestCase): "userlist": lambda inner: collections.UserList([inner]), } for name, wrap in wrappers.items(): - document = define_document_type(f"tests.{name}", encode=lambda value: value, payload_encoder=lambda tree: b"ok") + document = define_document_type(f"tests.{name}", encode=lambda value: value, payload_codec=_STUB_CODEC) at_limit: object = "leaf" for _ in range(256): at_limit = wrap(at_limit) self.assertEqual(document.encode_payload(at_limit), b"ok", name) with self.assertRaises(CultCachePayloadDepthError, msg=name): document.encode_payload(wrap(at_limit)) - decoding = define_document_type(f"tests.{name}.read", payload_decoder=lambda payload, w=wrap: w(at_limit)) + decoding = define_document_type( + f"tests.{name}.read", payload_codec=PayloadCodec("test", lambda tree: b"ok", lambda payload, w=wrap: w(at_limit)) + ) with self.assertRaises(CultCachePayloadDepthError, msg=name): decoding.decode_payload(b"x") def test_text_and_bytes_are_leaves_however_long(self) -> None: - document = define_document_type("tests.leaves", encode=lambda value: value, payload_encoder=lambda tree: b"ok") + document = define_document_type("tests.leaves", encode=lambda value: value, payload_codec=_STUB_CODEC) self.assertEqual(document.encode_payload([["x" * 100000, b"y" * 100000, bytearray(5), memoryview(b"z")]]), b"ok") def test_a_scalar_payload_has_no_depth(self) -> None: diff --git a/packages/cultnet-py/src/cultnet_py/interop_peer.py b/packages/cultnet-py/src/cultnet_py/interop_peer.py index ba236686..4cac8e1c 100644 --- a/packages/cultnet-py/src/cultnet_py/interop_peer.py +++ b/packages/cultnet-py/src/cultnet_py/interop_peer.py @@ -969,8 +969,6 @@ def binding( document_type, encode=encode_slots, decode=decode_slots, - payload_encoder=lambda value: msgpack.packb(value, use_bin_type=True), - payload_decoder=lambda payload: msgpack.unpackb(payload, raw=False), schema_id=schema_id, schema_name=document_type, schema_version=schema_version, diff --git a/packages/cultnet-py/tests/test_cultnet.py b/packages/cultnet-py/tests/test_cultnet.py index 3c5793c1..5b78db1c 100644 --- a/packages/cultnet-py/tests/test_cultnet.py +++ b/packages/cultnet-py/tests/test_cultnet.py @@ -24,6 +24,7 @@ from cultnet_py.compare_csharp import ( ) from cultnet_py.interop_peer import ( append_shard_log_put, + binding, build_state, handle_server_message, raw_snapshot_response, @@ -2508,6 +2509,12 @@ class CultNetTests(unittest.TestCase): self.assertEqual(response["shardLogSequence"], 1) self.assertEqual([record["recordKey"] for record in response["documents"]], ["note:logged"]) + def test_python_interop_peer_binding_writes_plain_messagepack_slots(self) -> None: + # The bytes the binding wrote before it stopped passing its own codec lambdas: packb of the slot array. + note = binding("tests.note", "tests.note.v1", "tests.note.v1", "{}", lambda value: ["a", 1], lambda slots: slots) + self.assertEqual(note.document.encode_payload({}), bytes.fromhex("92a16101")) + self.assertEqual(note.document.decode_payload(bytes.fromhex("92a16101")), ["a", 1]) + def test_python_interop_peer_refuses_v1_selection_messages(self) -> None: # R-2, owed by Cut 1 (docs/cultnet-selection-cut.md, section 9): a v0-only peer refuses any # non-v0 message loudly - cultnet.error.v0 { code: "unsupported_schema_version" } - rather than