# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-retrieval-before-re-planning-not-after-a-boundary-invariant-for-indirect-prompt-injection-through-retrieved.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-retrieval-before-re-planning-not-after-a-boundary-invariant-for-indirect-prompt-injection-through-retrieved.warrant.json
# Markdown SHA-256:   d7a8ab3026e4ad22a4ae5719cf96290ae3db397261d0ce9e48fa3d5f06149bb1
# Code AST SHA-256:   10226a8c343ae2768d623c6247af386e48129e0a3a483640a633432a24c29e5f
# Verified Classes:   TaintBoundaryViolation, Span, CandidateAction
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintBoundaryViolation(RuntimeError):
    """Raised when a candidate action is taint-reachable and lacks a clearing justification."""


@dataclass
class Span:
    source_id: str
    start: int
    end: int
    tainted: bool = True


@dataclass
class CandidateAction:
    name: str
    arguments: dict
    provenance: list[Span] = field(default_factory=list)
    justification: Optional[str] = None


def taint_reachable(action: CandidateAction) -> bool:
    return any(s.tainted for s in action.provenance)


def admit_to_plan(action: CandidateAction) -> None:
    """Re-planning boundary: admit only if not taint-reachable or explicitly justified."""
    if taint_reachable(action) and not action.justification:
        chain = " -> ".join(f"{s.source_id}[{s.start}:{s.end}]" for s in action.provenance)
        raise TaintBoundaryViolation(
            f"action {action.name!r} is taint-reachable via {chain} and has no "
            f"clearing justification; quarantine before re-planning, do not dispatch"
        )
    # action is admitted to the executable queue only past this point


def dispatch(action: CandidateAction) -> None:
    if taint_reachable(action) and not action.justification:
        raise TaintBoundaryViolation(
            f"refusing to dispatch {action.name!r}: taint check must fire at re-planning, "
            f"not at execution"
        )
    # ... execute ...


# Observed failure trace, reproduced against the guardrail:
chunk2_span = Span(source_id="chunk_2", start=41, end=118, tainted=True)
fetch = CandidateAction(
    name="fetch_url",
    arguments={"url": "https://internal.example/renewal"},
    provenance=[chunk2_span],
)
admit_to_plan(fetch)  # raises TaintBoundaryViolation; plan halts, provenance logged
