Serialize the Python cache behind one reentrant lock per instance

The Python cache took no lock, so "refused write changes neither store nor
cache" and the one-home rule held only for one caller at a time. A put paused
between its store push and its apply let a concurrent attach route the type to
a new home (the record stayed in the old store), and let a second global put
reach disk first so cache and disk disagreed.

CultCache now holds a threading.RLock around attach, pull, registration, every
write and delete (globals and update included), name/index resolution and
snapshots, matching the C# per-cache gate and the TS serial queue. Single-dict
reads stay unlocked. No public API change.

Tests: test_concurrent_put_and_attach_cannot_land_record_in_non_home_store and
test_concurrent_global_puts_cannot_both_reach_disk force the interleaving with
a store that pauses inside push; both fail on 4dc7f3a and pass here. The
contract's Python cells drop the one-caller caveat.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-14 12:03:45 +02:00
commit 15c6a5d513
3 changed files with 130 additions and 3 deletions

View file

@ -1,15 +1,30 @@
from __future__ import annotations
import functools
import threading
from dataclasses import dataclass, field
from typing import Any, Generic, TypeVar
from typing import Any, Callable, Generic, TypeVar
from .backing_store import BackingStore, CultCacheEnvelope
from .documents import DocumentDefinition, extract_value
T = TypeVar("T")
F = TypeVar("F", bound=Callable[..., Any])
GLOBAL_KEY = "__global__"
def _locked(method: F) -> F:
"""Runs the method holding the cache's lock, so its validation, store I/O and apply cannot
interleave with another thread's attach, pull, registration, write or delete."""
@functools.wraps(method)
def wrapper(self: "CultCache", *args: Any, **kwargs: Any) -> Any:
with self._lock:
return method(self, *args, **kwargs)
return wrapper # type: ignore[return-value]
class CultCacheError(RuntimeError):
pass
@ -83,7 +98,13 @@ class CultCache:
def __init__(self) -> None:
self._state = _State()
# Reentrant: extractors, decoders and updaters may read or write this cache from inside a
# held call. Single-structure reads (get, get_all, get_envelope, key lookups) stay unlocked:
# each reads one dict under the GIL, and every write installs a record's value, envelope and
# lookups before releasing the lock, so they never observe a store/cache split.
self._lock = threading.RLock()
@_locked
def register_document_type(self, document: DocumentDefinition[Any]) -> None:
if document.type in self._state.documents:
raise CultCacheError(f"Document type already registered: {document.type}")
@ -100,16 +121,19 @@ class CultCache:
self._state.documents[document.type] = document
self._state.documents_by_schema_name[schema_name] = document
@_locked
def register_registry(self, documents: list[DocumentDefinition[Any]] | tuple[DocumentDefinition[Any], ...]) -> None:
for document in documents:
self.register_document_type(document)
@_locked
def register_name_lookup(self, document: DocumentDefinition[Any], extractor: str | Any) -> None:
self._assert_registered(document)
name_extractors = dict(self._state.name_extractors)
name_extractors[document.type] = extractor
self._install_lookups(name_extractors, self._state.index_extractors)
@_locked
def register_index(self, document: DocumentDefinition[Any], index: str, extractor: str | Any) -> None:
self._assert_registered(document)
index_extractors = {type: dict(indexes) for type, indexes in self._state.index_extractors.items()}
@ -130,6 +154,7 @@ class CultCache:
self._state.lookup_keys,
) = (name_extractors, index_extractors, names, indexes, lookup_keys)
@_locked
def add_backing_store(self, store: BackingStore, types: list[str] | tuple[str, ...] | set[str]) -> None:
"""Makes the store home to the given types, or the generic store when there are none.
@ -149,6 +174,7 @@ class CultCache:
self._refuse_home_moves(routes, self._state.generic_store)
self._state.stores_by_type = routes
@_locked
def add_generic_store(self, store: BackingStore) -> None:
"""Makes the store home to every type no other store claims. A cache has at most one."""
if self._state.generic_store is not None:
@ -178,6 +204,7 @@ class CultCache:
return "the generic store"
return "the store routed to " + ", ".join(sorted(type for type, routed in routes.items() if routed is store))
@_locked
def pull_all_backing_stores(self) -> None:
"""Builds the complete next state (values, envelopes, name and index lookups) in local
structures, running every check and every user extractor; the cache's state is replaced
@ -267,6 +294,9 @@ class CultCache:
self._assert_registered(document)
return self._state.names.get((document.type, name))
# Name and index resolution read the lookup and then the values, two structures a pull swaps and a
# write updates in sequence, so they hold the lock to resolve a key and its value from one state.
@_locked
def get_by_name(self, document: DocumentDefinition[T], name: str) -> T | None:
key = self.get_key_by_name(document, name)
return None if key is None else self.get(document, key)
@ -275,10 +305,12 @@ class CultCache:
self._assert_registered(document)
return self._state.indexes.get((document.type, index, value))
@_locked
def get_by_index(self, document: DocumentDefinition[T], index: str, value: str) -> T | None:
key = self.get_key_by_index(document, index, value)
return None if key is None else self.get(document, key)
@_locked
def put(self, document: DocumentDefinition[T], key: str, value: T) -> None:
self._assert_registered(document)
if document.global_document and key != GLOBAL_KEY:
@ -293,6 +325,7 @@ class CultCache:
)
self._write(document, [(envelope, value)], batch=False)
@_locked
def put_envelope(self, document: DocumentDefinition[T], envelope: CultCacheEnvelope) -> T:
self._assert_registered(document)
self._check_envelope(document, envelope)
@ -300,6 +333,7 @@ class CultCache:
self._write(document, [(envelope, value)], batch=False)
return value
@_locked
def put_envelopes(self, document: DocumentDefinition[T], envelopes: list[CultCacheEnvelope]) -> list[T]:
self._assert_registered(document)
values: list[T] = []
@ -351,20 +385,24 @@ class CultCache:
for index, index_value in keys.indexes.items():
self._state.indexes[(type, index, index_value)] = envelope.key
@_locked
def put_global(self, document: DocumentDefinition[T], value: T) -> None:
self._assert_global(document)
self.put(document, GLOBAL_KEY, value)
@_locked
def update(self, document: DocumentDefinition[T], key: str, updater: Any) -> T:
current = self.get_required(document, key)
updated = updater(current)
self.put(document, key, updated)
return updated
@_locked
def update_global(self, document: DocumentDefinition[T], updater: Any) -> T:
self._assert_global(document)
return self.update(document, GLOBAL_KEY, updater)
@_locked
def delete(self, document: DocumentDefinition[Any], key: str) -> None:
self._assert_registered(document)
store = self._store_for_type(document.type)
@ -378,16 +416,20 @@ class CultCache:
if not held:
by_type.pop(document.type, None)
@_locked
def delete_global(self, document: DocumentDefinition[Any]) -> None:
self._assert_global(document)
self.delete(document, GLOBAL_KEY)
# Snapshots iterate dicts a concurrent write would resize mid-iteration, so they hold the lock.
@_locked
def snapshot(self) -> dict[str, dict[str, Any]]:
out: dict[str, dict[str, Any]] = {}
for type, values in self._state.values.items():
out[type] = dict(values)
return out
@_locked
def snapshot_envelopes(self) -> list[CultCacheEnvelope]:
return [
envelope

View file

@ -1,6 +1,7 @@
from __future__ import annotations
import tempfile
import threading
import unittest
from dataclasses import asdict, dataclass, replace
from pathlib import Path
@ -543,6 +544,90 @@ class CultCacheTests(unittest.TestCase):
self.assertEqual(cache.snapshot_envelopes(), cache_before)
self.assertEqual(cache.get_required_global(settings), {"theme": "base"})
@staticmethod
def _pausing_store(path: Path, barrier: threading.Barrier, resume: threading.Event):
"""A store whose first push writes, meets the other thread at the barrier, then waits until that
thread's call has returned (or a timeout: a locked cache makes the other thread wait on us)."""
class PausingStore(SingleFileMessagePackBackingStore):
pushes = 0
paused = False
other_reached_store_while_paused = False
def push(self, envelope):
self.other_reached_store_while_paused |= self.paused
self.pushes += 1
super().push(envelope)
if self.pushes == 1:
self.paused = True
barrier.wait(timeout=5)
resume.wait(timeout=0.5)
self.paused = False
return PausingStore(path)
@staticmethod
def _run_racing(first, second, resume: threading.Event) -> list[BaseException]:
errors: list[BaseException] = []
def run(action, signal):
try:
action()
except BaseException as error: # noqa: BLE001 - reported to the test
errors.append(error)
finally:
if signal:
resume.set()
threads = [threading.Thread(target=run, args=(first, False)), threading.Thread(target=run, args=(second, True))]
for thread in threads:
thread.start()
for thread in threads:
thread.join(timeout=10)
return errors
def test_concurrent_put_and_attach_cannot_land_record_in_non_home_store(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
settings = define_database_entry_type("settings", [("theme", 0)])
generic_path, settings_path = Path(tmp) / "generic.cc", Path(tmp) / "settings.cc"
barrier, resume = threading.Barrier(2), threading.Event()
generic = self._pausing_store(generic_path, barrier, resume)
cache = CultCache.builder().register_document_type(settings).add_generic_store(generic).build()
def attach() -> None:
barrier.wait(timeout=5)
cache.add_backing_store(SingleFileMessagePackBackingStore(settings_path), ["settings"])
errors = self._run_racing(lambda: cache.put(settings, "app", {"theme": "t"}), attach, resume)
# Either the attach was refused (the record is held, so its home cannot move) or it won;
# in every case each held record must be in the store that is its home.
home = SingleFileMessagePackBackingStore(generic_path if errors else settings_path)
self.assertEqual([(e.key, e.type) for e in home.pull_all()], [("app", "settings")])
self.assertTrue(all(isinstance(error, CultCacheError) for error in errors), errors)
def test_concurrent_global_puts_cannot_both_reach_disk(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
settings = define_document_type("settings", global_document=True)
path = Path(tmp) / "generic.cc"
barrier, resume = threading.Barrier(2), threading.Event()
store = self._pausing_store(path, barrier, resume)
cache = CultCache.builder().register_document_type(settings).add_generic_store(store).build()
def second() -> None:
barrier.wait(timeout=5)
cache.put_global(settings, {"theme": "second"})
errors = self._run_racing(lambda: cache.put_global(settings, {"theme": "first"}), second, resume)
self.assertEqual(errors, [])
# While the first write was between its store push and its apply, the second never reached disk.
self.assertFalse(store.other_reached_store_while_paused)
on_disk = SingleFileMessagePackBackingStore(path).pull_all()
self.assertEqual(len(on_disk), 1)
self.assertEqual(on_disk[0].payload, cache.get_required_envelope(settings, CultCache.GLOBAL_KEY).payload)
self.assertEqual(cache.get_required_global(settings), {"theme": "second"})
def test_put_envelope_refuses_a_global_under_another_key(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
settings = define_document_type("settings", global_document=True)

View file

@ -239,9 +239,9 @@ no serialization; a CultMath encoding, if added, uses this shape.
|---|---|---|---|---|
| One home store, no mirrors | implemented | implemented (exact type ids; `add_backing_store` returns `Err` on a second generic store or a claimed type; an empty type list is the generic store) | implemented (exact type ids; `addBackingStore` throws on a second generic store or a claimed type; no types is the generic store) | implemented (exact type ids; `add_backing_store`/`add_generic_store` raise on a claimed type or a second generic store; an empty type list is the generic store) |
| Zero stores is in memory | implemented | implemented | implemented | implemented |
| Home cannot move after admission | implemented | implemented (`add_backing_store` returns `Err` and attaches nothing) | implemented (`addBackingStore` rejects and attaches nothing; it runs in the cache's serial queue, so it cannot move a write that is in flight) | implemented (`add_backing_store`/`add_generic_store` raise and attach nothing) |
| Home cannot move after admission | implemented | implemented (`add_backing_store` returns `Err` and attaches nothing) | implemented (`addBackingStore` rejects and attaches nothing; it runs in the cache's serial queue, so it cannot move a write that is in flight) | implemented (`add_backing_store`/`add_generic_store` raise and attach nothing; they hold the cache's lock, so they cannot move a write that is in flight) |
| Refused at load when not home | implemented | implemented (`pull_all_backing_stores` returns `Err` naming key and both stores; `load_soa` returns `Err` for a type with no home once a store is attached; both admit nothing and leave the prior view intact) | implemented (`pullAllBackingStores` throws naming key and both stores; admits nothing) | implemented (`pull_all_backing_stores` raises naming key and both stores; admits nothing) |
| Refused write changes neither store nor cache | implemented | implemented (`put`, `put_envelope`, `put_raw_envelope`, `put_prepared_batch` and `delete` validate before the store call and apply infallibly after it; there are no user accessors) | implemented (home, `__global__` key and name and index accessors run before the store call; overwrite and delete use lookup values stored at admission; attach, pull, registration, writes and deletes run through one per-cache promise queue) | implemented for one caller at a time (same validation order and stored lookup keys as TypeScript; the cache takes no lock, so concurrent threads are not serialized) |
| Refused write changes neither store nor cache | implemented | implemented (`put`, `put_envelope`, `put_raw_envelope`, `put_prepared_batch` and `delete` validate before the store call and apply infallibly after it; there are no user accessors) | implemented (home, `__global__` key and name and index accessors run before the store call; overwrite and delete use lookup values stored at admission; attach, pull, registration, writes and deletes run through one per-cache promise queue) | implemented (same validation order and stored lookup keys as TypeScript; attach, pull, registration, writes, deletes, name and index resolution and snapshots hold one reentrant lock per cache) |
| Attach hydrates; loading never writes | implemented | attach does not read (call `pull_all_backing_stores`); pull loads without writing | attach does not read (call `pullAllBackingStores`); pull loads without writing | attach does not read (call `pull_all_backing_stores`); pull loads without writing |
| Runtime type decides schema | implemented | n/a (explicit type ids) | n/a | n/a |
| Assignable lookups and watches | implemented | exact type ids | exact type ids | exact type ids |