# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-when-a-forget-then-rewrite-cycle-re-derives-a-deleted-fact-from-a-retained-derivation-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-when-a-forget-then-rewrite-cycle-re-derives-a-deleted-fact-from-a-retained-derivation-cache.warrant.json
# Markdown SHA-256:   1e4f3900e2dcbc09931e27b151d894847c47ee7c2ed2b40fa117257b1a905569
# Code AST SHA-256:   d0d9d05d3b7e41287d64563f0b3693f71e97ec893cc85babbeda0feefbf70627
# Verified Classes:   ProvenanceLaunderingError, MemoryRecord, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a read would serve a payload whose provenance closure
    reaches a tombstoned record carrying an RTBF obligation."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    payload: str
    parents: List[str] = field(default_factory=list)
    retention: str = "default"
    tombstoned: bool = False


class MemoryStore:
    def __init__(self) -> None:
        self.records: Dict[str, MemoryRecord] = {}

    def write(self, rec: MemoryRecord) -> None:
        for p in rec.parents:
            parent = self.records.get(p)
            if parent is not None and parent.tombstoned:
                # Write-time guard: never derive from a tombstoned parent.
                raise ProvenanceLaunderingError(
                    f"cannot derive {rec.record_id} from tombstoned parent {p}"
                )
        self.records[rec.record_id] = rec

    def forget(self, record_id: str) -> None:
        target = self.records[record_id]
        target.tombstoned = True
        # Cascade: tombstone live descendants whose retention is weaker.
        changed = True
        while changed:
            changed = False
            for r in self.records.values():
                if r.tombstoned:
                    continue
                if record_id in self._ancestry(r):
                    if r.retention != "rtbf":
                        r.tombstoned = True
                        changed = True

    def _ancestry(self, rec: MemoryRecord) -> Set[str]:
        seen: Set[str] = set()
        stack = list(rec.parents)
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            parent = self.records.get(cur)
            if parent is not None:
                stack.extend(parent.parents)
        return seen

    def read(self, record_id: str) -> str:
        rec = self.records[record_id]
        if rec.tombstoned:
            raise ProvenanceLaunderingError(f"{record_id} is tombstoned")
        # Read-time guard: closure audit against tombstone set.
        for ancestor_id in self._ancestry(rec):
            ancestor = self.records.get(ancestor_id)
            if ancestor is not None and ancestor.tombstoned:
                raise ProvenanceLaunderingError(
                    f"{record_id} has tombstoned ancestor {ancestor_id}; "
                    f"payload is provenance-laundered"
                )
        return rec.payload


def audit_closure(store: MemoryStore) -> List[str]:
    """Post-forget audit: return live records whose ancestry hits a tombstone."""
    leaks: List[str] = []
    for rec in store.records.values():
        if rec.tombstoned:
            continue
        for ancestor_id in store._ancestry(rec):
            ancestor = store.records.get(ancestor_id)
            if ancestor is not None and ancestor.tombstoned:
                leaks.append(rec.record_id)
                break
    return leaks
