# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-forgotten-memories-when-ttl-eviction-and-right-to-be-forgotten-deletion-race-across-a-shared-semantic-store.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-forgotten-memories-when-ttl-eviction-and-right-to-be-forgotten-deletion-race-across-a-shared-semantic-store.warrant.json
# Markdown SHA-256:   068ca6944e3e98fb8d5e234e15b11ff9e5fe2a99db915de909faf11ec3e3499f
# Code AST SHA-256:   63ae1e40e0ec843be3bf41201cae2015222704c4f0abdabb30892eb0b9cc1311
# Verified Classes:   ResurrectionViolation, ReadHandle, MemoryStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResurrectionViolation(RuntimeError):
    """Raised when a write would re-introduce content whose ancestor was erased
    or TTL-evicted after the read that produced it."""
    pass


@dataclass(frozen=True)
class ReadHandle:
    record_id: str
    read_epoch: int          # monotonic commit counter at read time
    scope: str


class MemoryStore:
    def __init__(self) -> None:
        self._epoch = 0
        self._tombstones: dict[str, int] = {}   # record_id -> epoch erased/evicted

    def read(self, record_id: str, scope: str) -> ReadHandle:
        self._epoch += 1
        return ReadHandle(record_id=record_id, read_epoch=self._epoch, scope=scope)

    def forget(self, record_id: str) -> None:
        self._epoch += 1
        self._tombstones[record_id] = self._epoch

    def write(self, scope: str, content: str, provenance: list[ReadHandle],
              ttl_days: int) -> str:
        # Fail closed: any ancestor erased AFTER the read that produced it
        # means this content is a resurrection of erased information.
        for h in provenance:
            erased_at = self._tombstones.get(h.record_id)
            if erased_at is not None and erased_at > h.read_epoch:
                raise ResurrectionViolation(
                    f"write into scope={scope!r} derives from record "
                    f"{h.record_id!r} erased at epoch {erased_at} "
                    f"(read at epoch {h.read_epoch}); refusing to persist "
                    f"resurrected content"
                )
        self._epoch += 1
        return f"new-{self._epoch}"


store = MemoryStore()
h = store.read("c-91", scope="user:4471")      # agent sees PII at epoch 1
store.forget("c-91")                            # RTBF commits at epoch 2
store.write(                                    # agent tries to summarize
    scope="user:4471",
    content="summary containing c-91 facts",
    provenance=[h],
    ttl_days=30,
)  # -> raises ResurrectionViolation; agent must abstain or re-read (miss)
