# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-invocation-before-branch-and-rollback-commits-an-unrollbackable-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-invocation-before-branch-and-rollback-commits-an-unrollbackable-side-effect.warrant.json
# Markdown SHA-256:   eef4ff48cc07a83f8869bb47fdb870326a0eaff817ca243102a31028c94fe2d8
# Code AST SHA-256:   4e3c8b9390ceb8b82251f35b3706aa7bad163e29e6de6f5983ba56969d152245
# Verified Classes:   CommitmentClass, SpeculationBoundaryError, ToolCall, Branch
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class CommitmentClass(Enum):
    PURE = "pure"                    # no external effect
    REVERSIBLE_STATE = "reversible"  # agent-owned state only
    COMPENSABLE = "compensable"      # external, observable, has compensator
    IRREVERSIBLE = "irreversible"    # no sound rollback


class SpeculationBoundaryError(RuntimeError):
    """Raised when a speculative branch would cross the commit barrier
    without a staged intent, or when rollback is claimed without verified
    compensation."""


@dataclass
class ToolCall:
    name: str
    commitment: CommitmentClass
    compensate: Callable[[], bool] | None = None  # returns True iff externally verified
    staged: bool = False


@dataclass
class Branch:
    branch_id: str
    calls: list[ToolCall] = field(default_factory=list)
    observed_by: set[str] = field(default_factory=set)  # branches that read our effects
    committed: bool = False


def fire_speculatively(branch: Branch, call: ToolCall, scorer_p_win: float) -> None:
    """Optimistic invocation gate. Must refuse to fire across the barrier."""
    if call.commitment in (CommitmentClass.IRREVERSIBLE,):
        raise SpeculationBoundaryError(
            f"branch {branch.branch_id}: refusing to speculatively fire "
            f"{call.name} ({call.commitment.value}); no sound rollback exists"
        )
    if call.commitment is CommitmentClass.COMPENSABLE:
        # Allowed only as a staged intent, never as a live call.
        call.staged = True
        branch.calls.append(call)
        # Scorer must reason over the intent, not the effect.
        if scorer_p_win < 0.0:
            raise SpeculationBoundaryError(
                f"branch {branch.branch_id}: scorer cannot rank staged intent {call.name}"
            )
        return
    # PURE / REVERSIBLE_STATE: safe to fire now.
    branch.calls.append(call)


def rollback(branch: Branch) -> None:
    """Rollback is only clean if every effect is restored or verified-compensated,
    and no surviving branch observed the compensated effect."""
    if branch.observed_by:
        raise SpeculationBoundaryError(
            f"branch {branch.branch_id}: cannot roll back; effects were observed by "
            f"{sorted(branch.observed_by)} before compensation—premise corruption"
        )
    for call in reversed(branch.calls):
        if call.commitment is CommitmentClass.REVERSIBLE_STATE:
            continue  # state restore is total and assumed done by runtime
        if call.commitment is CommitmentClass.IRREVERSIBLE:
            raise SpeculationBoundaryError(
                f"branch {branch.branch_id}: irreversible effect {call.name} already fired"
            )
        if call.commitment is CommitmentClass.COMPENSABLE:
            if call.compensate is None:
                raise SpeculationBoundaryError(
                    f"branch {branch.branch_id}: {call.name} has no compensator"
                )
            if not call.compensate():
                raise SpeculationBoundaryError(
                    f"branch {branch.branch_id}: compensation for {call.name} "
                    f"unverified by external system; refusing to report clean rollback"
                )
    branch.calls.clear()
