# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-poisoned-provenance-from-surviving-a-forget-operation-in-persistent-agent-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-poisoned-provenance-from-surviving-a-forget-operation-in-persistent-agent-stores.warrant.json
# Markdown SHA-256:   d5a3b3c3a19ceb4ccdddf0eb815cc744ea79075dc38c49149b3c8f11d211745b
# Code AST SHA-256:   86c448a6ef1b6a7bc7109d450b9a7235e1281686fcebe9b08cd94a52cc249e86
# Verified Classes:   ProvenanceLaunderingError, Record, ProvenanceStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a forget would strip taint from a derived record."""
    pass

@dataclass
class Record:
    rid: str
    trust: float
    derived_from: Set[str] = field(default_factory=set)
    tainted_by: Set[str] = field(default_factory=set)
    deleted: bool = False

class ProvenanceStore:
    def __init__(self):
        self.records: Dict[str, Record] = {}
        self.tombstone_edges: Dict[str, Set[str]] = {}  # child -> deleted parents

    def add(self, rec: Record) -> None:
        # Invariant 1: latched lower bound on write.
        for p in rec.derived_from:
            if p in self.records and self.records[p].trust < rec.trust:
                rec.trust = self.records[p].trust
            if p in self.records:
                rec.tainted_by |= self.records[p].tainted_by
        self.records[rec.rid] = rec

    def forget(self, rid: str) -> None:
        target = self.records[rid]
        target.deleted = True
        # Invariant 2 + 3: propagate taint to all reachable descendants,
        # tombstone the edge rather than dropping it.
        for child in self._descendants(rid):
            c = self.records[child]
            c.tainted_by.add(rid)
            c.trust = min(c.trust, target.trust)
            if rid in c.derived_from:
                c.derived_from.discard(rid)
                self.tombstone_edges.setdefault(child, set()).add(rid)

    def _descendants(self, rid: str) -> Set[str]:
        out, frontier = set(), {rid}
        while frontier:
            cur = frontier.pop()
            for r in self.records.values():
                if cur in r.derived_from and r.rid not in out:
                    out.add(r.rid)
                    frontier.add(r.rid)
        return out

    def read(self, rid: str, gate: float = 0.7) -> Record:
        r = self.records[rid]
        if r.deleted:
            raise ProvenanceLaunderingError(f"{rid} is forgotten; read refused")
        if r.tainted_by and r.trust >= gate:
            # Detect the exact laundering failure: tainted but passing gate.
            raise ProvenanceLaunderingError(
                f"{rid} tainted_by={sorted(r.tainted_by)} yet trust={r.trust} "
                f">= gate {gate}: provenance was laundered by a prior forget"
            )
        return r
