# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-labels-across-tool-call-boundaries-to-prevent-taint-laundering-in-prompt-injection-defense.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-labels-across-tool-call-boundaries-to-prevent-taint-laundering-in-prompt-injection-defense.warrant.json
# Markdown SHA-256:   438afd0df80bcedb7f5694e2a5a888e0161eaa1430c1c35b61a946060dbabeaf
# Code AST SHA-256:   d177ebeb69c79af7b847ab49be0581255fadab05bcd2fa8a54bd0008acba24d3
# Verified Classes:   TaintLaunderingError, Provenance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a tool result would re-enter context with provenance
    that under-reports the taint of the arguments that produced it."""
    pass


@dataclass(frozen=True)
class Provenance:
    source: str
    tainted: bool
    ancestors: frozenset = field(default_factory=frozenset)

    def join(self, other: "Provenance") -> "Provenance":
        return Provenance(
            source=f"{self.source}+{other.source}",
            tainted=self.tainted or other.tainted,
            ancestors=self.ancestors | other.ancestors | {self.source, other.source},
        )


# A tool declares which argument positions it provably sanitizes.
# Empty set == taint-transparent: result inherits full argument taint.
TOOL_SANITIZATION_CONTRACT = {
    "search_knowledge_base": frozenset(),   # query string shapes results -> NOT clearing
    "calculator": frozenset({"expr"}),      # computes, does not echo -> clearing
    "submit_assessment": frozenset(),       # privileged side effect -> never clearing
}


def execute_tool_call(tool_name: str, args: dict, arg_provenance: dict) -> Provenance:
    if tool_name not in TOOL_SANITIZATION_CONTRACT:
        raise TaintLaunderingError(
            f"tool {tool_name!r} has no sanitization contract; "
            f"cannot compute result provenance safely"
        )
    sanitized = TOOL_SANITIZATION_CONTRACT[tool_name]

    # Join taint over every model-generated argument position.
    joined = Provenance(source="tool_input", tainted=False)
    for pos, prov in arg_provenance.items():
        if pos not in sanitized:
            joined = joined.join(prov)

    # Result inherits argument taint unless the tool is certified clearing
    # for ALL contributing positions. Partial clearing still leaks.
    if joined.tainted and not sanitized.issuperset(arg_provenance.keys()):
        # Do NOT silently reset to source=tool_name,trust=trusted.
        # That reset is exactly the laundering path.
        result = Provenance(
            source=f"{tool_name}:result",
            tainted=True,
            ancestors=joined.ancestors | {tool_name},
        )
        return result

    return Provenance(source=f"{tool_name}:result", tainted=False)


def assert_action_permitted(action: str, action_provenance: Provenance) -> None:
    if action_provenance.tainted:
        raise TaintLaunderingError(
            f"refusing privileged action {action!r}: provenance-reachable "
            f"taint from {sorted(action_provenance.ancestors)}"
        )


# --- Failure trace reproduction ---
ticket_seg = Provenance(source="ticket_db", tainted=True)
kb_query_prov = ticket_seg  # query string constructed from tainted ticket

kb_result = execute_tool_call(
    "search_knowledge_base",
    args={"query": "severity classification for escalated ops tickets"},
    arg_provenance={"query": kb_query_prov},
)
# kb_result.tainted is True -> the two-hop path is visible.

try:
    assert_action_permitted("submit_assessment", kb_result)
except TaintLaunderingError as e:
    print(f"BLOCKED (correctly): {e}")
