# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-sever-a-tainted-tool-call-subgraph-when-provenance-labels-are-laundered-through-a-legitimate-summarizer-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-sever-a-tainted-tool-call-subgraph-when-provenance-labels-are-laundered-through-a-legitimate-summarizer-hop.warrant.json
# Markdown SHA-256:   c6257d402945c4973fb84e7c7cb3d35f68630bf173098bf2757b77d1d52b3a47
# Code AST SHA-256:   18bb9be67bc21f3f8b3447591e70bcbaffb42619532a2d5c8f3c05d61b45251a
# Verified Classes:   TaintLaunderingError, CallNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a transformation node attempts to clear taint without a
    dischargeable injection-invariance proof, or when a privileged sink is
    invoked with a non-empty tainted-ancestor set and no authorizing policy."""
    pass


@dataclass
class CallNode:
    node_id: str
    tool: str
    tainted: bool                      # ingress taint of this node's output
    injection_invariant: bool = False  # may this node clear taint?
    parents: list = field(default_factory=list)
    arg_is_freetext: bool = True       # does output carry unbounded strings?


PRIVILEGED_SINKS = {"write_file", "read_file", "exec_shell", "http_post"}


def resolve_taint(node: CallNode, dag: dict) -> bool:
    """Taint is reachability over the call DAG, not a per-value label.
    A node is tainted if it is tainted at ingress OR any ancestor is tainted
    AND the node did not discharge an injection-invariance proof."""
    if node.tainted:
        return True
    for pid in node.parents:
        parent = dag.get(pid)
        if parent is None:
            raise TaintLaunderingError(
                f"node {node.node_id}: parent {pid} missing from DAG; "
                f"cannot establish ancestor taint set"
            )
        if resolve_taint(parent, dag):
            # Parent is tainted. Can this node clear it?
            if node.injection_invariant and not node.arg_is_freetext:
                continue  # schema-constrained, proven-invariant: legal clear
            return True
    return False


def gate_sink(node: CallNode, dag: dict, authorized_paths: set) -> None:
    if node.tool not in PRIVILEGED_SINKS:
        return
    if not resolve_taint(node, dag):
        return
    path_key = tuple(sorted(node.parents)) + (node.tool,)
    if path_key in authorized_paths:
        return
    raise TaintLaunderingError(
        f"privileged sink {node.tool} (node {node.node_id}) has tainted "
        f"ancestors and no authorizing policy for path {path_key}; "
        f"refusing to execute"
    )


# Reproduce the observed defect: summarize clears taint it cannot prove clean.
dag = {}
fetch = CallNode("n1", "fetch", tainted=True)
dag["n1"] = fetch
summ = CallNode("n2", "summarize", tainted=False,
                injection_invariant=True,   # WRONG: LLM node, freetext output
                arg_is_freetext=True,
                parents=["n1"])
dag["n2"] = summ
extract = CallNode("n3", "extract_entities", tainted=False,
                   parents=["n2"])
dag["n3"] = extract
sink = CallNode("n4", "write_file", tainted=False, parents=["n3"])
dag["n4"] = sink

try:
    gate_sink(sink, dag, authorized_paths=set())
except TaintLaunderingError as e:
    print(f"BLOCKED (correct): {e}")
    # Under the defect, resolve_taint(n2) would have returned False because
    # injection_invariant=True was trusted despite freetext output; the
    # gate would have fired the sink. The fix is to refuse the clear.
