# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-subgraph-rather-than-re-sanitize-it-taint-join-ambiguity-across-multi-hop-tool-invocation-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-subgraph-rather-than-re-sanitize-it-taint-join-ambiguity-across-multi-hop-tool-invocation-graphs.warrant.json
# Markdown SHA-256:   e5adb32a1deeaf129d461fb83c432bc4fafca5da9a9c1e74d241238c42f0f55c
# Code AST SHA-256:   b75800069b44989e970ac7e447c9a21903f52e24d3d7797f1c6d276464e7e124
# Verified Classes:   TaintQuarantine, TaintLabel, SanitizerContract, Invocation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintQuarantine(RuntimeError):
    """Raised when a tainted path reaches a side-effecting sink argument
    that is not pinned by a grammar-level sanitizer contract."""


@dataclass(frozen=True)
class TaintLabel:
    source_id: str
    cleared_by: str | None = None  # sanitizer id, or None if still tainted


@dataclass(frozen=True)
class SanitizerContract:
    sanitizer_id: str
    # Argument positions this sanitizer is proven to pin for the given sink.
    # A sink argument is "pinned" only if the sanitizer constrains it to a
    # model-independent allowlist / enum / schema, not by string stripping.
    pinned_args: frozenset[str]


@dataclass
class Invocation:
    hop: int
    tool: str
    sanitizer: SanitizerContract | None
    inputs: list[TaintLabel] = field(default_factory=list)


SIDE_EFFECTING_SINKS = {
    "create_ticket": {"assignee", "body"},
    "send_email": {"to", "body"},
    "write_file": {"path", "content"},
    "http_post": {"url", "body"},
    "execute_sql": {"query"},
}


def enforce_taint_boundary(
    path: Iterable[Invocation],
    sink: str,
    sink_args: Iterable[str],
) -> None:
    """Walk a taint path. Quarantine if any tainted input reaches an
    unpinned side-effecting sink argument. Re-sanitization is refused
    when the subgraph depth from source to sink is >= 2 and the sink has
    an attacker-relevant degree of freedom."""
    hops = list(path)
    sink_args = set(sink_args)
    if sink not in SIDE_EFFECTING_SINKS:
        return  # read-only sink: model stays in the loop, re-sanitize is fine

    free_args = SIDE_EFFECTING_SINKS[sink] & sink_args
    if not free_args:
        return  # all sink args pinned by construction

    # Collect taint labels that survive to the sink hop.
    surviving: list[TaintLabel] = []
    for inv in hops:
        for lbl in inv.inputs:
            if lbl.cleared_by is None:
                surviving.append(lbl)
                continue
            # A label cleared by a sanitizer is only cleared for the args
            # that sanitizer is proven to pin. Otherwise it is still live.
            contract = inv.sanitizer
            if contract is None or contract.sanitizer_id != lbl.cleared_by:
                surviving.append(lbl)
                continue
            if not (contract.pinned_args >= free_args):
                surviving.append(TaintLabel(source_id=lbl.source_id))

    if not surviving:
        return

    depth = max(inv.hop for inv in hops) - min(inv.hop for inv in hops)
    if depth >= 2:
        # Multi-hop: string-level sanitization is unsound for free-form
        # sink args. Must quarantine, not re-sanitize.
        raise TaintQuarantine(
            f"sink={sink!r} args={sorted(free_args)!r} reached by tainted "
            f"source(s)={[s.source_id for s in surviving]!r} at depth={depth}. "
            f"Re-sanitization refused; halt and re-plan from last clean "
            f"checkpoint."
        )
    # Depth 1: model remains in the loop; re-sanitize is acceptable.
    return


# --- Example: the vendor-risk ticket, depth 2, attacker-controlled assignee ---
path = [
    Invocation(hop=1, tool="fetch_url", sanitizer=None,
               inputs=[TaintLabel(source_id="https://vendor.example/risk")]),
    Invocation(hop=2, tool="extract_text",
               sanitizer=SanitizerContract(
                   sanitizer_id="strip-injection-markers",
                   pinned_args=frozenset()),  # string-level: pins nothing
               inputs=[TaintLabel(source_id="https://vendor.example/risk")]),
    Invocation(hop=3, tool="create_ticket", sanitizer=None,
               inputs=[TaintLabel(source_id="https://vendor.example/risk",
                                  cleared_by="strip-injection-markers")]),
]

try:
    enforce_taint_boundary(path, sink="create_ticket",
                           sink_args=["title", "body", "assignee"])
except TaintQuarantine as e:
    # Expected: quarantine fires; the ticket is not filed.
    print("QUARANTINE:", e)
