# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-result-because-taint-from-an-injected-context-segment-survived-a-laundering-step.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-result-because-taint-from-an-injected-context-segment-survived-a-laundering-step.warrant.json
# Markdown SHA-256:   691fa6e39205878d129d26d0c6872e5c3442105bd4f33083494f3fb8e5d9ecdf
# Code AST SHA-256:   12b40cccbc726265404c68508f0840cc371180a80f7abd0b88f1a195d930dd0d
# Verified Classes:   TaintLaunderingError, Node, DerivationGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a tainted ancestor reaches an instruction-bearing sink
    argument without crossing a valid, sink-scoped declassification edge."""
    pass


@dataclass
class Node:
    id: str
    taint: int                      # 1 if this node itself is untrusted-origin
    derived_from: list[str] = field(default_factory=list)
    declassified_for: set[str] = field(default_factory=set)  # sink schemas


class DerivationGraph:
    def __init__(self) -> None:
        self.nodes: dict[str, Node] = {}

    def add(self, node: Node) -> None:
        self.nodes[node.id] = node

    def tainted_ancestors(self, node_id: str, seen: Optional[set[str]] = None) -> set[str]:
        seen = seen or set()
        if node_id in seen:
            return set()
        seen.add(node_id)
        node = self.nodes[node_id]
        result = {node_id} if node.taint else set()
        for parent in node.derived_from:
            result |= self.tainted_ancestors(parent, seen)
        return result

    def check_sink(self, arg_node_id: str, sink_schema: str, instruction_bearing: bool) -> None:
        node = self.nodes[arg_node_id]
        tainted = self.tainted_ancestors(arg_node_id)
        if not tainted:
            return
        # Declassification only counts if scoped to this exact sink schema.
        if sink_schema in node.declassified_for:
            return
        if instruction_bearing:
            raise TaintLaunderingError(
                f"sink arg {arg_node_id} (schema={sink_schema}) reachable from "
                f"tainted ancestors {sorted(tainted)}; laundering blocked"
            )
        # data-bearing: allowed only if value matches server-side allowlist
        raise TaintLaunderingError(
            f"data-bearing arg {arg_node_id} tainted via {sorted(tainted)}; "
            f"require allowlist match before use"
        )


def file_ticket(graph: DerivationGraph, priority_node: str, assignee_node: str) -> None:
    # priority and assignee are instruction-bearing: they redirect future agent action.
    graph.check_sink(priority_node, sink_schema="file_ticket.priority", instruction_bearing=True)
    graph.check_sink(assignee_node, sink_schema="file_ticket.assignee", instruction_bearing=True)
    # ... actual side effect here


# Reproduction of the observed escape:
g = DerivationGraph()
g.add(Node(id="seg_02", taint=1))                                   # fetched page, injected
g.add(Node(id="summ_out", taint=0, derived_from=["seg_02"]))        # summarizer "cleared" taint
g.add(Node(id="mem_facts", taint=0, derived_from=["summ_out"]))     # memory write
g.add(Node(id="facts_read", taint=0, derived_from=["mem_facts"]))   # memory read
g.add(Node(id="priority", taint=0, derived_from=["facts_read"]))    # extracted field
g.add(Node(id="assignee", taint=0, derived_from=["facts_read"]))    # extracted field

file_ticket(g, priority_node="priority", assignee_node="assignee")  # raises
