# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-that-survives-a-tool-output-round-trip-when-the-taint-label-is-derived-from-content-rather-than-pro.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-that-survives-a-tool-output-round-trip-when-the-taint-label-is-derived-from-content-rather-than-pro.warrant.json
# Markdown SHA-256:   02f13ffbfe38b9d8fe543aeac9ef583073ffce15c192230034f8427977e7f8c7
# Code AST SHA-256:   11c01da226c266b3cdddefc34703c3c38ec4d5c56574dca6d56d1594cbb115a8
# Verified Classes:   Trust, TaintLineageError, Span, TaintTracker
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class Trust(IntEnum):
    UNTRUSTED = 0
    QUARANTINED = 1
    TRUSTED = 2


class TaintLineageError(RuntimeError):
    """Raised when a sink's argument lineage reaches an untrusted span."""


@dataclass
class Span:
    span_id: str
    trust: Trust
    constituents: tuple[str, ...] = field(default_factory=tuple)


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

    def register_source(self, span_id: str, trust: Trust) -> None:
        # Provenance assigned at transport boundary; immutable.
        self._spans[span_id] = Span(span_id, trust)

    def derive(self, span_id: str, author_trust: Trust, quoted: Iterable[str]) -> None:
        # Join-only across derivation: cannot rise above lowest constituent.
        floor = min((self._spans[q].trust for q in quoted), default=author_trust)
        self._spans[span_id] = Span(span_id, min(author_trust, floor), tuple(quoted))

    def _lineage_min(self, span_id: str, seen: set[str]) -> Trust:
        if span_id in seen:
            return Trust.TRUSTED
        seen.add(span_id)
        span = self._spans[span_id]
        worst = span.trust
        for c in span.constituents:
            worst = min(worst, self._lineage_min(c, seen))
        return worst

    def enforce_sink(self, sink: str, arg_span_ids: Iterable[str]) -> None:
        # Meet-only across composition: sink inherits worst reachable trust.
        worst = Trust.TRUSTED
        for sid in arg_span_ids:
            worst = min(worst, self._lineage_min(sid, set()))
        if worst < Trust.TRUSTED:
            offenders = [s for s in arg_span_ids
                         if self._lineage_min(s, set()) < Trust.TRUSTED]
            raise TaintLineageError(
                f"sink {sink!r} blocked: lineage reaches untrusted span(s) {offenders}"
            )


def run_turn(tracker: TaintTracker) -> None:
    tracker.register_source("S1", Trust.UNTRUSTED)          # fetch_url result
    tracker.derive("S2", Trust.TRUSTED, quoted=["S1"])      # scratchpad quote
    # Classifier miss on S1 does not matter: S2 inherits UNTRUSTED.
    tracker.enforce_sink("send_email", arg_span_ids=["S2"])  # raises


if __name__ == "__main__":
    run_turn(TaintTracker())
