# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-tainted-context-before-it-crosses-a-tool-boundary-and-how-does-taint-laundering-through-retri.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-tainted-context-before-it-crosses-a-tool-boundary-and-how-does-taint-laundering-through-retri.warrant.json
# Markdown SHA-256:   8ee95ecc3d7ea112df2bced538bc33ca092e5188c58dbf0c6911fb7dd5d26b25
# Code AST SHA-256:   b8f35f765735d8fcfa60c230a58c6706c44ef8b2261d3f9b43e6718d9981ca24
# Verified Classes:   TaintLaunderingError, Segment, ProvenanceStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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

class TaintLaunderingError(RuntimeError):
    """Raised when a segment with external-tainted ancestry reaches a privileged sink."""
    pass

@dataclass
class Segment:
    seg_id: str
    content: str
    taint: str  # "none" | "external" | "derived_external"
    derived_from: Set[str] = field(default_factory=set)

class ProvenanceStore:
    def __init__(self) -> None:
        self._segs: Dict[str, Segment] = {}

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

    def transitive_taint(self, seg_id: str, _seen: Set[str] = None) -> str:
        _seen = _seen or set()
        if seg_id in _seen:
            return "none"
        _seen.add(seg_id)
        seg = self._segs[seg_id]
        if seg.taint == "external":
            return "external"
        for parent in seg.derived_from:
            if self.transitive_taint(parent, _seen) == "external":
                return "external"
        return seg.taint

    def guard_privileged_sink(self, seg_id: str, sink: str) -> None:
        taint = self.transitive_taint(seg_id)
        if taint == "external":
            raise TaintLaunderingError(
                f"segment {seg_id} has external-tainted ancestry; "
                f"refusing to pass to privileged sink '{sink}' without sanitization"
            )

def persist_model_output(store: ProvenanceStore, out_id: str, content: str,
                         context_ids: List[str]) -> Segment:
    # Conservative over-approximation: any output produced while tainted
    # segments were in context is derived_external unless proven otherwise.
    tainted = any(store.transitive_taint(c) == "external" for c in context_ids)
    seg = Segment(
        seg_id=out_id,
        content=content,
        taint="derived_external" if tainted else "none",
        derived_from=set(context_ids),
    )
    store.add(seg)
    return seg

def run_shell_with_arg(store: ProvenanceStore, arg_seg_id: str) -> None:
    store.guard_privileged_sink(arg_seg_id, sink="shell_exec")
    # ... execute ...

# Reproduces the laundering trace:
store = ProvenanceStore()
store.add(Segment("web1", "page with ADMIN_OVERRIDE=1", taint="external"))
note = persist_model_output(store, "note1", "ADMIN_OVERRIDE=1", context_ids=["web1"])
# note.taint == "derived_external"; transitive_taint == "external"
run_shell_with_arg(store, "note1")  # raises TaintLaunderingError
