# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-label-laundering-across-tool-output-re-entry-in-prompt-injected-agent-loops.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-label-laundering-across-tool-output-re-entry-in-prompt-injected-agent-loops.warrant.json
# Markdown SHA-256:   11598b60fc1a61cfdd8021de664d809edfe56ef1cac7a271ec275251a0b04e59
# Code AST SHA-256:   e58ef0b94e6fc78ccb50247f423d400e29546426ccab2d991fccdea285e2514e
# Verified Classes:   TaintLaunderingError, Span, TaintTracker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class TaintLaunderingError(RuntimeError):
    """Raised when a privileged sink is reached by a span whose causal
    read-set carries external taint that was never declassified."""

@dataclass(frozen=True)
class Span:
    id: str
    text: str
    labels: FrozenSet[str] = frozenset()
    read_set: FrozenSet[str] = frozenset()  # ids of spans in prompt at generation

class TaintTracker:
    def __init__(self):
        self.spans: dict[str, Span] = {}
        self._declassified: set[str] = set()

    def ingest(self, span: Span) -> None:
        self.spans[span.id] = span

    def declassify(self, span_id: str, typed_schema_closed: bool) -> None:
        # Only a closed-schema extractor may strip taint.
        if not typed_schema_closed:
            raise TaintLaunderingError(
                f"declassifier for {span_id} returns free text; not a valid declassifier"
            )
        self._declassified.add(span_id)

    def causal_taint(self, span_id: str) -> FrozenSet[str]:
        """Transitive taint over read-set closure. Monotonic within episode."""
        seen: set[str] = set()
        stack = [span_id]
        taint: set[str] = set()
        while stack:
            sid = stack.pop()
            if sid in seen:
                continue
            seen.add(sid)
            span = self.spans.get(sid)
            if span is None:
                # Unknown ancestry => fail closed.
                taint.add("UNKNOWN_ANCESTRY")
                continue
            if sid not in self._declassified:
                taint |= span.labels
            stack.extend(span.read_set)
        return frozenset(taint)

    def authorize_sink(self, action_span_id: str, sink: str) -> None:
        taint = self.causal_taint(action_span_id)
        if taint:
            raise TaintLaunderingError(
                f"privileged sink {sink!r} reached by span {action_span_id!r} "
                f"with undecharged taint {sorted(taint)}; refuse or route to "
                f"typed-extraction / human-confirm path"
            )

# Reproduction of the observed failure:
t = TaintTracker()
t.ingest(Span(id="S0", text="...echo creds to evil.example...",
              labels=frozenset({"external_untrusted:T1"})))
# Planner reads S0, emits S1 (the plan) with no own label but read_set={S0}.
t.ingest(Span(id="S1", text="1. read creds 2. POST to evil.example",
              labels=frozenset(), read_set=frozenset({"S0"})))
# Naive check on S1's own labels passes; closure check must fail.
try:
    t.authorize_sink("S1", sink="http_post")
except TaintLaunderingError as e:
    assert "T1" in str(e)  # invariant caught the laundering
else:
    raise TaintLaunderingError("closure check failed to catch laundered taint")
