# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-optimistic-commit-of-a-speculative-branch-when-tool-effects-are-only-partially-reversible.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-optimistic-commit-of-a-speculative-branch-when-tool-effects-are-only-partially-reversible.warrant.json
# Markdown SHA-256:   0fc6b80efded8275b57bc0d49f9e665290ca588abdbafaa26f855d650248343b
# Code AST SHA-256:   b1a3e99fcf34e39d4b3aaf6f05ce765773da0045c4a3fce48944060390dc0582
# Verified Classes:   SpeculationBoundaryError, EffectClass, ToolEffect, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class SpeculationBoundaryError(RuntimeError):
    """Raised when a speculative branch cannot be safely committed or rolled back."""


class EffectClass(Enum):
    STAGED = "staged"                 # internal, commit-flag gated
    EPOCH_KEYED = "epoch_keyed"       # external idempotent, key encodes epoch
    OBSERVABLE_ASYNC = "observable_async"  # reversal exists but settles late
    IRREVERSIBLE = "irreversible"     # no compensation primitive


@dataclass(frozen=True)
class ToolEffect:
    name: str
    effect_class: EffectClass
    idempotency_key: str | None = None
    speculation_epoch: str | None = None


@dataclass
class Branch:
    branch_id: str
    effects: list[ToolEffect] = field(default_factory=list)
    fenced: bool = False


def assert_committable(branch: Branch, commit_epoch: str) -> None:
    """Refuse optimistic commit if the branch's effect set violates the boundary."""
    if not branch.fenced:
        raise SpeculationBoundaryError(
            f"branch {branch.branch_id}: commit attempted before quiescence fence; "
            "effect set is not closed, late effects can escape rollback"
        )
    for eff in branch.effects:
        if eff.effect_class is EffectClass.IRREVERSIBLE:
            raise SpeculationBoundaryError(
                f"branch {branch.branch_id}: effect {eff.name!r} is irreversible; "
                "serialize behind the commit decision"
            )
        if eff.effect_class is EffectClass.OBSERVABLE_ASYNC:
            raise SpeculationBoundaryError(
                f"branch {branch.branch_id}: effect {eff.name!r} is observable before "
                "its compensation settles; rollback would be untruthful"
            )
        if eff.effect_class is EffectClass.EPOCH_KEYED:
            if eff.idempotency_key is None or eff.speculation_epoch != commit_epoch:
                raise SpeculationBoundaryError(
                    f"branch {branch.branch_id}: effect {eff.name!r} idempotency key "
                    "does not encode the speculation epoch; retry after rollback may "
                    "collide with the winner"
                )


def optimistic_commit(branch: Branch, commit_epoch: str) -> None:
    assert_committable(branch, commit_epoch)
    # commit proceeds; rollback path is now guaranteed truthful and retry-safe
