# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tainted-provenance-from-laundering-through-tool-result-boundaries-in-agent-context.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tainted-provenance-from-laundering-through-tool-result-boundaries-in-agent-context.warrant.json
# Markdown SHA-256:   e52060df4807d7f2fea1d9d7031e8047fce87e8b2907b10c0ea82c5221215e0b
# Code AST SHA-256:   467ce40ef168eb6fa282c47121c0900d8316cc908dff85040f83e8a852eec1a2
# Verified Classes:   TaintLaunderingError, Segment, TaintTracker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Set

class TaintLaunderingError(RuntimeError):
    """Raised when a derived segment's taint set does not cover its inputs' taint."""
    pass

@dataclass
class Segment:
    seg_id: str
    origin: str
    taint_set: Set[str] = field(default_factory=set)
    input_ids: Set[str] = field(default_factory=set)

class TaintTracker:
    def __init__(self):
        self.segments: dict[str, Segment] = {}

    def ingest(self, seg: Segment) -> None:
        self.segments[seg.seg_id] = seg

    def derive(self, out_id: str, tool_origin: str, input_ids: Set[str],
               tool_is_semantic: bool) -> Segment:
        # Join taint over all transitive inputs.
        joined: Set[str] = set()
        for iid in input_ids:
            if iid not in self.segments:
                raise TaintLaunderingError(
                    f"derive({out_id}): input {iid} missing from tracker; "
                    f"taint lineage broken, cannot compute join"
                )
            joined |= self.segments[iid].taint_set
        if tool_is_semantic:
            # Semantic tool carries input content into output: inherit taint.
            taint = set(joined)
        else:
            # Closed-schema tool: output domain cannot carry instructions.
            taint = set()
        out = Segment(seg_id=out_id, origin=tool_origin,
                      taint_set=taint, input_ids=set(input_ids))
        self.segments[out_id] = out
        return out

    def gate(self, seg_id: str, forbidden_origins: Set[str]) -> None:
        seg = self.segments[seg_id]
        leaked = seg.taint_set & forbidden_origins
        if leaked:
            raise TaintLaunderingError(
                f"gate({seg_id}): segment carries forbidden taint {leaked} "
                f"via origin {seg.origin}; action blocked"
            )

    def evict(self, seg_id: str) -> None:
        # Refuse eviction if any live segment depends on this one's taint.
        for other in self.segments.values():
            if other.seg_id != seg_id and seg_id in other.input_ids:
                raise TaintLaunderingError(
                    f"evict({seg_id}): live segment {other.seg_id} depends on it; "
                    f"fold taint before eviction"
                )
        del self.segments[seg_id]


def run_pipeline() -> None:
    t = TaintTracker()
    t.ingest(Segment("chunk1", "web", taint_set={"untrusted"}))
    # Summarizer is semantic: must inherit input taint.
    summary = t.derive("sum1", "tool:summarize", {"chunk1"}, tool_is_semantic=True)
    if "untrusted" not in summary.taint_set:
        raise TaintLaunderingError("sum1 laundered taint through semantic tool")
    t.gate("sum1", forbidden_origins={"untrusted"})  # raises, as required
