# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-provenance-as-precondition-on-forget-when-a-memory-tool-s-delete-path-shadows-its-read-path.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-provenance-as-precondition-on-forget-when-a-memory-tool-s-delete-path-shadows-its-read-path.warrant.json
# Markdown SHA-256:   a77bbae5335a0fe5d9802fd26017bd009e8b8e442f8b3560bf35ee5b95eb7686
# Code AST SHA-256:   42e489e04655d88dce09a47f57a8e166fc6b145ca765737922cf969f438a571b
# Verified Classes:   ErasureResidualError, ResurrectionError, Record, ProvenanceMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class ErasureResidualError(RuntimeError):
    """Raised when forget() leaves transitively-reachable records behind."""
    pass

class ResurrectionError(RuntimeError):
    """Raised when a write attempts to re-materialize a tombstoned record."""
    pass

@dataclass
class Record:
    id: str
    content_hash: str
    provenance: dict            # {"source_episode_ids": [...], "consent_scope": str}
    deleted: bool = False

class ProvenanceMemory:
    def __init__(self):
        self._records: dict[str, Record] = {}
        self._tombstones: dict[str, str] = {}   # content_hash -> provenance_root

    def write(self, rec: Record) -> None:
        if rec.content_hash in self._tombstones:
            raise ResurrectionError(
                f"write of {rec.id} attempts to resurrect tombstoned content "
                f"{rec.content_hash} (root {self._tombstones[rec.content_hash]})"
            )
        self._records[rec.id] = rec

    def _reachable(self, root_id: str) -> set[str]:
        # transitive closure over provenance edges; indirect lineage included
        seen, frontier = set(), [root_id]
        while frontier:
            cur = frontier.pop()
            if cur in seen:
                continue
            seen.add(cur)
            for rid, rec in self._records.items():
                if cur in rec.provenance.get("source_episode_ids", []) and rid not in seen:
                    frontier.append(rid)
        return seen

    def forget(self, root_id: str, caller_scope: str) -> list[str]:
        reachable = self._reachable(root_id)
        if root_id not in reachable:
            raise ErasureResidualError(f"root {root_id} not found; cannot authorize erasure")
        # precondition: every reachable record must be covered by caller_scope
        for rid in reachable:
            rec = self._records[rid]
            if rec.provenance.get("consent_scope") != caller_scope:
                raise ErasureResidualError(
                    f"scope mismatch on {rid}: {rec.provenance.get('consent_scope')} "
                    f"!= {caller_scope}; refusing partial erasure"
                )
        # tombstone-first, then delete, atomically per record
        for rid in reachable:
            rec = self._records[rid]
            self._tombstones[rec.content_hash] = root_id
            rec.deleted = True
        return sorted(reachable)

    def verify_erasure(self, root_id: str) -> None:
        residual = [
            rid for rid, rec in self._records.items()
            if not rec.deleted and root_id in self._reachable(rid)
        ]
        if residual:
            raise ErasureResidualError(
                f"erasure of {root_id} incomplete; residual records: {residual}"
            )
