# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-across-a-mid-pipeline-retrieval-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-across-a-mid-pipeline-retrieval-compaction-boundary.warrant.json
# Markdown SHA-256:   9f2292074aaa6b44712d4b598ce6d56f9215d9488d5c0ba9663a54efbbe3214a
# Code AST SHA-256:   9a2bf09d6f9825881e3046074faa01dc59b9e3008e01443eeced22a59342883f
# Verified Classes:   TaintClosureViolation, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintClosureViolation(RuntimeError):
    """Raised when a tool-call argument's provenance DAG cannot prove taint-closure."""


@dataclass
class Span:
    span_id: str
    untrusted: bool
    derived_from: tuple[str, ...] = ()
    is_ingestion_source: bool = False


def compute_join_taint(span: Span, registry: dict[str, Span], _seen: Optional[set] = None) -> bool:
    """Taint of a span = its own bit OR the join over all recorded sources.

    A producer span with no recorded inputs and not an ingestion source is
    treated as tainted: its inputs are unverifiable, so we fail closed.
    """
    if _seen is None:
        _seen = set()
    if span.span_id in _seen:
        raise TaintClosureViolation(f"cycle in provenance DAG at {span.span_id}")
    _seen.add(span.span_id)

    if not span.derived_from:
        if not span.is_ingestion_source:
            # Generated content with no provenance: laundering signature.
            return True
        return span.untrusted

    joined = span.untrusted
    for src_id in span.derived_from:
        src = registry.get(src_id)
        if src is None:
            # Missing edge -> unverifiable -> fail closed.
            return True
        joined = joined or compute_join_taint(src, registry, _seen)
    return joined


def gate_tool_call(tool: str, arg_span_ids: list[str], registry: dict[str, Span]) -> None:
    """Approve an outbound tool call only if every argument span is taint-closed and trusted."""
    for sid in arg_span_ids:
        span = registry.get(sid)
        if span is None:
            raise TaintClosureViolation(f"argument span {sid} missing from registry")
        effective_taint = compute_join_taint(span, registry)
        if effective_taint:
            raise TaintClosureViolation(
                f"tool '{tool}' blocked: argument span {sid} is tainted "
                f"(effective_taint=True via provenance join)"
            )


# --- demonstration of the laundering path ---
registry: dict[str, Span] = {}
registry["doc_441"] = Span("doc_441", untrusted=True, is_ingestion_source=True)
# Summarizer emitted a span with NO derived_from edge and default untrusted=False.
registry["summary_9"] = Span("summary_9", untrusted=False, derived_from=(), is_ingestion_source=False)

try:
    gate_tool_call("http_post", ["summary_9"], registry)
except TaintClosureViolation as exc:
    print(f"BLOCKED (fail-closed on unverifiable provenance): {exc}")

# Corrected summarizer: records the edge; join propagates taint.
registry["summary_9_fixed"] = Span(
    "summary_9_fixed", untrusted=False, derived_from=("doc_441",), is_ingestion_source=False
)
try:
    gate_tool_call("http_post", ["summary_9_fixed"], registry)
except TaintClosureViolation as exc:
    print(f"BLOCKED (taint propagated through join): {exc}")
