# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-demote-a-tool-call-s-privilege-tier-when-an-argument-s-taint-label-is-inherited-transitively-through-a-summariz.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-demote-a-tool-call-s-privilege-tier-when-an-argument-s-taint-label-is-inherited-transitively-through-a-summariz.warrant.json
# Markdown SHA-256:   25039d0d9cf537d6d2c11fe16a4de06f6d53f0d1fb7d2046a23f293d83775770
# Code AST SHA-256:   95a854278dcf3ec64bd864e4641e78261c066011fe3752dc951e2dafcc8b9f73
# Verified Classes:   TaintLaunderingError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

UNTRUSTED = "UNTRUSTED"


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged sink is reached by an argument whose taint
    was dropped across a model-call hop without a non-model declassification."""


@dataclass
class Span:
    span_id: str
    kind: str                      # "source" | "model_call" | "tool_call"
    inputs: list[str] = field(default_factory=list)
    taint_labels: set[str] = field(default_factory=set)
    declassified_by: set[str] = field(default_factory=set)


def propagate_taint(spans: dict[str, Span]) -> None:
    """Dataflow taint propagation. A model_call transmits the union of its
    inputs' taint to its outputs. Declassification only clears taint when the
    gate is non-model and recorded on the span."""
    for span in spans.values():
        if span.kind == "source":
            span.taint_labels = {UNTRUSTED}
        elif span.kind == "model_call":
            inherited: set[str] = set()
            for src_id in span.inputs:
                inherited |= spans[src_id].taint_labels
            span.taint_labels = inherited - span.declassified_by


def enforce_least_privilege(span: Span, tier: str) -> str:
    """Decide the effective tier for a tool call. WRITE+ sinks must demote or
    fail if any input carries live taint."""
    if span.kind != "tool_call":
        raise TaintLaunderingError(f"not a tool_call span: {span.span_id}")
    live = set()
    for src_id in span.inputs:
        live |= span.taint_labels  # already propagated upstream
    if not live:
        return tier
    if tier in {"WRITE", "EXEC", "NETWORK"}:
        # No non-model declassification occurred on this path.
        raise TaintLaunderingError(
            f"span {span.span_id} reached {tier} sink with live taint {sorted(live)}; "
            f"demote to SANDBOX or add a recorded non-model declassification gate"
        )
    return tier  # READ-tier sinks may proceed with taint logged


def run_pipeline(spans: dict[str, Span]) -> None:
    propagate_taint(spans)
    # Summarizer output feeds a create_ticket WRITE call. The model_call hop
    # has no declassification, so taint must survive to the sink.
    create = spans["create_ticket"]
    enforce_least_privilege(create, tier="WRITE")


if __name__ == "__main__":
    spans = {
        "fetch_inbox": Span("fetch_inbox", "source"),
        "summarize": Span("summarize", "model_call", inputs=["fetch_inbox"]),
        "create_ticket": Span("create_ticket", "tool_call", inputs=["summarize"]),
    }
    run_pipeline(spans)  # raises TaintLaunderingError: taint survived the model hop
