# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculates-tool-calls-under-idempotency-tokens-and-the-compensating-transaction-fires-against-a-non-compensable-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculates-tool-calls-under-idempotency-tokens-and-the-compensating-transaction-fires-against-a-non-compensable-effect.warrant.json
# Markdown SHA-256:   49427349693a38f4776672299eaab468cf130743e064a1b91c0b0e182c6f2f00
# Code AST SHA-256:   88b9f1f4ebde9efe95d3f2c26b69fd2f6b336af34f89b9659a54acaa34f995e4
# Verified Classes:   EffectClass, NonCompensableSpeculationError, ToolSpec, SpeculativeBranch, SpeculationGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class NonCompensableSpeculationError(RuntimeError):
    """Raised when a speculative branch attempts to execute an irreversible effect."""


@dataclass
class ToolSpec:
    name: str
    effect_class: EffectClass
    effect_key_fn: Callable[[dict], str]
    intent_hash_fn: Callable[[dict], str]


@dataclass
class SpeculativeBranch:
    branch_id: str
    calls: List[dict] = field(default_factory=list)


class SpeculationGate:
    def __init__(self, registry: Dict[str, ToolSpec]):
        self.registry = registry
        self._committed_effect_keys: Dict[str, str] = {}  # effect_key -> intent_hash

    def admit(self, branch: SpeculativeBranch, call: dict) -> str:
        tool = self.registry[call["tool"]]
        effect_key = tool.effect_key_fn(call["args"])
        intent = tool.intent_hash_fn(call["args"])

        if tool.effect_class is EffectClass.IRREVERSIBLE:
            # Must be deferred to post-commit phase; speculation is forbidden.
            raise NonCompensableSpeculationError(
                f"branch {branch.branch_id} attempted speculative call to "
                f"irreversible tool {tool.name} on effect_key={effect_key}; "
                f"defer to commit barrier"
            )

        prior = self._committed_effect_keys.get(effect_key)
        if prior is not None and prior != intent:
            # Same effect, divergent intent: this is a conflict, not a duplicate.
            raise NonCompensableSpeculationError(
                f"effect_key={effect_key} already committed with intent={prior}; "
                f"branch {branch.branch_id} intent={intent} conflicts"
            )

        self._committed_effect_keys[effect_key] = intent
        branch.calls.append(call)
        return f"tok:{branch.branch_id}:{effect_key}:{intent}"

    def compensate(self, branch: SpeculativeBranch) -> None:
        # Only reached for branches whose calls were all COMPENSABLE.
        for call in reversed(branch.calls):
            tool = self.registry[call["tool"]]
            effect_key = tool.effect_key_fn(call["args"])
            self._committed_effect_keys.pop(effect_key, None)
            call["compensate"]()


def run_speculative_plan(gate: SpeculationGate, branch: SpeculativeBranch, plan: List[dict]) -> None:
    try:
        for call in plan:
            gate.admit(branch, call)
    except NonCompensableSpeculationError:
        gate.compensate(branch)
        raise
