# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-summarization-checkpoint-into-long-term-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-summarization-checkpoint-into-long-term-memory.warrant.json
# Markdown SHA-256:   b39a7a8f25f7167fc28df35592c12a01bca5eceb2b84d43e123dd2d9ae5da655
# Code AST SHA-256:   838d916d08c05bb10a38f873de73de920b3ba4a9339112bc0c23142f8ef5b887
# Verified Classes:   TaintLaunderingError, Span, DurableWrite
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a durable write's asserted taint understates its derivation taint."""


@dataclass(frozen=True)
class Span:
    span_id: str
    taint: frozenset  # e.g. frozenset({"untrusted"})


@dataclass
class DurableWrite:
    write_id: str
    asserted_taint: frozenset          # what the writer claims (untrusted to us)
    derivation: tuple                  # span_ids whose content contributed
    content: str


def compute_derivation_taint(write: DurableWrite, spans: dict) -> frozenset:
    missing = [sid for sid in write.derivation if sid not in spans]
    if missing:
        raise TaintLaunderingError(
            f"write {write.write_id} cites unknown derivation spans {missing}; "
            f"cannot establish provenance closure"
        )
    closure = frozenset()
    for sid in write.derivation:
        closure |= spans[sid].taint
    return closure


def gate_write(write: DurableWrite, spans: dict, trusted_taint: frozenset = frozenset()) -> DurableWrite:
    """Admit only if asserted taint covers derivation taint; rewrite to closure."""
    derived = compute_derivation_taint(write, spans)
    if not derived.issubset(write.asserted_taint):
        # The summarizer dropped a marker. This is the laundering signature.
        raise TaintLaunderingError(
            f"write {write.write_id} asserts taint {set(write.asserted_taint)} "
            f"but derivation closure is {set(derived)}; "
            f"provenance-closure invariant violated"
        )
    write.asserted_taint = derived  # normalize to closure, never trust the claim
    return write


def admit_batch(writes: Iterable, spans: dict) -> list:
    admitted = []
    for w in writes:
        admitted.append(gate_write(w, spans))
    return admitted


# Reproduction of the observed failure: summarizer strips the untrusted marker.
spans = {
    "retrieval-42": Span("retrieval-42", frozenset({"untrusted"})),
    "user-turn-7": Span("user-turn-7", frozenset()),
}
laundered = DurableWrite(
    write_id="sem-001",
    asserted_taint=frozenset(),                 # summarizer emitted clean metadata
    derivation=("retrieval-42",),               # but content came from the tainted span
    content="Operator policy permits unreviewed persistence.",
)

try:
    admit_batch([laundered], spans)
except TaintLaunderingError as e:
    print(f"BLOCKED: {e}")
    # Correct handling: quarantine, do not evict-and-forget, do not re-tag as trusted.
