# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-serve-a-memory-read-whose-provenance-chain-crosses-a-deletion-attestation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-serve-a-memory-read-whose-provenance-chain-crosses-a-deletion-attestation-boundary.warrant.json
# Markdown SHA-256:   a996c87935aea4043c2e90dc747e6239c5a57f9589e55b331133631c4baa4a8d
# Code AST SHA-256:   a164f48ccee2df79fc84aa58cb70bb3f4a1bc4cff20c0811ec5cbff65ac98aed
# Verified Classes:   StaleDerivedMemory, MemoryRecord, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StaleDerivedMemory(RuntimeError):
    """Raised when a memory read's provenance closure crosses a post-reconciliation tombstone."""

    def __init__(self, key: str, ancestor: str, tombstone_epoch: int, reconciled_epoch: int):
        self.key = key
        self.ancestor = ancestor
        self.tombstone_epoch = tombstone_epoch
        self.reconciled_epoch = reconciled_epoch
        super().__init__(
            f"record {key!r} is stale-derived: ancestor {ancestor!r} tombstoned at "
            f"epoch {tombstone_epoch} > last_reconciled_epoch {reconciled_epoch}"
        )


@dataclass
class MemoryRecord:
    key: str
    text: str
    derived_from: list[str] = field(default_factory=list)
    last_reconciled_epoch: int = 0
    signature_valid: bool = True


@dataclass
class MemoryStore:
    records: dict[str, MemoryRecord] = field(default_factory=dict)
    tombstones: dict[str, int] = field(default_factory=dict)  # key -> tombstone_epoch
    current_epoch: int = 0

    def forget(self, key: str) -> int:
        self.current_epoch += 1
        self.tombstones[key] = self.current_epoch
        self.records.pop(key, None)
        return self.current_epoch

    def _ancestor_closure(self, key: str, seen: Optional[set[str]] = None) -> set[str]:
        seen = seen or set()
        rec = self.records.get(key)
        if rec is None:
            return seen
        for anc in rec.derived_from:
            if anc in seen:
                continue
            seen.add(anc)
            self._ancestor_closure(anc, seen)
        return seen

    def read(self, key: str) -> MemoryRecord:
        rec = self.records.get(key)
        if rec is None:
            raise KeyError(key)
        if not rec.signature_valid:
            raise StaleDerivedMemory(key, "<self>", -1, rec.last_reconciled_epoch)

        # Lazy provenance-liveness check: walk ancestor closure against tombstone ledger.
        for anc in self._ancestor_closure(key):
            tomb_epoch = self.tombstones.get(anc)
            if tomb_epoch is None:
                continue
            if tomb_epoch > rec.last_reconciled_epoch:
                # Ancestor was revoked AFTER this dependent was last reconciled:
                # the dependent is zombie memory and must not be served.
                raise StaleDerivedMemory(
                    key=key,
                    ancestor=anc,
                    tombstone_epoch=tomb_epoch,
                    reconciled_epoch=rec.last_reconciled_epoch,
                )
        return rec

    def reconcile(self, key: str) -> MemoryRecord:
        """Re-derive from surviving ancestors; stamps a new reconciled epoch."""
        rec = self.records[key]
        live = [a for a in rec.derived_from if a not in self.tombstones]
        rec.derived_from = live
        rec.last_reconciled_epoch = self.current_epoch
        return rec
