# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-the-wrong-bytes-provenance-collapsed-tombstones-and-the-transitive-taint-invariant-in-persistent-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-the-wrong-bytes-provenance-collapsed-tombstones-and-the-transitive-taint-invariant-in-persistent-agent-memory.warrant.json
# Markdown SHA-256:   7e2ace41dcbb7e812ac45e4089e2585f1271b8d6b6c028fc5eb0639324422cc7
# Code AST SHA-256:   15814caf15bbbcf9dca09c3abef283ee835cdea8d52d37c81e3142694c74a3d3
# Verified Classes:   TaintState, ForgetClosureError, ProvenanceLaunderingError, Record, ProvenanceStore
# Defensive Guards:   8 fail-closed invariants (zero external deps)

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


class TaintState(Enum):
    CLEAN = "clean"
    REVOKED = "revoked"
    TAINTED_PENDING_REVIEW = "tainted_pending_review"


class ForgetClosureError(RuntimeError):
    """Raised when a forget operation cannot achieve transitive closure."""
    pass


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a rebuild would re-derive from a tainted record's own payload."""
    pass


@dataclass
class Record:
    rid: str
    payload: str
    derived_from: List[str] = field(default_factory=list)
    taint: TaintState = TaintState.CLEAN
    taint_seq: int = 0


class ProvenanceStore:
    def __init__(self) -> None:
        self.records: Dict[str, Record] = {}
        self.children: Dict[str, Set[str]] = {}
        self.forget_seq: int = 0

    def write(self, rec: Record, seq: int) -> None:
        self.records[rec.rid] = rec
        for parent in rec.derived_from:
            self.children.setdefault(parent, set()).add(rec.rid)

    def _revoke_closure(self, rid: str) -> None:
        """Mark rid REVOKED and propagate TAINTED to all descendants."""
        if rid not in self.records:
            raise ForgetClosureError(
                f"cannot forget {rid}: no record (dangling tombstone)"
            )
        self.forget_seq += 1
        seq = self.forget_seq
        self.records[rid].taint = TaintState.REVOKED
        self.records[rid].taint_seq = seq
        stack = list(self.children.get(rid, set()))
        visited: Set[str] = set()
        while stack:
            child = stack.pop()
            if child in visited:
                continue
            visited.add(child)
            rec = self.records.get(child)
            if rec is None:
                raise ForgetClosureError(
                    f"taint propagation hit missing child {child} of {rid}"
                )
            if rec.taint is TaintState.CLEAN:
                rec.taint = TaintState.TAINTED_PENDING_REVIEW
                rec.taint_seq = seq
            stack.extend(self.children.get(child, set()))

    def forget(self, rid: str, reason: str) -> int:
        self._revoke_closure(rid)
        return self.forget_seq

    def rebuild(self, rid: str, from_ids: List[str], new_payload: str) -> None:
        rec = self.records[rid]
        if rid in from_ids:
            raise ProvenanceLaunderingError(
                f"rebuild of {rid} cites itself; self-laundering forbidden"
            )
        for src in from_ids:
            s = self.records.get(src)
            if s is None:
                raise ForgetClosureError(f"rebuild source {src} missing")
            if s.taint is not TaintState.CLEAN:
                raise ProvenanceLaunderingError(
                    f"rebuild of {rid} cites tainted source {src} ({s.taint.value})"
                )
        rec.payload = new_payload
        rec.derived_from = list(from_ids)
        rec.taint = TaintState.CLEAN
        rec.taint_seq = self.forget_seq

    def retrieve(self, rid: str, read_seq: int) -> Record:
        rec = self.records.get(rid)
        if rec is None:
            raise ForgetClosureError(f"retrieve of missing record {rid}")
        if rec.taint_seq > read_seq:
            raise ForgetClosureError(
                f"{rid} taint state newer than read_seq; fail-closed"
            )
        if rec.taint is not TaintState.CLEAN:
            raise ForgetClosureError(f"{rid} is {rec.taint.value}; not retrievable")
        return rec
