# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-stale-fact-resurrection-when-an-agent-s-forget-and-write-memory-tools-race-across-a-checkpoint-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-stale-fact-resurrection-when-an-agent-s-forget-and-write-memory-tools-race-across-a-checkpoint-boundary.warrant.json
# Markdown SHA-256:   5e48601cd7657c35b6729f9461179bdadab476680e9608b07ea63dd110689324
# Code AST SHA-256:   e235a754d2dd5e7c9e2941264e92dbf36a214680acbd0f7cdd6d88d66d2ef5ab
# Verified Classes:   MemoryContradictionError, Record, MemoryStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class MemoryContradictionError(RuntimeError):
    """Raised when a resumed memory state cannot be reconciled with the mutation journal."""
    pass

@dataclass
class Record:
    key: str
    value: Optional[str]   # None => tombstone
    clock: int
    source_turn: int

@dataclass
class MemoryStore:
    # per-key total order of records; last element is authoritative
    log: dict[str, list[Record]] = field(default_factory=dict)
    high_water: dict[str, int] = field(default_factory=dict)

    def _append(self, rec: Record) -> None:
        chain = self.log.setdefault(rec.key, [])
        if chain and rec.clock <= chain[-1].clock:
            raise MemoryContradictionError(
                f"non-monotonic clock for {rec.key!r}: {rec.clock} <= {chain[-1].clock}"
            )
        chain.append(rec)
        self.high_water[rec.key] = rec.clock

    def write(self, key: str, value: str, clock: int, source_turn: int) -> None:
        self._append(Record(key, value, clock, source_turn))

    def forget(self, key: str, clock: int, source_turn: int) -> None:
        self._append(Record(key, None, clock, source_turn))  # first-class tombstone

    def read(self, key: str) -> Optional[Record]:
        chain = self.log.get(key, [])
        if not chain:
            return None
        return chain[-1]  # max-clock record wins; tombstone => absent

def resume(store: MemoryStore, snapshot_high_water: dict[str, int],
           journal: list[Record]) -> MemoryStore:
    """Replay journal onto a snapshot, gating per-key on the snapshot's high-water mark."""
    for rec in journal:
        hw = snapshot_high_water.get(rec.key, -1)
        if rec.clock <= hw:
            continue  # already reflected in snapshot; skip, do not resurrect
        if rec.key in store.log and store.log[rec.key][-1].clock >= rec.clock:
            raise MemoryContradictionError(
                f"journal replay would violate order for {rec.key!r}"
            )
        store._append(rec)
    # invariant check: every key's authoritative record must be the max-clock one
    for key, chain in store.log.items():
        if chain[-1].clock != max(r.clock for r in chain):
            raise MemoryContradictionError(f"tombstone/value order violated for {key!r}")
    return store

def assert_trustworthy(store: MemoryStore, key: str, agent_believed_tombstone_clock: int) -> str:
    rec = store.read(key)
    if rec is None:
        raise MemoryContradictionError(f"{key!r} absent; refusing to assert")
    if rec.value is not None and rec.clock < agent_believed_tombstone_clock:
        raise MemoryContradictionError(
            f"stale-fact resurrection for {key!r}: value clock {rec.clock} "
            f"predates believed tombstone clock {agent_believed_tombstone_clock}"
        )
    return rec.value
