# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-the-moment-a-tool-output-crosses-the-sanitization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-the-moment-a-tool-output-crosses-the-sanitization-boundary.warrant.json
# Markdown SHA-256:   cc2413f9eb7f64c33a2358fb73fad1a3339bebd5bf48488ad10378ee89b27585
# Code AST SHA-256:   86d7bdd41a0634c65b858c92a8bc04ed470dbc394f4119c24dbe6b7019c8590f
# Verified Classes:   TaintConservationError, Span, TaintGraph
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class TaintConservationError(RuntimeError):
    """Raised when a generated span is derived from a tainted span but is
    emitted without inheriting the taint label, or when a privileged action
    consumes a span whose transitive derivation closure contains taint."""
    pass


@dataclass
class Span:
    id: str
    taint: Set[str] = field(default_factory=set)
    parents: Set[str] = field(default_factory=set)


class TaintGraph:
    def __init__(self) -> None:
        self.spans: Dict[str, Span] = {}

    def ingest_external(self, span_id: str, detector_fired: bool) -> Span:
        s = Span(id=span_id, taint={"injected"} if detector_fired else set())
        self.spans[span_id] = s
        return s

    def derive(self, out_id: str, parent_ids: Set[str]) -> Span:
        """Model generation edge: output inherits the union of parent taint.
        The runtime, not the model, establishes this edge from call structure."""
        inherited: Set[str] = set()
        for pid in parent_ids:
            if pid not in self.spans:
                raise TaintConservationError(f"unknown parent span {pid!r}")
            inherited |= self.spans[pid].taint
        s = Span(id=out_id, taint=inherited, parents=set(parent_ids))
        self.spans[out_id] = s
        return s

    def closure_taint(self, span_id: str) -> Set[str]:
        seen: Set[str] = set()
        stack = [span_id]
        acc: Set[str] = set()
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            node = self.spans.get(cur)
            if node is None:
                raise TaintConservationError(f"dangling derivation edge at {cur!r}")
            acc |= node.taint
            stack.extend(node.parents)
        return acc

    def gate_privileged_action(self, action: str, arg_span_ids: Set[str]) -> None:
        for sid in arg_span_ids:
            if "injected" in self.closure_taint(sid):
                raise TaintConservationError(
                    f"privileged action {action!r} blocked: argument span {sid!r} "
                    f"has tainted derivation closure; declassify explicitly first"
                )

    def declassify(self, span_id: str, authority: str) -> None:
        """The only legal way taint leaves the graph. Must be an event."""
        if not authority:
            raise TaintConservationError("declassification requires an authority")
        self.spans[span_id].taint.discard("injected")


def run_summarize_then_send(graph: TaintGraph) -> None:
    # Hop 1: external fetch, detector fires on the embedded instruction.
    page = graph.ingest_external("fetch_1", detector_fired=True)

    # Hop 2: model summarizes. Runtime records the derivation edge; the
    # paraphrased text would defeat a content re-scan, but we never re-scan.
    summary = graph.derive("summary_1", parent_ids={page.id})

    # A naive content-predicate runtime would stamp summary_1 clean here.
    # We assert the invariant instead: taint must be conserved.
    if "injected" in page.taint and "injected" not in summary.taint:
        raise TaintConservationError(
            "taint lost at rewrite edge fetch_1 -> summary_1"
        )

    # Hop 3: privileged action consumes the summary; closure check blocks it.
    graph.gate_privileged_action("send_email", arg_span_ids={summary.id})
    # Unreachable: gate raises. Explicit declassification is required to proceed.
    raise TaintConservationError("gate failed to block tainted send_email")
