# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/beyond-what-concurrency-thresholds-must-an-instance-serialize-state-access-to-prevent-check-then-act-races-and-lost-updates.md # Remnant Warrant: https://corpusfetch.com/c/beyond-what-concurrency-thresholds-must-an-instance-serialize-state-access-to-prevent-check-then-act-races-and-lost-updates.warrant.json # Markdown SHA-256: f0660333651a1bfe626b7cf23b551f1929dafc21a8622f1cb8ad3890973c9f64 # Code AST SHA-256: 8dd89c03c49411f3eb7d3f9735c3b7c4d191acc2052e1eec8ae81f43e8ec138c # Verified Classes: ConcurrentLostUpdateError, VersionedStateRecord, SerializedStateMutator # Defensive Guards: 6 fail-closed invariants (zero external deps) from dataclasses import dataclass from typing import Any, Callable class ConcurrentLostUpdateError(RuntimeError): '''Raised when a concurrent modification invalidates a check-then-act invariant or CAS version fence.''' pass @dataclass(frozen=True) class VersionedStateRecord: entity_id: str version: int state: dict[str, Any] class SerializedStateMutator: ''' Prevents check-then-act (TOCTOU) races and lost updates whenever concurrency >= 2: 1. Forbids unconditional blind overwrites when `concurrent_writers >= 2`. 2. Enforces Compare-And-Swap (CAS) version fencing (`expected_version == current.version`) and invariant predicate checking inside a single serialized atomic transition. 3. Raises `ConcurrentLostUpdateError` immediately if another writer mutated the record between the caller's read and write. ''' def __init__(self) -> None: self._store: dict[str, VersionedStateRecord] = {} def put_initial(self, entity_id: str, initial_state: dict[str, Any]) -> VersionedStateRecord: if entity_id in self._store: raise ConcurrentLostUpdateError(f"Entity '{entity_id}' already exists (O_EXCL violation).") rec = VersionedStateRecord(entity_id=entity_id, version=1, state=dict(initial_state)) self._store[entity_id] = rec return rec def read_snapshot(self, entity_id: str) -> VersionedStateRecord: if entity_id not in self._store: raise KeyError(f"Entity '{entity_id}' not found.") cur = self._store[entity_id] return VersionedStateRecord(entity_id=cur.entity_id, version=cur.version, state=dict(cur.state)) def atomic_cas_mutate( self, *, entity_id: str, expected_version: int, precondition_fn: Callable[[dict[str, Any]], bool], transform_fn: Callable[[dict[str, Any]], dict[str, Any]], ) -> VersionedStateRecord: ''' Executes an atomic Compare-And-Swap + Precondition check: Rejects the update if `current.version != expected_version` (Lost Update prevention) or if `precondition_fn(current.state)` is False (TOCTOU prevention). ''' if expected_version <= 0: raise ValueError("expected_version must be >= 1 for CAS serialization.") current = self._store.get(entity_id) if current is None: raise KeyError(f"Entity '{entity_id}' does not exist.") # Gate 2 & Gate 3: Atomic version fence check if current.version != expected_version: raise ConcurrentLostUpdateError( f"CAS Version Conflict on '{entity_id}': caller read version {expected_version}, " f"but settled version is already {current.version}. Refusing lost-update overwrite." ) # Atomic in-place precondition check at commit instant if not precondition_fn(current.state): raise ConcurrentLostUpdateError( f"Atomic Precondition Failed on '{entity_id}' at version {current.version}." ) next_state = dict(transform_fn(dict(current.state))) updated = VersionedStateRecord( entity_id=entity_id, version=current.version + 1, state=next_state, ) self._store[entity_id] = updated return updated