# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-sever-a-tainted-tool-call-subgraph-before-provenance-labels-are-laundered-by-re-summarization.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-sever-a-tainted-tool-call-subgraph-before-provenance-labels-are-laundered-by-re-summarization.warrant.json
# Markdown SHA-256:   c066dd90bd45738f1a79309a93ac88a2067d6cf0bdc604dfacac4693a55c9128
# Code AST SHA-256:   50683d9245d36ff12d533dbb6d83b82605e141f6a4f6213f90ce5473f9523b59
# Verified Classes:   TaintLaunderingError, ProvenanceNode, ProvenanceGraph
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a generation node would reset provenance on tainted inputs."""
    pass


@dataclass(frozen=True)
class ProvenanceNode:
    node_id: str
    label: str                      # e.g. "untrusted:web", "trusted:model"
    inputs: FrozenSet[str] = frozenset()  # ids of causal input nodes


class ProvenanceGraph:
    def __init__(self) -> None:
        self._nodes: dict[str, ProvenanceNode] = {}

    def add(self, node: ProvenanceNode) -> None:
        self._nodes[node.node_id] = node

    def effective_taint(self, node_id: str) -> FrozenSet[str]:
        """Join of taint labels over the full causal input DAG."""
        node = self._nodes[node_id]
        taint = set()
        if node.label.startswith("untrusted"):
            taint.add(node.label)
        for parent in node.inputs:
            taint |= self.effective_taint(parent)
        return frozenset(taint)

    def register_generation(self, node_id: str, input_ids: FrozenSet[str]) -> ProvenanceNode:
        """Register a model generation node. Its label is trusted:model ONLY
        if its entire causal input set is trusted; otherwise it inherits taint
        and must NOT be relabeled as trusted:model."""
        joined = set()
        for pid in input_ids:
            joined |= self.effective_taint(pid)
        label = "trusted:model" if not joined else "untrusted-derived:model"
        node = ProvenanceNode(node_id=node_id, label=label, inputs=input_ids)
        self.add(node)
        return node


def authorize_write_tool(graph: ProvenanceGraph, arg_node_id: str) -> None:
    taint = graph.effective_taint(arg_node_id)
    if taint:
        raise TaintLaunderingError(
            f"write-side tool argument {arg_node_id!r} carries effective taint "
            f"{sorted(taint)}; generation node did not sever the tainted subgraph "
            f"and provenance was laundered. Escalate to confirmation or route "
            f"through deterministic extraction."
        )
