# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-speculative-branch-s-tool-side-effects-as-irreversible-before-the-merge-barrier-and-how-does-rollback-on-di.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-speculative-branch-s-tool-side-effects-as-irreversible-before-the-merge-barrier-and-how-does-rollback-on-di.warrant.json
# Markdown SHA-256:   1993ead9c6c191796323a30844b18cd82f99e0e745c345e39458ffd28363475b
# Code AST SHA-256:   7972f022a40d5e48288fc5ccec310e4387260edf71fb9bbaea9914b6c659562e
# Verified Classes:   EffectClass, SpeculationBoundaryError, ToolSpec, Branch
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    CONFINED = "confined"          # branch-scoped scratch; rollback = drop
    DEDUP_KEYED = "dedup_keyed"    # non-idempotent but accepts op key
    UNRECOVERABLE = "unrecoverable"  # non-idempotent, no key, opaque handle


class SpeculationBoundaryError(RuntimeError):
    """Raised when a branch is forked across a tool whose effects cannot be rolled back."""


@dataclass
class ToolSpec:
    name: str
    effect: EffectClass
    accepts_dedup_key: bool = False
    returns_opaque_handle: bool = False


@dataclass
class Branch:
    branch_id: str
    tool_calls: list = field(default_factory=list)
    persisted_handles: dict = field(default_factory=dict)


def assert_fork_is_discardable(branch: Branch, tool_registry: dict, op_key_assigned: bool) -> None:
    """Pre-fork gate: refuse to speculate a branch that can mutate unowned external state."""
    for call in branch.tool_calls:
        spec: Optional[ToolSpec] = tool_registry.get(call["tool"])
        if spec is None:
            raise SpeculationBoundaryError(
                f"branch {branch.branch_id}: tool {call['tool']!r} unregistered; "
                f"effect class unknown, cannot certify discardable"
            )
        if spec.effect is EffectClass.CONFINED:
            continue
        if spec.effect is EffectClass.DEDUP_KEYED:
            if not spec.accepts_dedup_key or not op_key_assigned:
                raise SpeculationBoundaryError(
                    f"branch {branch.branch_id}: tool {spec.name!r} is non-idempotent "
                    f"and no pre-fork operation key was assigned; a losing branch "
                    f"cannot be collapsed into the winner's effect"
                )
            continue
        # UNRECOVERABLE
        raise SpeculationBoundaryError(
            f"branch {branch.branch_id}: tool {spec.name!r} has unrecoverable external "
            f"effect (opaque_handle={spec.returns_opaque_handle}); must be serialized "
            f"behind the merge barrier, not speculated"
        )


def merge_barrier(selected: Branch, discarded: list[Branch], external_state: dict,
                  invariant) -> None:
    """Post-merge: re-read external state; do not trust the abort ledger."""
    for b in discarded:
        for handle in b.persisted_handles.values():
            if handle in external_state.get("live_handles", ()):
                raise SpeculationBoundaryError(
                    f"discarded branch {b.branch_id} left live external handle {handle!r}; "
                    f"rollback was context-only, effect survived"
                )
    if not invariant(external_state):
        raise SpeculationBoundaryError(
            f"post-merge invariant violated: {external_state!r}; "
            f"abort ledger claims clean but resource disagrees"
        )
