# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-leak-tainted-arguments-through-the-sanitizer-return-path-when-a-tool-call-is-re-derived-after-a-quarantine-rejection.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-leak-tainted-arguments-through-the-sanitizer-return-path-when-a-tool-call-is-re-derived-after-a-quarantine-rejection.warrant.json
# Markdown SHA-256:   64b9f952705a08a2fa34760768943ea9e5bbc15202dd5c7b361c3b0290abc410
# Code AST SHA-256:   cb7e1371b8b390b8977ad5dd0fa0e40c9af486b369f3a85d9b4d02211857bd02
# Verified Classes:   TaintedArgumentError, Span, Token, ToolCall, ProvenanceLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintedArgumentError(RuntimeError):
    """Raised when a tool-call argument descends from a span that was tainted
    at the time the argument's tokens were generated, even if the span has
    since been scrubbed from the context window."""


@dataclass(frozen=True)
class Span:
    span_id: str
    tainted_at_generation: bool


@dataclass
class Token:
    text: str
    ancestry: FrozenSet[str] = field(default_factory=frozenset)


@dataclass
class ToolCall:
    name: str
    arguments: dict  # arg name -> list[Token]


class ProvenanceLedger:
    """Monotonic taint tracking: a span's taint status is recorded at the
    moment tokens were generated under it and is never cleared retroactively."""

    def __init__(self) -> None:
        self._taint_at_generation: dict[str, bool] = {}

    def record(self, span: Span) -> None:
        # First observation wins; a later "untaint" cannot rewrite history.
        self._taint_at_generation.setdefault(
            span.span_id, span.tainted_at_generation
        )

    def was_tainted(self, span_id: str) -> bool:
        return self._taint_at_generation.get(span_id, False)


def admit_tool_call(call: ToolCall, ledger: ProvenanceLedger) -> None:
    """Reject the call if ANY argument token has a tainted ancestor.

    This is the guardrail: it runs on the assembled call, after any
    re-derivation, and it refuses rather than re-prompts. Re-prompting
    is what created the leak in the first place.
    """
    violations: list[str] = []
    for arg_name, tokens in call.arguments.items():
        for tok in tokens:
            tainted_ancestors = {
                sid for sid in tok.ancestry if ledger.was_tainted(sid)
            }
            if tainted_ancestors:
                violations.append(
                    f"{call.name}.{arg_name} token {tok.text!r} descends "
                    f"from tainted span(s) {sorted(tainted_ancestors)}"
                )
                break  # one violation per argument is enough to reject
    if violations:
        raise TaintedArgumentError(
            "refusing tool call; argument provenance violates quarantine "
            "invariant: " + "; ".join(violations)
        )


def demo() -> None:
    ledger = ProvenanceLedger()
    # The injected span was tainted when the model first read it.
    ledger.record(Span(span_id="q7", tainted_at_generation=True))

    # Model's prior reasoning paraphrased the account number under q7's
    # influence; the sanitizer scrubbed the span but not these tokens.
    leaked_account = [Token(text="OPS-7731", ancestry=frozenset({"q7"}))]
    clean_amount = [Token(text="0.0", ancestry=frozenset({"user_goal"}))]
    ledger.record(Span(span_id="user_goal", tainted_at_generation=False))

    call = ToolCall(
        name="transfer_funds",
        arguments={"account": leaked_account, "amount": clean_amount},
    )
    admit_tool_call(call, ledger)  # raises TaintedArgumentError


if __name__ == "__main__":
    demo()
