# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tainted-context-from-laundering-privilege-across-a-sandboxed-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tainted-context-from-laundering-privilege-across-a-sandboxed-tool-boundary.warrant.json
# Markdown SHA-256:   3797555f43c438b58f9ca8deb2858fd6c642471b48071cea353748efbe276235
# Code AST SHA-256:   512bbb1f16cdbf147f6261ba9e0db38b9c9c076f757e3bf415163f3d7cda38c0
# Verified Classes:   TaintLaunderingError, Span, TaintLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Taint = Literal["CLEAN", "TAINT_SOURCE"]

class TaintLaunderingError(RuntimeError):
    """Raised when a privileged call's derivation DAG reaches a TAINT_SOURCE
    span without a recorded non-generative declassification cut."""
    pass

@dataclass
class Span:
    id: str
    taint: Taint
    parents: list[str] = field(default_factory=list)  # derivation edges

class TaintLedger:
    def __init__(self) -> None:
        self.spans: dict[str, Span] = {}
        self.cuts: set[tuple[str, str]] = set()  # (child_id, parent_id) declassified

    def add_source(self, span_id: str) -> None:
        self.spans[span_id] = Span(span_id, "TAINT_SOURCE")

    def add_generation(self, span_id: str, context_ids: list[str]) -> None:
        # Derivation edge: output inherits join of input taints.
        taint: Taint = "CLEAN"
        for cid in context_ids:
            if self.spans[cid].taint == "TAINT_SOURCE":
                taint = "TAINT_SOURCE"
                break
        self.spans[span_id] = Span(span_id, taint, parents=list(context_ids))

    def declassify(self, child_id: str, parent_id: str, verifier: str) -> None:
        # Only a non-generative verifier may cut an edge. The model may not.
        if verifier == "model":
            raise TaintLaunderingError(
                f"model attempted self-declassification of {child_id}<-{parent_id}"
            )
        edge = (child_id, parent_id)
        if edge not in {(child_id, p) for p in self.spans[child_id].parents}:
            raise TaintLaunderingError(f"no derivation edge {edge} to declassify")
        self.cuts.add(edge)

    def effective_taint(self, span_id: str) -> Taint:
        # Walk the DAG; a TAINT_SOURCE ancestor with no cut edge taints the leaf.
        seen: set[str] = set()
        stack = [(span_id, None)]
        while stack:
            sid, parent = stack.pop()
            if sid in seen:
                continue
            seen.add(sid)
            span = self.spans[sid]
            if span.taint == "TAINT_SOURCE":
                if parent is None or (sid, parent) not in self.cuts:
                    return "TAINT_SOURCE"
            for p in span.parents:
                stack.append((p, sid))
        return "CLEAN"

def admit_privileged_call(ledger: TaintLedger, arg_span_id: str, tool: str) -> None:
    if ledger.effective_taint(arg_span_id) == "TAINT_SOURCE":
        raise TaintLaunderingError(
            f"privileged tool '{tool}' blocked: argument span {arg_span_id} "
            f"derives from TAINT_SOURCE with no declassification cut"
        )
    # admitted
