# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-taint-monotonicity-when-a-quarantined-retrieval-span-is-re-derived-by-a-trusted-summarizer.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-taint-monotonicity-when-a-quarantined-retrieval-span-is-re-derived-by-a-trusted-summarizer.warrant.json
# Markdown SHA-256:   0b13d221f646ff9128e53fc9ab34b9c8c37a60aaf5fef1ebb2907d430d03c664
# Code AST SHA-256:   e94da8628ae9109d7faadeaa53cc27f7fc5e32aa3622db9637f454a42fc47ce8
# Verified Classes:   TaintLaunderingError, Span, ProvenanceTracker
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a span's taint is weaker than the join over its derivation set."""


TRUSTED = 0
UNTRUSTED = 1


def join(taints: Iterable[int]) -> int:
    """Least upper bound over derivation DAG. UNTRUSTED dominates."""
    result = TRUSTED
    for t in taints:
        result = max(result, t)
    return result


@dataclass
class Span:
    span_id: str
    taint: int
    # Spans physically present in the emitter's context, enumerated by the
    # RUNTIME, never by the model. Completeness is the load-bearing property.
    context_set: tuple[str, ...] = field(default_factory=tuple)


class ProvenanceTracker:
    def __init__(self) -> None:
        self._spans: dict[str, Span] = {}

    def register(self, span: Span) -> None:
        self._spans[span.span_id] = span

    def admit_summary(self, summary: Span) -> None:
        """
        Admit a summarizer output. The runtime computes taint as the join over
        the spans actually present in the summarizer's context window, ignoring
        any self-reported 'used' set. Rejects emission-time 'trusted' stamping
        of a summary with untrusted ancestors.
        """
        if not summary.context_set:
            raise TaintLaunderingError(
                f"summary {summary.span_id!r} has empty context_set; "
                "derivation edges are unrecorded and taint cannot be joined"
            )
        try:
            ancestors = [self._spans[sid] for sid in summary.context_set]
        except KeyError as exc:
            raise TaintLaunderingError(
                f"summary {summary.span_id!r} cites unknown ancestor {exc.args[0]!r}"
            ) from exc

        required = join(a.taint for a in ancestors)
        if summary.taint < required:
            raise TaintLaunderingError(
                f"summary {summary.span_id!r} stamped taint={summary.taint} "
                f"but join over context_set is {required}; "
                "trusted emitter laundered untrusted retrieval content"
            )
        self.register(summary)


def gate_tool_call(tracker: ProvenanceTracker, arg_span_ids: Iterable[str]) -> None:
    """
    Enforce the taint gate at the tool-call boundary using transitive closure
    over the derivation DAG, not immediate parents only.
    """
    frontier = list(arg_span_ids)
    seen: set[str] = set()
    while frontier:
        sid = frontier.pop()
        if sid in seen:
            continue
        seen.add(sid)
        span = tracker._spans.get(sid)
        if span is None:
            raise TaintLaunderingError(
                f"tool argument references unregistered span {sid!r}; "
                "provenance chain is broken and cannot be trusted"
            )
        if span.taint == UNTRUSTED:
            raise TaintLaunderingError(
                f"tool argument derives from untrusted span {sid!r}; "
                "route to quarantined executor or refuse"
            )
        frontier.extend(span.context_set)
