# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-tainted-tool-arguments-at-the-execution-boundary-rather-than-sanitize-them-in-context.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-tainted-tool-arguments-at-the-execution-boundary-rather-than-sanitize-them-in-context.warrant.json
# Markdown SHA-256:   af00d0d0f7cca3abe3ab0b98f05fd77c5a84c287962ec5bc957282150e80c475
# Code AST SHA-256:   728e2d942938d740d3257121bc8508fb11dc349de3ff18cd3dfde6beff6d3819
# Verified Classes:   TaintedArgumentRejected, Warrant, ToolCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintedArgumentRejected(RuntimeError):
    """Raised at the execution boundary when a tainted argument field
    is not covered by a trusted warrant. This is a refusal, not a
    sanitization failure: the call must not execute."""

    def __init__(self, field_name: str, taint_sources: frozenset[str]):
        self.field_name = field_name
        self.taint_sources = taint_sources
        super().__init__(
            f"argument field {field_name!r} carries taint {sorted(taint_sources)} "
            f"with no covering warrant; quarantine and re-derive from a trusted source"
        )


@dataclass(frozen=True)
class Warrant:
    """A trusted principal's assertion that a named field may carry a
    value of a permitted class, despite taint. Signed out-of-band."""
    field_name: str
    permitted_class: str
    signer: str


@dataclass
class ToolCall:
    tool: str
    args: dict[str, str]
    # taint is a lattice: source -> set of fields derived from it.
    # Derivation only adds; nothing in-context removes.
    taint: dict[str, set[str]] = field(default_factory=dict)

    def taint_of(self, field_name: str) -> frozenset[str]:
        return frozenset(src for src, fs in self.taint.items() if field_name in fs)


def _content_validates(value: str, allowed_class: str) -> bool:
    # Content check is NECESSARY but NOT SUFFICIENT. It must never
    # short-circuit the taint check below.
    if allowed_class == "account_id":
        return len(value) == 7 and value[:2].isalpha() and value[2] == "-" and value[3:].isdigit()
    return False


def execute_tool_call(
    call: ToolCall,
    warrants: list[Warrant],
    field_classes: dict[str, str],
) -> str:
    """Boundary enforcement. Order is invariant:
       check_taint -> validate_content -> execute.
    A passing content check is evidence about content, not provenance."""
    for name, value in call.args.items():
        sources = call.taint_of(name)
        covered = any(
            w.field_name == name and w.signer == "trusted-principal"
            for w in warrants
        )
        if sources and not covered:
            # Quarantine: do not sanitize, do not execute.
            raise TaintedArgumentRejected(name, sources)
        # Only now, after taint is discharged, is content relevant.
        if not _content_validates(value, field_classes.get(name, "")):
            raise ValueError(f"content invalid for {name!r}: {value!r}")
    return f"executed {call.tool} with {sorted(call.args)}"


# --- Replay of the observed failure ---
call = ToolCall(
    tool="lookup_account",
    args={"account_id": "AC-4471"},
    # footer_field was derived from ticket S_t; label follows the
    # derived value, not just the raw span.
    taint={"S_t": {"account_id"}},
)

try:
    execute_tool_call(call, warrants=[], field_classes={"account_id": "account_id"})
except TaintedArgumentRejected as e:
    # Correct outcome: cross-tenant read blocked despite valid content.
    assert "S_t" in e.taint_sources
    print(f"quarantined: {e}")

# With a warrant, the same call executes; content still validated.
warrants = [Warrant(field_name="account_id", permitted_class="account_id", signer="trusted-principal")]
print(execute_tool_call(call, warrants, {"account_id": "account_id"}))
