# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-invocations-from-leaking-irreversible-side-effects-across-branch-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-invocations-from-leaking-irreversible-side-effects-across-branch-rollback.warrant.json
# Markdown SHA-256:   bca463c5df449dd21824d03987f3ad2f9b075d565a7bac16ef8b1d97d731b436
# Code AST SHA-256:   2529ff3682358923224c03530e05590bd0c5011b23c3690a84f92695a32e3b69
# Verified Classes:   SpeculationViolation, EffectClass, TokenState, ToolSpec, Branch, SpeculativeOrchestrator
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class SpeculationViolation(RuntimeError):
    """Raised when a speculative branch attempts an effect it is not authorized to emit."""
    pass


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


class TokenState(Enum):
    SPECULATIVE = "speculative"
    VALIDATED = "validated"
    ABANDONED = "abandoned"


@dataclass
class ToolSpec:
    name: str
    effect_class: EffectClass
    compensator: Callable[[dict], None] | None = None


@dataclass
class Branch:
    branch_id: str
    state: TokenState = TokenState.SPECULATIVE
    compensators: list[Callable[[], None]] = field(default_factory=list)


class SpeculativeOrchestrator:
    def __init__(self) -> None:
        self._registry: dict[str, ToolSpec] = {}

    def register_tool(self, spec: ToolSpec) -> None:
        if spec.effect_class is EffectClass.COMPENSABLE and spec.compensator is None:
            raise SpeculationViolation(
                f"tool {spec.name!r} declared COMPENSABLE but has no compensator; "
                "write-ahead compensation is mandatory"
            )
        self._registry[spec.name] = spec

    def invoke(self, branch: Branch, tool_name: str, args: dict) -> dict:
        spec = self._registry.get(tool_name)
        if spec is None:
            raise SpeculationViolation(f"unregistered tool {tool_name!r}")

        # Gate 1: irreversible effects require a validated token.
        if spec.effect_class is EffectClass.IRREVERSIBLE and branch.state is not TokenState.VALIDATED:
            raise SpeculationViolation(
                f"branch {branch.branch_id} in state {branch.state.value} attempted "
                f"IRREVERSIBLE tool {tool_name!r}; validate before dispatch"
            )

        # Gate 2: compensable effects must register compensation write-ahead.
        if spec.effect_class is EffectClass.COMPENSABLE:
            if spec.compensator is None:
                raise SpeculationViolation(f"no compensator for {tool_name!r}")
            branch.compensators.append(lambda: spec.compensator(args))

        # Gate 3: abandoned branches may not dispatch at all.
        if branch.state is TokenState.ABANDONED:
            raise SpeculationViolation(
                f"branch {branch.branch_id} is ABANDONED and cannot invoke {tool_name!r}"
            )

        return {"tool": tool_name, "args": args, "dispatched": True}

    def rollback(self, branch: Branch) -> None:
        branch.state = TokenState.ABANDONED
        for compensate in reversed(branch.compensators):
            compensate()
        branch.compensators.clear()

    def validate(self, branch: Branch) -> None:
        if branch.state is not TokenState.SPECULATIVE:
            raise SpeculationViolation(
                f"branch {branch.branch_id} cannot transition {branch.state.value} -> VALIDATED"
            )
        branch.state = TokenState.VALIDATED
        # Winner's compensators are confirmed-unneeded.
        branch.compensators.clear()
