# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-right-to-be-forgotten-tombstone-has-silently-diverged-from-a-still-live-derivative-in-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-right-to-be-forgotten-tombstone-has-silently-diverged-from-a-still-live-derivative-in-agent-memory.warrant.json
# Markdown SHA-256:   9ed9bd34a18c36f86f189e607c7ea77ae27d49b6063a1856a5fdbbbaa434124e
# Code AST SHA-256:   501e9c8d1ed4a9378e53036628190992cf8629dde728fa05b0e460098c265b7d
# Verified Classes:   ErasureClosureViolation, MemoryRecord, ScopedMemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, List, Set


class ErasureClosureViolation(RuntimeError):
    """Raised when a forget() tombstone leaves a live derivative reachable."""
    pass


@dataclass
class MemoryRecord:
    id: str
    text: str
    derived_from: List[str] = field(default_factory=list)
    derived_into: List[str] = field(default_factory=list)
    snapshot_epoch: int = 0
    tombstoned: bool = False


class ScopedMemoryStore:
    def __init__(self) -> None:
        self.records: Dict[str, MemoryRecord] = {}
        self.erasure_epoch: int = 0
        self.index_epoch: Dict[str, int] = {}  # index_name -> epoch built against

    def write(self, rec: MemoryRecord) -> None:
        self.records[rec.id] = rec

    def summarize(self, child_id: str, text: str, sources: List[str]) -> None:
        rec = MemoryRecord(
            id=child_id,
            text=text,
            derived_from=list(sources),
            snapshot_epoch=self.erasure_epoch,
        )
        self.records[child_id] = rec
        for s in sources:
            if s in self.records:
                # forward provenance edge is mandatory for bounded cascade
                self.records[s].derived_into.append(child_id)

    def forget(self, target_id: str) -> None:
        if target_id not in self.records:
            return
        # compute forward closure BEFORE writing tombstone (atomicity precondition)
        closure: Set[str] = set()
        stack = [target_id]
        while stack:
            cur = stack.pop()
            if cur in closure:
                continue
            closure.add(cur)
            for child in self.records.get(cur, MemoryRecord("", "")).derived_into:
                stack.append(child)

        for rid in closure:
            self.records[rid].tombstoned = True

        self.erasure_epoch += 1
        for idx in self.index_epoch:
            self.index_epoch[idx] = self.erasure_epoch

    def audit_erasure(self, target_id: str) -> None:
        """Post-condition: no live record may have target in derivation closure."""
        for rid, rec in self.records.items():
            if rec.tombstoned:
                continue
            # walk backward derivation closure of every live record
            seen: Set[str] = set()
            stack = list(rec.derived_from)
            while stack:
                cur = stack.pop()
                if cur in seen:
                    continue
                seen.add(cur)
                if cur == target_id:
                    raise ErasureClosureViolation(
                        f"live record {rid} still derives from erased {target_id} "
                        f"(snapshot_epoch={rec.snapshot_epoch}, "
                        f"erasure_epoch={self.erasure_epoch})"
                    )
                parent = self.records.get(cur)
                if parent:
                    stack.extend(parent.derived_from)
            if rec.snapshot_epoch < self.erasure_epoch and target_id in seen:
                raise ErasureClosureViolation(
                    f"record {rid} predates erasure epoch and references {target_id}"
                )


def run_scenario() -> None:
    store = ScopedMemoryStore()
    store.write(MemoryRecord("ep_88213", "PII: alice@example.org"))
    store.summarize("sem_04417", "user contact is alice at example domain", ["ep_88213"])

    store.forget("ep_88213")
    store.audit_erasure("ep_88213")  # passes only if cascade closed

    # simulate the divergence: a summary created after tombstone from stale snapshot
    store.records["ep_88213"].tombstoned = False  # attacker/race re-materializes source
    store.summarize("sem_09999", "contact alice example", ["ep_88213"])
    store.records["ep_88213"].tombstoned = True

    try:
        store.audit_erasure("ep_88213")
    except ErasureClosureViolation as e:
        raise ErasureClosureViolation(
            f"right-to-be-forgotten invariant broken: {e}"
        )


if __name__ == "__main__":
    run_scenario()
