# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-prefetched-tool-call-taint-gated-commit-under-speculative-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-prefetched-tool-call-taint-gated-commit-under-speculative-execution.warrant.json
# Markdown SHA-256:   ee220b1960fe76547b28a8be10e2f513b48c6d9ad0889e723cf75bf24c250c2d
# Code AST SHA-256:   561729e5a27e58b6dca13de6188a9deab9a7383b3c3bbfed96cb2e4ef18df310
# Verified Classes:   Taint, TaintCommitRefusal, Span, PrefetchedCall, ContextGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum

class Taint(Enum):
    CLEAN = "clean"
    TAINTED = "tainted"
    UNKNOWN = "unknown"

class TaintCommitRefusal(RuntimeError):
    """Raised when an effectful prefetched call cannot be committed safely."""
    pass

@dataclass
class Span:
    span_id: str
    taint: Taint
    is_effectful: bool = False

@dataclass
class PrefetchedCall:
    call_id: str
    effectful: bool
    declared_deps: set[str]
    dispatch_snapshot_taint: Taint  # frozen at dispatch; NOT authoritative

@dataclass
class ContextGraph:
    spans: dict[str, Span] = field(default_factory=dict)
    attended: set[str] = field(default_factory=set)  # model-layer, not planner-layer

    def closure(self, deps: set[str]) -> set[str]:
        # transitive ancestors; simplified to direct for illustration
        return set(deps)

    def recompute_taint(self, deps: set[str]) -> Taint:
        c = self.closure(deps)
        if any(self.spans[s].taint == Taint.TAINTED for s in c):
            return Taint.TAINTED
        if any(self.spans[s].taint == Taint.UNKNOWN for s in c):
            return Taint.UNKNOWN
        return Taint.CLEAN

def commit(call: PrefetchedCall, graph: ContextGraph) -> None:
    if not call.effectful:
        return  # read-only prefetch may proceed regardless of taint

    live_taint = graph.recompute_taint(call.declared_deps)

    # silent-dependency check: attended spans not in declared closure
    silent = graph.attended - graph.closure(call.declared_deps)
    if any(graph.spans[s].taint == Taint.TAINTED for s in silent):
        raise TaintCommitRefusal(
            f"{call.call_id}: silent tainted dependency in attended-but-undeclared spans"
        )

    if live_taint != Taint.CLEAN:
        raise TaintCommitRefusal(
            f"{call.call_id}: live taint={live_taint.value}, "
            f"dispatch snapshot={call.dispatch_snapshot_taint.value}; refuse effect"
        )

    # effect applies only here, synchronously after re-derivation
    _apply_effect(call)

def _apply_effect(call: PrefetchedCall) -> None:
    pass  # side effect boundary
