From ecfbaa8baaab707c159f2e8edd0674f5ccf498db Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 14 Oct 2026 03:21:40 +0200 Subject: [PATCH] cultcache-py convert: create the destination inside its cleanup scope; refusals name the argument and a code, never a path Fixes s4 interrupt-window-leaves-destination and convert-refusals-echo-paths. The mixed-width NaN documented-refusal test reads the README paragraph of the previous commit. Not run on this workstation. Co-Authored-By: Claude Opus 5.5 --- .../cultcache-py/src/cultcache_py/cache.py | 85 ++++++------ .../cultcache-py/tests/test_payload_codec.py | 127 +++++++++++++++++- 2 files changed, 168 insertions(+), 44 deletions(-) diff --git a/packages/cultcache-py/src/cultcache_py/cache.py b/packages/cultcache-py/src/cultcache_py/cache.py index a20c5d8d..02df6de0 100644 --- a/packages/cultcache-py/src/cultcache_py/cache.py +++ b/packages/cultcache-py/src/cultcache_py/cache.py @@ -600,56 +600,63 @@ def convert( """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. + exclusively, and it is complete only once the call returns. A refusal (a record, a failed write) or an interrupt + after the create 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. A file another process creates at the destination between the + existence check and the create is refused and left alone. 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(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.") + raise CultCacheError("convert: argument source does not exist (source_missing); 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) destination = Path(destination) destination.parent.mkdir(parents=True, exist_ok=True) + exists = CultCacheError( + "convert: argument destination already exists (destination_exists); convert writes only a new store, " + "and the source is unchanged." + ) + if destination.exists(): + raise exists + refused = False + failure: CultCacheError | None = None try: - target = open(destination, "xb") - except FileExistsError: - 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: - 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()) + try: + target = open(destination, "xb") + except FileExistsError: + refused = True + else: + 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: - destination.unlink(missing_ok=True) + if not refused: + destination.unlink(missing_ok=True) raise + if refused: + raise exists return count diff --git a/packages/cultcache-py/tests/test_payload_codec.py b/packages/cultcache-py/tests/test_payload_codec.py index 1f9446c4..2250478a 100644 --- a/packages/cultcache-py/tests/test_payload_codec.py +++ b/packages/cultcache-py/tests/test_payload_codec.py @@ -334,6 +334,19 @@ class PayloadCodecTests(unittest.TestCase): refusal = self._refused(document.decode_payload, bytes.fromhex("91d40100")) self.assertEqual((refusal.code, str(refusal)), ("value_kind", text.format("read"))) + def test_mixed_width_nan_keys_are_a_documented_refusal(self) -> None: + # The bytes the C# reference writes for a map holding float.NaN and double.NaN keys: it reads them as two keys. + row = "82 ca ffc00000 01 cb fff8000000000000 02" + with self.assertRaises(PayloadCodecFault) as caught: + MESSAGEPACK_PAYLOAD_CODEC.decode(bytes.fromhex(row)) + self.assertEqual((caught.exception.code, caught.exception.kind), ("duplicate_map_key", "")) + document = define_document_type("tests.nan", encode=lambda value: value) + self.assertEqual(self._refused(document.decode_payload, bytes.fromhex(row)).code, "duplicate_map_key") + readme = (Path(__file__).resolve().parents[1] / "README.md").read_text(encoding="utf-8") + section = readme.split("## Wire Parity", 1)[1].split("\n## ", 1)[0] + self.assertIn("duplicate_map_key", section) + self.assertIn(row, section) + def test_every_nan_key_is_one_key_both_ways(self) -> None: from cultcache_py.leaves import Float32 @@ -634,6 +647,11 @@ MIGRATION_RECORDS = { "k7": b'{"big": 1180591620717411303424}', } BIG_DIGITS = "1180591620717411303424" +SOURCE_MISSING = "convert: argument source does not exist (source_missing); there is nothing to convert." +DESTINATION_EXISTS = ( + "convert: argument destination already exists (destination_exists); convert writes only a new store, " + "and the source is unchanged." +) class ConvertTests(unittest.TestCase): @@ -754,10 +772,7 @@ class ConvertTests(unittest.TestCase): convert(store, destination, definitions) with self.assertRaises(CultCacheError) as again: convert(store, destination, definitions) - self.assertEqual( - str(caught.exception), - f"{destination} already exists; convert writes only a new store. {store.path} is unchanged.", - ) + self.assertEqual(str(caught.exception), DESTINATION_EXISTS) self.assertEqual(str(again.exception), str(caught.exception)) self.assertIsNone(caught.exception.__context__) self.assertEqual(pull_all.call_count, 0) @@ -889,9 +904,111 @@ class ConvertTests(unittest.TestCase): missing = SingleFileMessagePackBackingStore(self.directory / "missing.cc") with self.assertRaises(CultCacheError) as caught: convert(missing, destination, [define_document_type("tests.mig")]) - self.assertEqual(str(caught.exception), f"{missing.path} does not exist; there is nothing to convert.") + self.assertEqual(str(caught.exception), SOURCE_MISSING) self.assertFalse(destination.exists()) + def test_convert_refusals_name_no_path(self) -> None: + for label, make in self._stores(): + with self.subTest(store=label): + folder = self.directory / f"{CANARY}-dir" + folder.mkdir() + definitions = [define_document_type("tests.mig")] + store = type(make("x"))(folder / f"{CANARY}-src") + taken = type(store)(folder / f"{CANARY}-taken") + taken.push(CultCacheEnvelope.create(key="k", type="tests.mig", payload=b'{"n": 1}')) + store.push(CultCacheEnvelope.create(key="k", type="tests.mig", payload=b'{"n": 1}')) + missing = type(store)(folder / f"{CANARY}-missing") + for expected, call in ( + (SOURCE_MISSING, lambda: convert(missing, folder / f"{CANARY}-out", definitions)), + (DESTINATION_EXISTS, lambda: convert(store, taken.path, definitions)), + ): + with self.assertRaises(CultCacheError) as caught: + call() + refusal = caught.exception + self.assertEqual(str(refusal), expected) + for text in (str(refusal), repr(refusal), repr(refusal.args), repr(vars(refusal)), _chain_text(refusal)): + self.assertNotIn(CANARY, text) + self.assertNotIn(str(folder), text) + self.assertIsNone(refusal.__context__) + self.assertIsNone(refusal.__cause__) + + def _one_record(self, label, name): + store = self._filled(dict(self._stores())[label], name, {"k1": b'{"n": 1}'}) + return store, self.directory / f"{name}.out", [define_document_type("tests.mig")] + + def test_convert_interrupt_leaves_no_destination(self) -> None: + import cultcache_py.cache as cache_module + + real_open = open + + class FirstWriteInterrupts: + def __init__(self, handle) -> None: + self.handle = handle + + def __enter__(self): + self.handle.__enter__() + return self + + def __exit__(self, *exc): + return self.handle.__exit__(*exc) + + def write(self, data): + raise KeyboardInterrupt + + def __getattr__(self, name): + return getattr(self.handle, name) + + def created_then_interrupted(path, mode): + real_open(path, mode).close() + raise KeyboardInterrupt + + def created_then_first_write_interrupted(path, mode): + return FirstWriteInterrupts(real_open(path, mode)) + + for label, _ in self._stores(): + for case, seam in ( + ("raises-after-create", created_then_interrupted), + ("first-write-raises", created_then_first_write_interrupted), + ): + with self.subTest(store=label, case=case): + store, destination, definitions = self._one_record(label, f"int-{label}-{case}") + before = store.path.read_bytes() + with mock.patch.object(cache_module, "open", seam, create=True): + with self.assertRaises(KeyboardInterrupt): + convert(store, destination, definitions) + self.assertFalse(destination.exists()) + self.assertEqual(store.path.read_bytes(), before) + self.assertEqual(convert(store, destination, definitions), 1) + self.assertTrue(destination.exists()) + + def test_convert_never_removes_a_destination_it_did_not_create(self) -> None: + import cultcache_py.cache as cache_module + + for label, _ in self._stores(): + with self.subTest(store=label): + store, destination, definitions = self._one_record(label, f"theirs-{label}") + destination.write_bytes(b"theirs") + with mock.patch.object(cache_module, "open", side_effect=KeyboardInterrupt, create=True): + with self.assertRaises(CultCacheError) as caught: + convert(store, destination, definitions) + self.assertEqual(str(caught.exception), DESTINATION_EXISTS) + self.assertEqual(destination.read_bytes(), b"theirs") + # Another process creates the destination between the existence check and the create. + other = self.directory / f"raced-{label}.out" + real_exists = Path.exists + + def exists(path): + if path == other: + other.write_bytes(b"raced") + return False + return real_exists(path) + + with mock.patch.object(Path, "exists", exists): + with self.assertRaises(CultCacheError) as caught: + convert(store, other, definitions) + self.assertEqual(str(caught.exception), DESTINATION_EXISTS) + self.assertEqual(other.read_bytes(), b"raced") + def test_a_destination_under_a_missing_directory_is_created(self) -> None: store = self._filled( lambda name: SingleFileMessagePackBackingStore(self.directory / f"{name}.cc"), "nested", {"k1": b'{"n": 1}'}