# 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-forget-collide-in-a-scoped-memory-tool-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-forgotten-memories-when-ttl-eviction-and-right-to-forget-collide-in-a-scoped-memory-tool-schema.warrant.json
# Markdown SHA-256:   98d8c55430f4f82d9f721e8fdce9d6727caf80d6313695f65a719c3d638d2dcf
# Code AST SHA-256:   bc615d47aa4a65ae3c90cc66b1ad182af94f2f9fcb9743d1223a271c34fabcf7
# Verified Classes:   ForgottenAncestorError, Record, ScopedMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ForgottenAncestorError(RuntimeError):
    """Raised when a derived write or read would resurrect forgotten lineage."""


@dataclass
class Record:
    scope: str
    key: str
    value: str
    ttl_s: Optional[int] = None
    provenance: tuple[str, ...] = ()  # ancestor keys this record was derived from


class ScopedMemory:
    def __init__(self) -> None:
        self._records: dict[tuple[str, str], Record] = {}
        self._forget_ledger: set[tuple[str, str]] = set()  # (scope, key)
        self._derivation_frontier: dict[str, int] = {}  # scope -> epoch

    def forget(self, scope: str, key: str) -> None:
        self._forget_ledger.add((scope, key))
        self._records.pop((scope, key), None)
        # bump frontier so in-flight distillation over this scope must abort
        self._derivation_frontier[scope] = self._derivation_frontier.get(scope, 0) + 1

    def _is_forgotten(self, scope: str, key: str) -> bool:
        return (scope, key) in self._forget_ledger

    def assert_no_forgotten_ancestor(self, rec: Record) -> None:
        for anc in rec.provenance:
            if self._is_forgotten(rec.scope, anc):
                raise ForgottenAncestorError(
                    f"derived write {rec.scope}/{rec.key} has forgotten ancestor {anc}"
                )

    def write(self, rec: Record, frontier_epoch: Optional[int] = None) -> None:
        # derived writes must declare the frontier they observed
        if rec.provenance and frontier_epoch is not None:
            if frontier_epoch != self._derivation_frontier.get(rec.scope, 0):
                raise ForgottenAncestorError(
                    f"stale derivation frontier for {rec.scope}: "
                    f"saw {frontier_epoch}, current {self._derivation_frontier.get(rec.scope, 0)}"
                )
        self.assert_no_forgotten_ancestor(rec)
        self._records[(rec.scope, rec.key)] = rec

    def read(self, scope: str, key: str) -> str:
        if self._is_forgotten(scope, key):
            raise ForgottenAncestorError(f"{scope}/{key} was forgotten (RTF)")
        rec = self._records.get((scope, key))
        if rec is None:
            raise KeyError(f"{scope}/{key} miss: evicted-or-absent")
        return rec.value


# Trigger: forget a key, then a distillation job derives a summary that
# includes it and tries to write back with stale frontier.
mem = ScopedMemory()
mem.write(Record("user:8812", "payment_hint", "card ending 4242"))
mem.forget("user:8812", "payment_hint")
try:
    mem.write(
        Record(
            "user:8812",
            "profile_summary",
            "user prefers card ending 4242",
            provenance=("payment_hint",),
        ),
        frontier_epoch=0,  # stale: forget bumped frontier to 1
    )
except ForgottenAncestorError as e:
    print("blocked:", e)
