From 62e5b2b04e2ff8f07768ebc8a5f62c14b9a7d0c7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 14 Oct 2026 02:11:49 +0200 Subject: [PATCH] cultcache-py: convert writes a new store and never its source; one carried-tree check and NaN key image Deletes migrate_payloads (backup, live-byte compare, swap into the live store) and adds convert(source, destination, definitions) per ruling py-migration-shape-ruled. Both store kinds expose _file_bytes, the one encoder of _replace_all and convert. The MessagePack codec decodes through the same _check_carried it writes through (depth past 256, extension values, timestamps outside years 1 to 9999) and every NaN key is one key image. Tests are updated in the next commit; this commit does not build the test suite. Co-Authored-By: Claude Opus 5.5 --- packages/cultcache-py/README.md | 26 +++--- .../cultcache-py/src/cultcache_py/__init__.py | 4 +- .../cultcache-py/src/cultcache_py/cache.py | 92 +++++++++---------- .../src/cultcache_py/documents.py | 75 ++++++++++----- .../cultcache-py/src/cultcache_py/stores.py | 18 +++- 5 files changed, 123 insertions(+), 92 deletions(-) diff --git a/packages/cultcache-py/README.md b/packages/cultcache-py/README.md index 79d6c6bf..009e32e0 100644 --- a/packages/cultcache-py/README.md +++ b/packages/cultcache-py/README.md @@ -125,23 +125,25 @@ another format is refused with `CultCachePayloadFormatError`, never guessed at. as `duplicate_map_key`, which includes `1` beside `1.0` or `True`: the reference keeps those apart and a Python `dict` cannot. The same keys are refused on write as `duplicate_map_key`, which includes a `Float32` key beside an equal - int, bool or float key: the codec never writes bytes its own reader refuses. + int, bool or float key, and two NaN keys, which are one key: the codec never + writes bytes its own reader refuses. - Arrays and maps nest at most 256 deep (`MAX_PAYLOAD_DEPTH`), on read and on write, in the codec and in the definition alike. - Integers beyond 64 bits (outside `-(2**63)..2**64-1`) are refused on write as `integer_out_of_range`; MessagePack has no wider integer. +- Timestamps lie within years 1 to 9999 (`.NET` `DateTime`), and no extension type + but the timestamp exists: a `msgpack.ExtType` value or a timestamp outside that + range is refused on read and on write as `value_kind` or `timestamp_out_of_range`. - A store written by cultcache-py 0.3 or earlier holds JSON payloads. Define each - type with `payload_codec=JSON_PAYLOAD_CODEC` to read it, or rewrite it once with - `migrate_payloads(store, definitions, backup=path)`. Stop every writer of the - store first. The store's bytes are copied to `backup`, which must not exist; - the copy is read, every record of the listed definitions is rewritten under the - definitions' own codec, and the live file is replaced, once, only if it is still - byte-identical to the copy. The source is never written. Any refusal (a record, - or a store that changed meanwhile) raises `CultCacheError` naming the type, - record key and code, or the path, removes the backup and leaves the store as it - was. The backup is also the guard against a second run, which is refused: payload - bytes cannot tell a migrated store from an unmigrated one. Delete the backup only - after the migrated store opens, and never rerun after deleting it. + type with `payload_codec=JSON_PAYLOAD_CODEC` to read it, or write it as a new store + with `convert(source, destination, definitions)`. Stop every writer of the source + first. `destination` must not exist; every record of the listed definitions is + rewritten under the definitions' own codec, records of other types keep their + bytes, and the new file is fsynced before the call returns. Open it with the + default definitions, then swap it in yourself. The source is never written. A + refused record raises `CultCacheError` naming the type, record key and code, and + leaves no destination; a killed run leaves the source as it was and a partial + destination, so delete the destination and run again. - 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. diff --git a/packages/cultcache-py/src/cultcache_py/__init__.py b/packages/cultcache-py/src/cultcache_py/__init__.py index 4da4c96f..811c0d67 100644 --- a/packages/cultcache-py/src/cultcache_py/__init__.py +++ b/packages/cultcache-py/src/cultcache_py/__init__.py @@ -1,7 +1,7 @@ from .backing_store import BackingStore, CultCacheEnvelope from .backing_store import CultCacheSchemaCatalogEntry, CultCacheSchemaCatalogMember from . import leaves -from .cache import CultCache, CultCacheBuilder, migrate_payloads +from .cache import CultCache, CultCacheBuilder, convert from .documents import ( MAX_PAYLOAD_DEPTH, JSON_PAYLOAD_CODEC, @@ -52,5 +52,5 @@ __all__ = [ "define_document_type", "define_record_codec", "define_union", - "migrate_payloads", + "convert", ] diff --git a/packages/cultcache-py/src/cultcache_py/cache.py b/packages/cultcache-py/src/cultcache_py/cache.py index 9f70d7d0..a20c5d8d 100644 --- a/packages/cultcache-py/src/cultcache_py/cache.py +++ b/packages/cultcache-py/src/cultcache_py/cache.py @@ -590,72 +590,66 @@ class CultCache: return self._state.documents_by_schema_name.get(envelope.type) -def migrate_payloads( - store: SingleFileMessagePackBackingStore | JsonLinesBackingStore, +def convert( + source: SingleFileMessagePackBackingStore | JsonLinesBackingStore, + destination: str | os.PathLike[str], definitions: Iterable[DocumentDefinition[Any]], *, - backup: str | os.PathLike[str], source_codec: PayloadCodec = JSON_PAYLOAD_CODEC, ) -> int: - """Rewrite the records of `definitions` in `store` from `source_codec` to each definition's own codec, whole or not - at all, and return the count rewritten. Stop every writer of the store first: a writer between the copy and the swap - makes the call refuse, but the swap itself takes no cross-process lock. - - The store's bytes are copied to `backup`, which must not exist. The copy is read, every listed record is rewritten - in memory, and only if the store is byte-identical to the copy is it replaced, once, with the result; any refusal - (a record, a changed store) removes the backup and leaves the store as it was. The source is never written. Records - of other types keep their bytes. The backup is also the rerun guard, since payload bytes cannot say whether a store - was migrated (the JSON `5` is the MessagePack `53`): a second call finds it and is refused. Delete the backup only - after the migrated store opens, and never rerun after deleting it. A count of 0 writes nothing and keeps no backup. + """Write the records of `source` to a new store of the same kind at `destination`, the records of `definitions` + rewritten from `source_codec` to each definition's own codec, and return the count rewritten. Records of other types + keep their bytes. Stop every writer of the source before calling. `destination` must not exist: the call creates it + exclusively, and it is complete only once the call returns. A refusal (a record, a failed write) removes it and + leaves the source as it was. A killed run leaves the source intact and a partial destination: delete the destination + and run again. The source is only read, never written; swap the new store in yourself once it opens. A count of 0 + still writes the destination. """ - if not isinstance(store, (SingleFileMessagePackBackingStore, JsonLinesBackingStore)): - raise TypeError(f"migrate_payloads takes a library file store, not {type(store).__name__}") - backup = Path(backup) + if not isinstance(source, (SingleFileMessagePackBackingStore, JsonLinesBackingStore)): + raise TypeError(f"convert takes a library file store, not {type(source).__name__}") + if not source.path.exists(): + raise CultCacheError(f"{source.path} does not exist; there is nothing to convert.") by_type: dict[str, DocumentDefinition[Any]] = {} for definition in definitions: by_type[definition.type] = definition by_type.setdefault(definition.catalog_entry().schema_name, definition) - original = store.path.read_bytes() + destination = Path(destination) + destination.parent.mkdir(parents=True, exist_ok=True) try: - with open(backup, "xb") as copy: - copy.write(original) + target = open(destination, "xb") except FileExistsError: - failure = CultCacheError( - f"{backup} already exists: a migration already ran or was stopped; the store is unchanged." + failure: CultCacheError | None = CultCacheError( + f"{destination} already exists; convert writes only a new store. {source.path} is unchanged." ) else: failure = None if failure is not None: raise failure try: - migrated: list[CultCacheEnvelope] = [] - count = 0 - for envelope in type(store)(backup).pull_all(): - definition = by_type.get(envelope.type) - if definition is not None: - try: - value = replace(definition, payload_codec=source_codec).decode_payload(envelope.payload) - envelope = replace(envelope, payload=definition.encode_payload(value)) - except Exception as refusal: - code = getattr(refusal, "code", type(refusal).__name__) - failure = CultCacheError( - f"Cannot migrate {envelope.type} record {envelope.key}: {code}; the store is unchanged." - ) - else: - count += 1 - if failure is not None: - raise failure - migrated.append(envelope) - if count: - with store._lock: - if store.path.read_bytes() != original: - raise CultCacheError( - f"{store.path} changed during migration; stop every writer and retry. The store is unchanged." - ) - store._replace_all(migrated) + with target: + converted: list[CultCacheEnvelope] = [] + count = 0 + for envelope in source.pull_all(): + definition = by_type.get(envelope.type) + if definition is not None: + try: + value = replace(definition, payload_codec=source_codec).decode_payload(envelope.payload) + envelope = replace(envelope, payload=definition.encode_payload(value)) + except Exception as refusal: + code = getattr(refusal, "code", type(refusal).__name__) + failure = CultCacheError( + f"Cannot convert {envelope.type} record {envelope.key}: {code}; " + "no store was written and the source is unchanged." + ) + else: + count += 1 + if failure is not None: + raise failure + converted.append(envelope) + target.write(type(source)._file_bytes(converted)) + target.flush() + os.fsync(target.fileno()) except BaseException: - backup.unlink(missing_ok=True) + destination.unlink(missing_ok=True) raise - if not count: - backup.unlink() return count diff --git a/packages/cultcache-py/src/cultcache_py/documents.py b/packages/cultcache-py/src/cultcache_py/documents.py index 4050cf16..3e2da58d 100644 --- a/packages/cultcache-py/src/cultcache_py/documents.py +++ b/packages/cultcache-py/src/cultcache_py/documents.py @@ -45,7 +45,8 @@ class CultCachePayloadDepthError(ValueError): class PayloadCodecFault(ValueError): """A codec raises this for a payload its format cannot carry. `code` names the rule (the library's are - `map_key_kind`, `duplicate_map_key`, `integer_out_of_range` and `depth_limit`) and `kind` the kind of node at fault (a MessagePack + `map_key_kind`, `duplicate_map_key`, `integer_out_of_range`, `depth_limit`, `value_kind` and + `timestamp_out_of_range`) and `kind` the kind of node at fault (a MessagePack kind such as `nil` or `bin`); neither is ever a payload value. A consumer-built codec may raise it.""" def __init__(self, code: str, kind: str = "") -> None: @@ -56,8 +57,8 @@ class PayloadCodecFault(ValueError): class CultCachePayloadFormatError(ValueError): """A payload is not one value of its definition's codec (read), or holds a key or integer the codec cannot carry. - Names the type, the codec, the direction and a `code`; `detail` is the fault's class or the key's kind. Never a - payload byte or value.""" + Names the type, the codec, the direction and a `code`; `detail` is the fault's class or the kind of the key or + extension value. Never a payload byte or value.""" def __init__(self, type_name: str, codec: str, direction: str, code: str, detail: str) -> None: self.type_name = type_name @@ -75,6 +76,13 @@ class CultCachePayloadFormatError(ValueError): message = f"{type_name} payload has two map keys Python holds as one; refused on {direction}." elif code == "integer_out_of_range": message = f"{type_name} payload has an integer beyond 64 bits; refused on write." + elif code == "value_kind": + message = ( + f"{type_name} payload holds a value of kind {detail}; " + f"{codec} payloads carry no extension type but the timestamp (refused on {direction})." + ) + elif code == "timestamp_out_of_range": + message = f"{type_name} payload holds a timestamp outside years 1 to 9999; refused on {direction}." else: message = f"{type_name} payload is refused by the {codec} codec ({code}); refused on {direction}." super().__init__(message) @@ -169,6 +177,8 @@ class PayloadCodec: _INTEGER_RANGE = (-(2**63), 2**64 - 1) +_TIMESTAMP_SECONDS = (-62135596800, 253402300799) +_NAN_KEY = object() _KEY_TYPES = (str, int, float, Float32, msgpack.Timestamp) @@ -187,33 +197,43 @@ def _node_kind(node: Any) -> str: return "unsupported" +def _key_image(key: Any) -> Any: + """A map key as the reader holds it, and the one key identity of read and write: a `Float32` is written as float32 + and read back as that float, and every NaN is one key (the reference refuses two of them).""" + if isinstance(key, Float32): + key = struct.unpack(">f", struct.pack(">f", key.value))[0] + return _NAN_KEY if isinstance(key, float) and key != key else key + + def _checked_map(pairs: list[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.""" for key, _ in pairs: if not isinstance(key, _KEY_TYPES): raise PayloadCodecFault("map_key_kind", _node_kind(key)) - held = dict(pairs) - if len(held) != len(pairs): + if len(dict.fromkeys(_key_image(key) for key, _ in pairs)) != len(pairs): raise PayloadCodecFault("duplicate_map_key") - return held + return dict(pairs) -def _key_image(key: Any) -> Any: - """A map key as the reader holds it: a `Float32` is written as float32 and read back as that float.""" - return struct.unpack(">f", struct.pack(">f", key.value))[0] if isinstance(key, Float32) else key - - -def _check_writable(tree: Any) -> None: - """The write side of the key, integer and depth rule: what `_checked_map` refuses on read, and nesting past - `MAX_PAYLOAD_DEPTH`, is refused here, so nothing this codec writes is refused by its own decode. Keys that collide - once decoded (a `Float32` beside an equal int, bool or float) are the reader's duplicate.""" - if isinstance(tree, int) and not _INTEGER_RANGE[0] <= tree <= _INTEGER_RANGE[1]: +def _check_scalar(node: Any) -> None: + if isinstance(node, int) and not _INTEGER_RANGE[0] <= node <= _INTEGER_RANGE[1]: raise PayloadCodecFault("integer_out_of_range") + if isinstance(node, msgpack.Timestamp) and not _TIMESTAMP_SECONDS[0] <= node.seconds <= _TIMESTAMP_SECONDS[1]: + raise PayloadCodecFault("timestamp_out_of_range") + + +def _check_carried(tree: Any) -> None: + """The one check of what a MessagePack payload carries, on read and on write: the keys, integers, timestamps and + nesting the C# reference's object reader takes, no extension type but the timestamp, and no two keys that decode + as one (a `Float32` beside an equal int, bool or float, or two NaNs), so nothing this codec writes is refused by + its own decode.""" + _check_scalar(tree) for node in _containers(tree): + if isinstance(node, msgpack.ExtType): + raise PayloadCodecFault("value_kind", "ext") for child in _children(node): - if isinstance(child, int) and not _INTEGER_RANGE[0] <= child <= _INTEGER_RANGE[1]: - raise PayloadCodecFault("integer_out_of_range") + _check_scalar(child) if isinstance(node, Mapping): for key in node: if not isinstance(key, _KEY_TYPES): @@ -226,8 +246,14 @@ def _unpack_tree(payload: bytes) -> Any: return msgpack.unpackb(payload, raw=False, strict_map_key=False, object_pairs_hook=_checked_map) +def _unpack_checked_tree(payload: bytes) -> Any: + tree = _unpack_tree(payload) + _check_carried(tree) + return tree + + def _pack_checked_tree(tree: Any) -> bytes: - _check_writable(tree) + _check_carried(tree) return _pack_tree(tree) @@ -240,11 +266,12 @@ def _load_json(payload: bytes) -> Any: MESSAGEPACK_PAYLOAD_CODEC = PayloadCodec( - "MessagePack", _pack_checked_tree, _unpack_tree, depth_faults=(msgpack.exceptions.StackError,) + "MessagePack", _pack_checked_tree, _unpack_checked_tree, depth_faults=(msgpack.exceptions.StackError,) ) """The default payload format. It carries what the C# reference's object reader accepts: str, int, float, bool and -timestamp keys, no duplicate key, and integers within -(2**63)..2**64-1, nested no deeper than `MAX_PAYLOAD_DEPTH`. It refuses the rest on read through its -map hook and on write through its encode, so it never writes a record it cannot read.""" +timestamp keys, no duplicate key (two NaN keys are one), integers within -(2**63)..2**64-1, timestamps within years 1 to +9999, no extension type but the timestamp, and nesting no deeper than `MAX_PAYLOAD_DEPTH`. One check refuses the rest on +read and on write, so it 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.""" @@ -404,8 +431,8 @@ def define_document_type( 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 a store written by cultcache-py 0.3 or earlier, and `migrate_payloads` to - rewrite it.""" + `payload_codec=JSON_PAYLOAD_CODEC` to read a store written by cultcache-py 0.3 or earlier, and `convert` to write + it as a new MessagePack store.""" codec = {} if payload_codec is None else {"payload_codec": payload_codec} return DocumentDefinition( type=type, diff --git a/packages/cultcache-py/src/cultcache_py/stores.py b/packages/cultcache-py/src/cultcache_py/stores.py index 3c34c19f..f9a31693 100644 --- a/packages/cultcache-py/src/cultcache_py/stores.py +++ b/packages/cultcache-py/src/cultcache_py/stores.py @@ -70,9 +70,8 @@ class JsonLinesBackingStore: existing = [item for item in self.pull_all() if not (item.type == type and item.key == key)] self._replace_all(existing) - def _replace_all(self, envelopes: list[CultCacheEnvelope]) -> None: - self.path.parent.mkdir(parents=True, exist_ok=True) - temp = self.path.with_suffix(self.path.suffix + ".tmp") + @staticmethod + def _file_bytes(envelopes: list[CultCacheEnvelope]) -> bytes: lines = [] for envelope in sorted(envelopes, key=lambda item: (item.type, item.key)): lines.append(json.dumps({ @@ -81,7 +80,12 @@ class JsonLinesBackingStore: "payload": base64.b64encode(envelope.payload).decode("ascii"), "stored_at": envelope.stored_at, }, ensure_ascii=False, sort_keys=True)) - temp.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8") + return ("\n".join(lines) + ("\n" if lines else "")).encode("utf-8") + + def _replace_all(self, envelopes: list[CultCacheEnvelope]) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + temp = self.path.with_suffix(self.path.suffix + ".tmp") + temp.write_bytes(self._file_bytes(envelopes)) temp.replace(self.path) @@ -120,10 +124,14 @@ class SingleFileMessagePackBackingStore: existing = [item for item in self.pull_all() if not (item.type == type and item.key == key)] self._replace_all(existing) + @staticmethod + def _file_bytes(envelopes: list[CultCacheEnvelope]) -> bytes: + return msgpack.packb(_encode_v1_snapshot(envelopes), use_bin_type=True) # type: ignore[no-any-return] + def _replace_all(self, envelopes: list[CultCacheEnvelope]) -> None: 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.write_bytes(self._file_bytes(envelopes)) temp.replace(self.path)