# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-summarization-in-agent-tool-invocation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-summarization-in-agent-tool-invocation-chains.warrant.json
# Markdown SHA-256:   4ba8aed0e6a83023469bc5b85c55632bbe80ca8663b03c8ea854693c147b0b59
# Code AST SHA-256:   4725db12ad2e201cf82e2818f9c2cc955d1fcaf0ce2df2785694b15fdfed20d4
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a sink argument's derivation graph contains an LLM node
    whose context set was not captured, making taint-closure unprovable."""
    pass


def check_sink_derivation(sink_arg, derivation_graph, context_store):
    """
    Enforce derivation-closure before allowing a tainted-capable sink call.

    sink_arg: value being passed to an external sink
    derivation_graph: dict mapping value_id -> list of (parent_id, edge_type)
        edge_type in {"derived", "authored"}
    context_store: dict mapping llm_node_id -> set of context value_ids
        actually seen by the model at that node
    """
    # Walk provenance backward from the sink argument.
    stack = [sink_arg]
    seen = set()
    tainted = False

    while stack:
        node = stack.pop()
        if node in seen:
            continue
        seen.add(node)

        parents = derivation_graph.get(node, [])

        for parent_id, edge_type in parents:
            if edge_type == "authored":
                # This is an LLM-authored value. Its true taint is the union
                # of its context set's taint. If we did not capture that
                # context set, closure is unprovable -> deny.
                ctx = context_store.get(parent_id)
                if ctx is None:
                    raise TaintLaunderingError(
                        f"LLM node {parent_id!r} authored {node!r} but its "
                        f"context set was not captured; taint-closure over "
                        f"derivation graph is unprovable. Denying sink call."
                    )
                # Push the actual context values, not the recorded parents.
                stack.extend(ctx)
            else:
                stack.append(parent_id)

        # A value is tainted if any resolved origin carries the label.
        if "untrusted" in derivation_graph.get(node, {}).get("labels", set()):
            tainted = True

    if tainted:
        raise TaintLaunderingError(
            f"Sink argument {sink_arg!r} is reachable from an untrusted "
            f"origin via derivation edges; no registered declassification "
            f"edge found. Blocking external sink call."
        )

    return True
