# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-a-quarantined-tool-invocation-s-argument-graph-rather-than-a-single-poisoned-field.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-a-quarantined-tool-invocation-s-argument-graph-rather-than-a-single-poisoned-field.warrant.json
# Markdown SHA-256:   afed4b847c75dff32dfb1bd607f6f4b943196989d86444bc6231a77419329976
# Code AST SHA-256:   74709f2d4d4846de2529e87f5cb695faeebf0c71707fc972734a2fea89227539
# Verified Classes:   TaintLaunderingError, Label, Node
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Callable

class TaintLaunderingError(RuntimeError):
    """Raised when a tool invocation's argument derivation closure
    reaches an untrusted source without passing an audited declassifier."""

@dataclass(frozen=True)
class Label:
    sources: frozenset[str] = frozenset()
    def tainted(self) -> bool:
        return bool(self.sources)
    def merge(self, other: "Label") -> "Label":
        return Label(self.sources | other.sources)

# Registry: tool_name -> ("propagating" | "non_interfering" | "declassifier")
# Unregistered tools default to propagating (fail-closed).
TRANSFORMS: dict[str, str] = {
    "text.normalize": "propagating",
    "json.dumps": "propagating",
    "int": "propagating",
    "len": "non_interfering",
    "schema.extract_allowlisted": "declassifier",
}

@dataclass
class Node:
    value: Any
    label: Label
    parents: list["Node"] = field(default_factory=list)

def apply_transform(name: str, inputs: list[Node], fn: Callable[..., Any]) -> Node:
    kind = TRANSFORMS.get(name, "propagating")  # fail-closed default
    if kind == "non_interfering":
        out_label = Label()
    elif kind == "declassifier":
        out_label = Label()  # audited: output is allowlist-constrained
    else:  # propagating
        out_label = Label()
        for n in inputs:
            out_label = out_label.merge(n.label)
    return Node(fn(*[n.value for n in inputs]), out_label, parents=list(inputs))

def check_sink(tool: str, args: list[Node]) -> None:
    """Walk the transitive derivation closure of every argument.
    Quarantine if any reachable node is tainted."""
    seen: set[int] = set()
    stack = list(args)
    while stack:
        node = stack.pop()
        if id(node) in seen:
            continue
        seen.add(id(node))
        if node.label.tainted():
            raise TaintLaunderingError(
                f"sink {tool!r} reached via tainted derivation "
                f"{sorted(node.label.sources)} at value {node.value!r}"
            )
        stack.extend(node.parents)

def guarded_call(tool: str, args: list[Node], fn: Callable[..., Any]) -> Any:
    check_sink(tool, args)
    return fn(*[n.value for n in args])

# --- trace: direct path is blocked, laundering path must also be blocked ---
page = Node("DROP TABLE users; --", Label(frozenset({"web:untrusted"})))

norm = apply_transform("text.normalize", [page], lambda s: s.strip())
try:
    guarded_call("db.execute", [norm], lambda q: ("executed", q))
    raise AssertionError("laundering path escaped quarantine")  # must not reach
except TaintLaunderingError:
    pass  # correct: closure still tainted

# numeric coercion must not erase the label
num = apply_transform("int", [Node("3", Label(frozenset({"web:untrusted"})))], int)
try:
    guarded_call("db.query", [num], lambda n: ("queried", n))
    raise AssertionError("type-erasure laundering escaped quarantine")
except TaintLaunderingError:
    pass

# audited declassifier is the only path that clears taint
clean = apply_transform(
    "schema.extract_allowlisted",
    [page],
    lambda s: {"table": "users"},  # allowlist-constrained output
)
guarded_call("db.execute", [clean], lambda q: ("executed", q))
