# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-tool-calls-and-rolls-back-without-compensating-external-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-tool-calls-and-rolls-back-without-compensating-external-effects.warrant.json
# Markdown SHA-256:   341dd3fd613790c832c05bacd54304bc9aa4963a2787fd1d9d5867d758e8f27f
# Code AST SHA-256:   69ae59c4d8df6212c789a224b95b5f1fe5988d1ab882285b673bfe73d52e0f61
# Verified Classes:   RollbackSoundnessError, EffectClass, ToolSpec, ExecutedCall, SpeculativeBranch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class RollbackSoundnessError(RuntimeError):
    """Raised when a speculative branch is abandoned with un-compensated external effects."""
    pass


class EffectClass(Enum):
    NONE = "none"
    COMPENSABLE = "compensable"
    RESERVABLE = "reservable"
    SERIALIZE = "serialize"


@dataclass
class ToolSpec:
    name: str
    idempotent: bool
    effect: EffectClass
    compensator: Optional[Callable[[dict], dict]] = None
    compensator_validated: bool = False


@dataclass
class ExecutedCall:
    tool: str
    args: dict
    idempotency_key: str
    compensated: bool = False
    residual: dict = field(default_factory=dict)


class SpeculativeBranch:
    def __init__(self, branch_id: str, coordinator_locks: set):
        self.branch_id = branch_id
        self.calls: list[ExecutedCall] = []
        self._locks = coordinator_locks

    def dispatch(self, spec: ToolSpec, args: dict, key: str, shadow: bool = False) -> dict:
        if shadow:
            # Shadow transport is credential-isolated; it must never reach production.
            return {"shadow": True, "tool": spec.name}

        if spec.effect is EffectClass.NONE:
            self.calls.append(ExecutedCall(spec.name, args, key))
            return {"ok": True}

        if spec.effect is EffectClass.SERIALIZE:
            if self.branch_id not in self._locks:
                raise RollbackSoundnessError(
                    f"branch {self.branch_id} attempted serialized effect "
                    f"{spec.name} without coordinator lock"
                )
            self.calls.append(ExecutedCall(spec.name, args, key))
            return {"ok": True, "serialized": True}

        if spec.effect is EffectClass.COMPENSABLE:
            if spec.compensator is None or not spec.compensator_validated:
                raise RollbackSoundnessError(
                    f"tool {spec.name} declared compensable but compensator "
                    f"is missing or unvalidated; refusing speculative dispatch"
                )
            self.calls.append(ExecutedCall(spec.name, args, key))
            return {"ok": True}

        # RESERVABLE: call lands under a hold keyed to branch_id; released on abandon.
        self.calls.append(ExecutedCall(spec.name, args, key))
        return {"ok": True, "reservation": f"{self.branch_id}:{key}"}

    def abandon(self, specs: dict[str, ToolSpec]) -> list[ExecutedCall]:
        uncompensated: list[ExecutedCall] = []
        for call in self.calls:
            spec = specs[call.tool]
            if spec.effect is EffectClass.NONE:
                continue
            if spec.effect is EffectClass.RESERVABLE:
                # Release hold; no production effect occurred.
                continue
            if spec.effect is EffectClass.SERIALIZE:
                uncompensated.append(call)
                continue
            if spec.compensator is not None and spec.compensator_validated:
                call.residual = spec.compensator(call.args)
                call.compensated = True
            else:
                uncompensated.append(call)

        if uncompensated:
            names = ", ".join(c.tool for c in uncompensated)
            raise RollbackSoundnessError(
                f"branch {self.branch_id} abandoned with un-compensated effects: {names}"
            )
        return self.calls
