# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-whose-provenance-tag-resolves-to-a-tombstoned-source.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-whose-provenance-tag-resolves-to-a-tombstoned-source.warrant.json
# Markdown SHA-256:   f3c97857a6198851103f1c474c9edf5f80832742520b6f827d737855fc6140b3
# Code AST SHA-256:   8109cdbaa251ff6cf3189f78deda7f3c6bf43e0cf70341647108210aa34b55bb
# Verified Classes:   ProvenanceState, ErasureSoundnessError, Record, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class ProvenanceState(Enum):
    LIVE = "LIVE"
    TOMBSTONED = "TOMBSTONED"
    EXPIRED = "EXPIRED"
    ABSENT = "ABSENT"


class ErasureSoundnessError(RuntimeError):
    """Raised when a memory operation would violate erasure-proof soundness."""


@dataclass
class Record:
    id: str
    value: str
    provenance: list[str] = field(default_factory=list)
    state: ProvenanceState = ProvenanceState.LIVE


def canonical_provenance_key(raw: str, version: int = 2) -> str:
    # Single canonicalization used by BOTH write and forget paths.
    if version == 2:
        return "v2:" + hashlib.sha256(raw.encode()).hexdigest()
    return raw


class MemoryStore:
    def __init__(self, closure_depth_bound: int = 8):
        self._records: dict[str, Record] = {}
        self._tombstones: set[str] = set()
        self._depth_bound = closure_depth_bound

    def write(self, rec: Record) -> None:
        for src in rec.provenance:
            key = canonical_provenance_key(src)
            if key in self._tombstones:
                raise ErasureSoundnessError(
                    f"refusing write of {rec.id!r}: provenance {src!r} "
                    f"(canonical {key!r}) is TOMBSTONED; derivative would "
                    f"survive the erasure proof"
                )
            src_rec = self._records.get(src)
            if src_rec is not None and src_rec.state == ProvenanceState.EXPIRED:
                raise ErasureSoundnessError(
                    f"refusing write of {rec.id!r}: provenance {src!r} is "
                    f"EXPIRED (not erased); re-derivation would launder expiry"
                )
        self._records[rec.id] = rec

    def read(self, rec_id: str) -> Record:
        rec = self._records[rec_id]
        for src in rec.provenance:
            if canonical_provenance_key(src) in self._tombstones:
                raise ErasureSoundnessError(
                    f"read of {rec_id!r} blocked: provenance {src!r} tombstoned"
                )
        return rec

    def forget(self, rec_id: str) -> dict:
        self._tombstones.add(canonical_provenance_key(rec_id))
        self._records[rec_id].state = ProvenanceState.TOMBSTONED

        frontier = [rec_id]
        scanned: list[str] = []
        depth = 0
        while frontier and depth <= self._depth_bound:
            nxt: list[str] = []
            for node in frontier:
                for rid, rec in self._records.items():
                    if any(canonical_provenance_key(p) == canonical_provenance_key(node)
                           for p in rec.provenance):
                        rec.state = ProvenanceState.TOMBSTONED
                        self._tombstones.add(canonical_provenance_key(rid))
                        scanned.append(rid)
                        nxt.append(rid)
            frontier = nxt
            depth += 1

        if frontier:
            return {
                "erased": [rec_id],
                "derivatives_scanned": len(scanned),
                "frontier": frontier,
                "status": "INCOMPLETE",
                "reason": f"closure depth exceeded bound {self._depth_bound}",
            }
        return {
            "erased": [rec_id],
            "derivatives_scanned": len(scanned),
            "frontier": [],
            "status": "PROVEN",
        }
