# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-a-branch-commits-an-irreversible-tool-side-effect-and-then-loses-the-merge-race.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-a-branch-commits-an-irreversible-tool-side-effect-and-then-loses-the-merge-race.warrant.json
# Markdown SHA-256:   06786883795bae7953cfa0907b3a47fd23aaa4ab26e2bfeda63ac4fa1d4f3a67
# Code AST SHA-256:   ad6d74605c00e5a17cbbeb45ff157f7ab95ebbea04a2ddd21b95f2a7da130118
# Verified Classes:   Reversibility, ToolInvocation, Branch, UnreconcilableSpeculationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Reversibility(Enum):
    DEFERRED = "deferred"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


@dataclass
class ToolInvocation:
    tool: str
    reversibility: Reversibility
    pre_state: Optional[dict] = None
    committed: bool = False


@dataclass
class Branch:
    branch_id: str
    invocations: list = field(default_factory=list)
    selected: bool = False


class UnreconcilableSpeculationError(RuntimeError):
    """Raised when a losing speculative branch committed an irreversible effect,
    making the world state unreconcilable with any branch plan. The task graph
    must halt and escalate; it must not proceed to merge."""


def arbiter_commit(branches: list, winner_id: str) -> Branch:
    winner = next((b for b in branches if b.branch_id == winner_id), None)
    if winner is None:
        raise UnreconcilableSpeculationError(f"winner {winner_id} not found in graph")

    # Invariant: no losing branch may have committed an irreversible effect.
    for b in branches:
        if b.branch_id == winner_id:
            continue
        for inv in b.invocations:
            if inv.committed and inv.reversibility is Reversibility.IRREVERSIBLE:
                raise UnreconcilableSpeculationError(
                    f"losing branch {b.branch_id} committed irreversible tool "
                    f"'{inv.tool}'; world state cannot be reconciled with winner "
                    f"{winner_id}. Halting graph for escalation."
                )

    # Re-validate winner preconditions against current world state, not fork-time.
    for inv in winner.invocations:
        if not inv.committed and inv.pre_state is None:
            raise UnreconcilableSpeculationError(
                f"winner {winner_id} invocation '{inv.tool}' lacks pre-state; "
                f"cannot re-validate preconditions at commit time."
            )

    winner.selected = True
    return winner
