# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-speculative-branches-verifier-gated-commit-and-the-orphaned-side-effect-rollback-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-speculative-branches-verifier-gated-commit-and-the-orphaned-side-effect-rollback-invariant.warrant.json
# Markdown SHA-256:   571608ec3ce7c485414b8999109bdc3ddb85b19bae15510dc9579bf134e79814
# Code AST SHA-256:   9e5fed8da8b0415c64231ded8f32140b538c8e2a4aad7a3d3ae55028a3c0f4dc
# Verified Classes:   EffectClass, SpeculationInvariantError, CommitToken, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    PURE = "pure"
    BUFFERED = "buffered"
    IRREVERSIBLE = "irreversible"


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


@dataclass
class CommitToken:
    branch_id: str
    granted: bool = False


@dataclass
class Branch:
    branch_id: str
    grant: dict[str, EffectClass]
    token: CommitToken
    pending_effects: list[tuple[str, Callable[[], None]]] = field(default_factory=list)
    registered_inverses: list[Callable[[], None]] = field(default_factory=list)


def emit(branch: Branch, tool: str, effect: Callable[[], None],
         inverse: Callable[[], None] | None = None) -> None:
    """Route a tool effect according to its class and the branch's commit status."""
    cls = branch.grant.get(tool)
    if cls is None:
        raise SpeculationInvariantError(
            f"branch {branch.branch_id} invoked ungranted tool {tool!r}"
        )

    if cls is EffectClass.PURE:
        effect()
        return

    if cls is EffectClass.BUFFERED:
        if inverse is None:
            raise SpeculationInvariantError(
                f"branch {branch.branch_id} buffered {tool!r} without a registered inverse"
            )
        branch.pending_effects.append((tool, effect))
        branch.registered_inverses.append(inverse)
        return

    # IRREVERSIBLE: only legal after the verifier has committed this branch.
    if not branch.token.granted or branch.token.branch_id != branch.branch_id:
        raise SpeculationInvariantError(
            f"branch {branch.branch_id} attempted irreversible {tool!r} "
            f"before commit token was granted"
        )
    effect()


def commit(branch: Branch) -> None:
    """Verifier-selected branch: mint token, replay buffered effects, emit irreversibles."""
    branch.token = CommitToken(branch_id=branch.branch_id, granted=True)
    for tool, effect in branch.pending_effects:
        effect()
    branch.pending_effects.clear()
    branch.registered_inverses.clear()


def discard(branch: Branch) -> None:
    """Loser branch: run registered inverses, drop buffered effects, never emit."""
    if branch.token.granted:
        raise SpeculationInvariantError(
            f"cannot discard branch {branch.branch_id}: already committed"
        )
    for inverse in reversed(branch.registered_inverses):
        inverse()
    branch.pending_effects.clear()
    branch.registered_inverses.clear()
