From 3760c02eab9ef38ee716f39a706417e0309af386 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 01:17:30 +0100 Subject: [PATCH] cultcache-py: an injectable cache clock; stores restamp without reading a clock Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-py/CHANGELOG.md | 2 + packages/cultcache-py/README.md | 1 + .../src/cultcache_py/backing_store.py | 4 +- .../cultcache-py/src/cultcache_py/cache.py | 30 +++++++- .../cultcache-py/src/cultcache_py/stores.py | 28 +++---- packages/cultcache-py/tests/test_clock.py | 73 +++++++++++++++++++ packages/cultcache-py/tests/test_update.py | 15 ++-- 7 files changed, 122 insertions(+), 31 deletions(-) create mode 100644 packages/cultcache-py/tests/test_clock.py diff --git a/packages/cultcache-py/CHANGELOG.md b/packages/cultcache-py/CHANGELOG.md index 3319863f..70b706e0 100644 --- a/packages/cultcache-py/CHANGELOG.md +++ b/packages/cultcache-py/CHANGELOG.md @@ -13,12 +13,14 @@ ### Added +- `CultCache(clock=...)`, `CultCacheBuilder.with_clock(clock)` and a settable `cache.clock`: the one clock (`Callable[[], datetime]`, timezone-aware; the wall clock by default) that stamps every fresh write, as the C# `Clock` and the Rust `set_clock` do. `CultCacheEnvelope.create` takes an optional `stored_at` and keeps the wall clock for direct store callers. A pinned clock alone is not byte-identity where a writer mints random values of its own (the C# writer's unset element ids); this writer mints none. - `CultCacheError` is exported from the package root (`from cultcache_py import CultCacheError`); it was reachable only from the private `cultcache_py.cache` module. - `CultCache.update` and `update_global` return `UpdateResult(outcome, document)`; `UpdateOutcome` is `UPDATED`, `DECLINED` or `LOST_RACE`. The single-file store gains `read(key)` (the record and its content version, the SHA-256 C# computes) and `commit_if(envelope, expected)`, the version is the SHA-256 of the record re-encoded as `[key, schemaId, storedAt, payload]` with minimal MessagePack encodings, which is the SHA-256 of the record's stored bytes exactly when the writer encoded it minimally (every writer in this library does; a record another writer encoded with a wider-than-needed length or integer has the version of its minimal form, not of its bytes). Both looked up by the cache and not `BackingStore` protocol members (variants:cut_spec:cut-update-with-retry-py). - `read_payload_tree(type_name, payload, decoder=None, depth_faults=(msgpack.exceptions.StackError,))`: the exported owner of the one-value, depth-first payload read that `decode_payload` uses, for payloads read outside a definition (`cultnet-py`'s witness bundle decode needs it, so `cultnet-py` now requires `cultcache-py>=0.4.0`). The manifest version is 0.4.0, the minor these Unreleased breaking changes imply, set in this change so the workspace install resolves the new bound; the `## Unreleased` heading becomes `## [0.4.0]` when it is tagged. ### Changed +- A store's restamp of a replacing write (`stored_at_over`) reads no clock: the staged stamp when both parse and it is strictly later, else the replaced stamp plus one microsecond (variants cultlib-gaps ruling `sibling-restamp-staged-derived`, as Rust and TypeScript do). A replaced stamp that does not parse leaves the staged stamp as written; before, such a write was stamped at now. `mint_stored_at` is removed. - A write that replaces a record is stored at a later `stored_at` than the record it replaces, in the single-file store, the JSONL store and a store-less cache, with no exception for identical content (`variants:ruling:py-rs-update-follow-csharp-restamp`); the cache holds the stamp the store wrote. A stored_at is read only in the shape the runtimes write (an RFC 3339 date-time with T, a fraction of 1 to 9 digits, Z or a numeric offset), the same on every Python; any other text, or an instant outside `datetime`'s range, is not a stamp and a write over it is stamped at now. A write over a record stamped at the last instant `datetime` can hold (9999-12-31T23:59:59.999999Z) is refused with `ValueError` and writes nothing. - `store_write_lock` looks for a link at the store path again once the lock is held, so a link put at the path while a writer waited on the lock is refused with `StoreLinkedError` and the lock released, instead of being replaced. `JsonLinesBackingStore` takes no cross-process lock (only its thread lock, under which it already refuses a link), so it has no lock wait to re-check across. Pinned by a test that puts the link while a foreign process holds the lock. - `CultCache.is_writable` does not look at store paths: a link at a store path is not predicted, and the write refuses it with `StoreLinkedError`. Pinned by a test through a cache attached to a linked store. diff --git a/packages/cultcache-py/README.md b/packages/cultcache-py/README.md index dbf02a9b..65b40a49 100644 --- a/packages/cultcache-py/README.md +++ b/packages/cultcache-py/README.md @@ -76,6 +76,7 @@ store. - `leaves` (typed slot leaves) - `define_document_registry(...)` - `CultCache.builder()` +- `CultCache(clock=...)`, `CultCacheBuilder.with_clock(clock)` and the settable `cache.clock`: the one clock (a `() -> datetime`, timezone-aware; the wall clock by default) that stamps fresh writes. Pin it to write reproducible stores; a replacing write is still stamped later than the record it replaces. A pinned clock alone is not byte-identity where a writer mints random values of its own (the C# writer's unset element ids); this writer mints none. - `register_document_type(...)` - `register_registry(...)` - `register_name_lookup(...)` diff --git a/packages/cultcache-py/src/cultcache_py/backing_store.py b/packages/cultcache-py/src/cultcache_py/backing_store.py index c20ac661..5f70cb50 100644 --- a/packages/cultcache-py/src/cultcache_py/backing_store.py +++ b/packages/cultcache-py/src/cultcache_py/backing_store.py @@ -46,12 +46,14 @@ class CultCacheEnvelope: payload: bytes, schema_id: str | None = None, catalog_entry: CultCacheSchemaCatalogEntry | None = None, + stored_at: str | None = None, ) -> "CultCacheEnvelope": + """A cache stamps through its own clock and passes `stored_at`; a direct store caller leaves it out and gets the wall clock.""" return cls( key=key, type=type, payload=payload, - stored_at=datetime.now(timezone.utc).isoformat(), + stored_at=datetime.now(timezone.utc).isoformat() if stored_at is None else stored_at, schema_id=schema_id, catalog_entry=catalog_entry, ) diff --git a/packages/cultcache-py/src/cultcache_py/cache.py b/packages/cultcache-py/src/cultcache_py/cache.py index dbb09997..bdf0480a 100644 --- a/packages/cultcache-py/src/cultcache_py/cache.py +++ b/packages/cultcache-py/src/cultcache_py/cache.py @@ -7,6 +7,7 @@ import os import threading from decimal import Decimal from dataclasses import dataclass, field, replace +from datetime import datetime, timezone from pathlib import Path from typing import Any, Callable, Generic, Iterable, TypeVar @@ -188,10 +189,18 @@ _Indexes = dict[tuple[str, str, str], str] _LookupKeysByType = dict[str, dict[str, _LookupKeys]] +def _wall_clock() -> datetime: + return datetime.now(timezone.utc) + + class CultCacheBuilder: def __init__(self) -> None: self._cache = CultCache() + def with_clock(self, clock: Callable[[], datetime]) -> "CultCacheBuilder": + self._cache.clock = clock + return self + def register_document_type(self, document: DocumentDefinition[Any]) -> "CultCacheBuilder": self._cache.register_document_type(document) return self @@ -227,7 +236,12 @@ class CultCache: def builder(cls) -> CultCacheBuilder: return CultCacheBuilder() - def __init__(self) -> None: + def __init__(self, clock: Callable[[], datetime] | None = None) -> None: + """`clock` is the one source of "now" for every stamp this cache mints: a timezone-aware datetime, the wall clock by default. + Pin it to write reproducible stores. A replacing write is still stamped later than the record it replaces, derived from the + two stamps and no clock. A pinned clock alone is not byte-identity where a writer mints random values of its own (the C# + writer's unset element ids); this writer mints none.""" + self._clock: Callable[[], datetime] = clock or _wall_clock self._state = _State() # Mutations hold this lock and refuse to start on the thread already inside one (see _mutating). # It is reentrant so a mutation's extractors, decoders and updaters may still read the cache. @@ -237,6 +251,17 @@ class CultCache: self._lock = threading.RLock() self._mutating_thread: int | None = None + @property + def clock(self) -> Callable[[], datetime]: + return self._clock + + @clock.setter + def clock(self, clock: Callable[[], datetime]) -> None: + self._clock = clock + + def _now(self) -> str: + return self._clock().astimezone(timezone.utc).isoformat() + @_mutating def register_document_type(self, document: DocumentDefinition[Any]) -> None: self._register_document_type(document) @@ -530,6 +555,7 @@ class CultCache: payload=document.encode_payload(value), schema_id=catalog_entry.schema_id, catalog_entry=catalog_entry, + stored_at=self._now(), ) return self._write(document, [(envelope, value)], batch=False, expected=expected) @@ -718,7 +744,7 @@ class CultCache: raise CultCacheError(f"Global document {document.type} must use key {GLOBAL_KEY}") self._refuse_unread([key]) entry = document.catalog_entry() - probe = CultCacheEnvelope.create(key=key, type=document.type, payload=b"", schema_id=entry.schema_id, catalog_entry=entry) + probe = CultCacheEnvelope.create(key=key, type=document.type, payload=b"", schema_id=entry.schema_id, catalog_entry=entry, stored_at=self._now()) return self._refuse_retype(document, [probe]) def _refuse_unread(self, keys: list[str]) -> None: diff --git a/packages/cultcache-py/src/cultcache_py/stores.py b/packages/cultcache-py/src/cultcache_py/stores.py index 387a5145..d88bcc77 100644 --- a/packages/cultcache-py/src/cultcache_py/stores.py +++ b/packages/cultcache-py/src/cultcache_py/stores.py @@ -814,27 +814,19 @@ def parse_stored_at(text: Any) -> datetime | None: return None -def mint_stored_at(previous: str | None, now: datetime) -> str: - """A stored_at later than `previous` (C# MintStoredAt): `now`, or the microsecond after `previous` when `now` is not later. - A previous that does not parse leaves `now`. Raises ValueError, nothing minted, when `previous` is the last instant a stamp - can name, so a write over it is refused and writes nothing.""" - now = now.astimezone(timezone.utc) - last = parse_stored_at(previous) - if last is not None and now <= last: - try: - now = last + timedelta(microseconds=1) - except OverflowError: - raise ValueError(f"stored_at {previous!r} is the last instant a stamp can name; a write over it cannot be stored later") from None - return now.isoformat(timespec="microseconds") - - def stored_at_over(staged: str, replaced: str) -> str: - """The stored_at a record replacing `replaced` is written with (C# StoredAtOver): `staged` when both parse and it is strictly - later, else one minted over `replaced`. No content is compared: every replacing write is stamped later.""" + """The stored_at a record replacing `replaced` is written with (C# StoredAtOver), derived from the two stamps and no clock + (variants:ruling:sibling-restamp-staged-derived): `staged` when both parse and it is strictly later, else the microsecond after + `replaced`. A `replaced` that does not parse leaves nothing to be later than, so `staged` stands as written. Raises ValueError, + nothing minted, when `replaced` is the last instant a stamp can name, so a write over it is refused and writes nothing. No + content is compared: every replacing write is stamped later.""" later, earlier = parse_stored_at(staged), parse_stored_at(replaced) - if later is not None and earlier is not None and later > earlier: + if earlier is None or (later is not None and later > earlier): return staged - return mint_stored_at(replaced, datetime.now(timezone.utc)) + try: + return (earlier + timedelta(microseconds=1)).isoformat(timespec="microseconds") + except OverflowError: + raise ValueError(f"stored_at {replaced!r} is the last instant a stamp can name; a write over it cannot be stored later") from None def record_version(envelope: CultCacheEnvelope) -> str: diff --git a/packages/cultcache-py/tests/test_clock.py b/packages/cultcache-py/tests/test_clock.py new file mode 100644 index 00000000..a3d29037 --- /dev/null +++ b/packages/cultcache-py/tests/test_clock.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import shutil +import tempfile +import unittest +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path + +from cultcache_py import CultCache, SingleFileMessagePackBackingStore, define_document_type +from cultcache_py.stores import stored_at_over + + +@dataclass +class Settings: + theme: str + retries: int + + +settings_doc = define_document_type("settings", encode=asdict, decode=lambda raw: Settings(**raw)) +PINNED = datetime(2026, 3, 4, 5, 6, 7, tzinfo=timezone.utc) + + +class CacheClockTests(unittest.TestCase): + def setUp(self) -> None: + self.dir = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.dir, ignore_errors=True) + + def pinned_cache(self, name: str, clock=lambda: PINNED, *, store: bool = True) -> CultCache: + builder = CultCache.builder().register_document_type(settings_doc).with_clock(clock) + if store: + builder.add_generic_store(SingleFileMessagePackBackingStore(self.dir / name)) + cache = builder.build() + cache.pull_all_backing_stores() + return cache + + def test_a_cache_with_no_clock_stamps_near_now(self) -> None: + cache = CultCache.builder().register_document_type(settings_doc).build() + cache.put(settings_doc, "app", Settings("green", 1)) + stamped = datetime.fromisoformat(cache.get_envelope(settings_doc, "app").stored_at) + self.assertLess(abs((datetime.now(timezone.utc) - stamped).total_seconds()), 5) + + def test_two_replays_with_a_pinned_clock_write_identical_bytes(self) -> None: + for name in ("a.cc", "b.cc"): + cache = self.pinned_cache(name) + cache.put(settings_doc, "app", Settings("green", 1)) + cache.put(settings_doc, "app", Settings("blue", 2)) + cache.put(settings_doc, "other", Settings("green", 1)) + self.assertEqual((self.dir / "a.cc").read_bytes(), (self.dir / "b.cc").read_bytes()) + + def test_a_pinned_clock_still_stamps_a_replacing_write_later(self) -> None: + for store in (True, False): + with self.subTest(store=store): + cache = self.pinned_cache("later.cc", store=store) + cache.put(settings_doc, "app", Settings("green", 1)) + self.assertEqual(cache.get_envelope(settings_doc, "app").stored_at, "2026-03-04T05:06:07+00:00") + cache.put(settings_doc, "app", Settings("blue", 2)) + self.assertEqual(cache.get_envelope(settings_doc, "app").stored_at, "2026-03-04T05:06:07.000001+00:00") + + def test_the_clock_property_is_settable_and_every_write_reads_it(self) -> None: + cache = self.pinned_cache("set.cc") + cache.clock = lambda: datetime(2030, 1, 1, tzinfo=timezone.utc) + cache.put(settings_doc, "app", Settings("green", 1)) + self.assertEqual(cache.get_envelope(settings_doc, "app").stored_at, "2030-01-01T00:00:00+00:00") + + def test_a_restamp_reads_no_clock(self) -> None: + # stored_at_over takes no clock: the staged stamp when later, else the replaced stamp plus a microsecond. + self.assertEqual(stored_at_over("2000-01-01T00:00:00Z", "2001-01-01T00:00:00Z"), "2001-01-01T00:00:00.000001+00:00") + self.assertEqual(stored_at_over("2100-01-01T00:00:00Z", "2099-01-01T00:00:00Z"), "2100-01-01T00:00:00Z") + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/cultcache-py/tests/test_update.py b/packages/cultcache-py/tests/test_update.py index 107adf3b..2c7c9aa2 100644 --- a/packages/cultcache-py/tests/test_update.py +++ b/packages/cultcache-py/tests/test_update.py @@ -26,7 +26,7 @@ from cultcache_py import ( leaves as t, ) from cultcache_py.cache import GLOBAL_KEY, CultCacheError -from cultcache_py.stores import parse_stored_at, mint_stored_at, record_version, stored_at_over +from cultcache_py.stores import parse_stored_at, record_version, stored_at_over @dataclass @@ -671,11 +671,8 @@ class StoreRestampTests(Fixture): for text in ("9999-12-31T23:30:00-05:00", "0001-01-01T00:00:00+05:00"): with self.subTest(text=text): self.assertIsNone(parse_stored_at(text)) - now = datetime(2030, 1, 1, tzinfo=timezone.utc) - self.assertEqual(mint_stored_at("9999-12-31T23:30:00-05:00", now), "2030-01-01T00:00:00.000000+00:00") + self.assertEqual(stored_at_over("2000-01-01T00:00:00Z", "9999-12-31T23:30:00-05:00"), "2000-01-01T00:00:00Z") edge = "9999-12-31T23:59:59.9999999Z" - with self.assertRaisesRegex(ValueError, "last instant"): - mint_stored_at(edge, now) with self.assertRaisesRegex(ValueError, "last instant"): stored_at_over("2000-01-01T00:00:00Z", edge) # A write over a record stamped at the edge is refused by the store and writes nothing, from push, commit_if and update. @@ -703,11 +700,9 @@ class StoreRestampTests(Fixture): self.assertEqual(parse_stored_at(text).tzinfo, timezone.utc) self.assertIsNone(parse_stored_at("garbage")) self.assertIsNone(parse_stored_at(None)) - now = datetime(2030, 1, 1, tzinfo=timezone.utc) - self.assertEqual(mint_stored_at("garbage", now), "2030-01-01T00:00:00.000000+00:00") - self.assertEqual(stored_at_over("2000-01-01T00:00:00Z", "2000-01-01T00:00:00Z")[:4], str(datetime.now(timezone.utc).year)) # no later: minted at now - self.assertEqual(mint_stored_at("2030-01-01T00:00:00Z", now), "2030-01-01T00:00:00.000001+00:00") # equal is not later - self.assertEqual(mint_stored_at("2099-01-01T00:00:00.1234567Z", now), "2099-01-01T00:00:00.123457+00:00") + self.assertEqual(stored_at_over("2030-01-01T00:00:00Z", "garbage"), "2030-01-01T00:00:00Z") # nothing to be later than + self.assertEqual(stored_at_over("garbage", "garbage"), "garbage") + self.assertEqual(stored_at_over("2000-01-01T00:00:00Z", "2000-01-01T00:00:00Z"), "2000-01-01T00:00:00.000001+00:00") # equal is not later self.assertEqual(stored_at_over("2000-01-01T00:00:00Z", "2099-01-01T00:00:00.1234567Z"), "2099-01-01T00:00:00.123457+00:00") for reported in (True, 1, "garbage"):