# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-pre-execute-tool-calls-that-later-diverge-the-commit-barrier-invariant-and-the-half-committed-side-effect-trap.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-pre-execute-tool-calls-that-later-diverge-the-commit-barrier-invariant-and-the-half-committed-side-effect-trap.warrant.json
# Markdown SHA-256:   b4751e53b875d3de53a7ce97d90ccf48b6d3b40558f6834ca82befc2f3c2c432
# Code AST SHA-256:   95d1134c43695de008d183ef21d6c2e35095383411f77315e1d624fad15600f2
# Verified Classes:   ReversibilityClass, SpeculationBarrierError, ToolSpec, CallState, SpeculationController
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ReversibilityClass(Enum):
    REVERSIBLE = "R"      # idempotent; safe to discard
    COMPENSABLE = "C"     # irreversible but has a registered, idempotent compensation
    IRREVERSIBLE = "I"    # irreversible, non-compensable; never speculate


class SpeculationBarrierError(RuntimeError):
    """Raised when a speculative dispatch would cross an irreversible boundary
    before the commit barrier, or when a post-effect divergence is handled
    without a registered compensation."""


@dataclass
class ToolSpec:
    name: str
    klass: ReversibilityClass
    compensate: Callable[[dict], None] | None = None


@dataclass
class CallState:
    tool: str
    draft_args: dict
    barrier_passed: bool = False
    dispatched: bool = False
    effect_emitted: bool = False
    speculation_nonce: str | None = None


class SpeculationController:
    def __init__(self, registry: dict[str, ToolSpec]):
        self.registry = registry

    def classify(self, tool: str) -> ToolSpec:
        spec = self.registry.get(tool)
        if spec is None:
            # Fail closed: unknown tools are treated as irreversible.
            return ToolSpec(tool, ReversibilityClass.IRREVERSIBLE)
        return spec

    def may_speculate(self, tool: str, barrier_passed: bool) -> bool:
        spec = self.classify(tool)
        if barrier_passed:
            return True  # committed; not speculation
        if spec.klass is ReversibilityClass.REVERSIBLE:
            return True
        if spec.klass is ReversibilityClass.COMPENSABLE:
            return spec.compensate is not None
        return False  # IRREVERSIBLE: gate on barrier

    def dispatch_speculative(self, state: CallState) -> None:
        spec = self.classify(state.tool)
        if state.barrier_passed:
            state.dispatched = True
            state.effect_emitted = True
            state.speculation_nonce = None
            return
        if not self.may_speculate(state.tool, state.barrier_passed):
            raise SpeculationBarrierError(
                f"speculative dispatch of {state.tool!r} "
                f"(class {spec.klass.value}) before commit barrier"
            )
        state.dispatched = True
        state.effect_emitted = True
        state.speculation_nonce = f"spec:{state.tool}:{id(state):x}"

    def on_divergence(self, state: CallState) -> None:
        if not state.dispatched:
            return  # nothing to clean up
        if not state.effect_emitted:
            return  # future cancelled pre-effect; free
        spec = self.classify(state.tool)
        if spec.klass is ReversibilityClass.REVERSIBLE:
            return  # idempotent; discard
        if spec.klass is ReversibilityClass.COMPENSABLE:
            if spec.compensate is None:
                raise SpeculationBarrierError(
                    f"post-effect divergence on {state.tool!r} "
                    f"with no registered compensation"
                )
            spec.compensate(state.draft_args)  # must be idempotent and acked
            return
        # IRREVERSIBLE and effect already emitted: the trap. Cannot retract.
        raise SpeculationBarrierError(
            f"half-committed side effect: {state.tool!r} emitted effect "
            f"(nonce={state.speculation_nonce}) before commit barrier; "
            f"phantom event is now in the system of record"
        )
