# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-call-prefetch-commit-divergence-in-verification-gated-agent-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-call-prefetch-commit-divergence-in-verification-gated-agent-pipelines.warrant.json
# Markdown SHA-256:   cbe632b06728bd02b055e8a896fd774f2d3d07599396011ea3cb926825c64dc0
# Code AST SHA-256:   22d40b07362c8f1ac5435313a9aaf298ecfea84221b83fb46709a41478ff9c4b
# Verified Classes:   SpeculationDivergenceError, EffectClass, ToolSpec, SpeculativeCall
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class SpeculationDivergenceError(RuntimeError):
    """Raised when a speculative prefetch would corrupt the verification gate's premise."""


class EffectClass(Enum):
    PURE = "pure"
    READ_ONLY_NO_MATERIALIZE = "read_only_no_materialize"
    MATERIALIZES = "materializes"          # lazy write / snapshot / cache warm
    CLOCK_ADVANCING = "clock_advancing"    # returns now(), seq, version
    UNKNOWN = "unknown"


@dataclass
class ToolSpec:
    name: str
    effect: EffectClass
    reads: frozenset[str] = field(default_factory=frozenset)
    advances_clock: bool = False


@dataclass
class SpeculativeCall:
    tool: ToolSpec
    requested_at_step: int
    materialized_at_step: int | None = None


SAFE_EFFECTS = {EffectClass.PURE, EffectClass.READ_ONLY_NO_MATERIALIZE}


def gate(
    speculative: list[SpeculativeCall],
    gate_input_resources: frozenset[str],
    gate_reads_clock: bool,
) -> None:
    """Pre-dispatch + post-gate structural audit. Raises on any divergence signal."""
    for call in speculative:
        if call.tool.effect not in SAFE_EFFECTS:
            raise SpeculationDivergenceError(
                f"tool {call.tool.name!r} has effect {call.tool.effect.value}; "
                f"speculation unsafe for gate inputs {sorted(gate_input_resources)}"
            )
        overlap = call.tool.reads & gate_input_resources
        if overlap:
            raise SpeculationDivergenceError(
                f"tool {call.tool.name!r} effects intersect gate reads {sorted(overlap)}"
            )
        if call.tool.advances_clock and gate_reads_clock:
            raise SpeculationDivergenceError(
                f"tool {call.tool.name!r} advances a clock the gate reads; "
                f"freeze clock snapshot pre-speculation or de-speculate"
            )


def audit_commit(speculative: list[SpeculativeCall], planner_step: int) -> None:
    """Post-gate ordering audit: materialization must follow its requesting step."""
    for call in speculative:
        if call.materialized_at_step is None:
            continue
        if call.materialized_at_step <= call.requested_at_step:
            raise SpeculationDivergenceError(
                f"{call.tool.name!r} materialized at step {call.materialized_at_step} "
                f"but requested at step {call.requested_at_step}; "
                f"timestamp inversion signals speculative side-effect leak"
            )
        if call.materialized_at_step < planner_step:
            raise SpeculationDivergenceError(
                f"{call.tool.name!r} materialized before planner step {planner_step}; "
                f"gate premise invalidated — de-speculate and re-issue sequentially"
            )
