# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-tainted-context-before-a-tool-invocation-rather-than-sanitize-it-in-place.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-tainted-context-before-a-tool-invocation-rather-than-sanitize-it-in-place.warrant.json
# Markdown SHA-256:   451268fcdfcb1b7be73e67775e6fc8f9d99289516f00415284979db5df20e871
# Code AST SHA-256:   cdf98710adeb485cddc2c8be06c0694c05f7eb2b1835bbfdabf69abe31cbf0d7
# Verified Classes:   TaintedArgumentDispatch, Span, PendingCall, Context
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintedArgumentDispatch(RuntimeError):
    """Raised when a tool call's argument derivation intersects the active taint set."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    provenance_root: str          # e.g. "user.task", "fs.read:config", "http.fetch:changelog"
    trusted: bool


@dataclass
class PendingCall:
    tool: str
    # argument name -> set of span_ids that contributed to its value
    arg_derivations: dict[str, FrozenSet[str]]
    selection_spans: FrozenSet[str]   # spans that influenced *which* tool was chosen


@dataclass
class Context:
    spans: dict[str, Span] = field(default_factory=dict)

    def taint_set(self) -> FrozenSet[str]:
        return frozenset(sid for sid, s in self.spans.items() if not s.trusted)


def dispatch(call: PendingCall, ctx: Context) -> None:
    taint = ctx.taint_set()

    # Tool selection must be untainted: if the tainted span influenced *which*
    # tool was chosen, sanitization cannot repair selection.
    if call.selection_spans & taint:
        raise TaintedArgumentDispatch(
            f"tool selection for {call.tool!r} derived from tainted spans "
            f"{sorted(call.selection_spans & taint)}; quarantine required, "
            f"sanitize-in-place is unsound for selection"
        )

    # Any argument whose derivation set intersects taint is already contaminated;
    # stripping the source text does not recompute the materialized value.
    for arg, deriv in call.arg_derivations.items():
        hit = deriv & taint
        if hit:
            raise TaintedArgumentDispatch(
                f"argument {arg!r} of {call.tool!r} has tainted ancestor(s) "
                f"{sorted(hit)}; must quarantine and re-derive from clean root, "
                f"not sanitize in place"
            )

    # Reached only when derivation and selection are provenance-disjoint from taint.
    _execute(call)


def _execute(call: PendingCall) -> None:
    ...  # side-effecting dispatch, reached only past the invariant


# Reproduction of the observed failure:
ctx = Context(spans={
    "s1": Span("s1", "user.task", trusted=True),
    "s2": Span("s2", "fs.read:config", trusted=True),
    "s3": Span("s3", "http.fetch:changelog", trusted=False),   # injected path
})
call = PendingCall(
    tool="fs.write",
    arg_derivations={"path": frozenset({"s3"}), "body": frozenset({"s2"})},
    selection_spans=frozenset({"s1"}),
)
dispatch(call, ctx)   # raises TaintedArgumentDispatch -> quarantine, do not sanitize
