# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-whose-optimistic-tool-call-has-already-committed-an-irreversible-external-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-whose-optimistic-tool-call-has-already-committed-an-irreversible-external-side-effect.warrant.json
# Markdown SHA-256:   dec6cc7814d0da0fc0efbcf8210f232ff7615186d7e6c6b004795130b273f88b
# Code AST SHA-256:   ff78576d451861c08b91ed8db4f37b3f40eac8bcb97be62e17e4f4a110c60651
# Verified Classes:   ToolClass, StickyRollbackError, Receipt, Branch, SpeculativeOrchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ToolClass(Enum):
    REVERSIBLE = "reversible"
    GATED = "gated"
    IRREVERSIBLE = "irreversible"


class StickyRollbackError(RuntimeError):
    """Raised when a merge protocol attempts to roll back a branch that has
    committed an irreversible external side effect."""


@dataclass
class Receipt:
    branch_id: str
    tool_name: str
    external_id: str
    idempotency_key: Optional[str]


@dataclass
class Branch:
    branch_id: str
    tool_class: ToolClass
    committed_receipts: list[Receipt] = field(default_factory=list)

    @property
    def is_sticky(self) -> bool:
        return any(r.idempotency_key is None for r in self.committed_receipts)


class SpeculativeOrchestrator:
    def __init__(self) -> None:
        # Escrow lives OUTSIDE any branch and survives rollback.
        self.escrow: list[Receipt] = []

    def commit_optimistic_call(
        self, branch: Branch, tool_name: str, external_id: str,
        idempotency_key: Optional[str],
    ) -> Receipt:
        if branch.tool_class is ToolClass.IRREVERSIBLE and idempotency_key is None:
            # Allowed only because we escrow; otherwise this is the bug.
            pass
        receipt = Receipt(branch.branch_id, tool_name, external_id, idempotency_key)
        self.escrow.append(receipt)          # durable, branch-independent
        branch.committed_receipts.append(receipt)
        return receipt

    def rollback(self, branch: Branch) -> None:
        if branch.is_sticky:
            receipts = [r for r in self.escrow if r.branch_id == branch.branch_id]
            raise StickyRollbackError(
                f"branch {branch.branch_id} has committed irreversible effects "
                f"{[r.external_id for r in receipts]}; rollback would orphan them. "
                f"Route to compensation or halt."
            )
        branch.committed_receipts.clear()

    def merge(self, winner: Branch, losers: list[Branch]) -> None:
        for loser in losers:
            self.rollback(loser)  # will raise if any loser is sticky


def reconcile(orchestrator: SpeculativeOrchestrator, winner: Branch, losers: list[Branch]) -> None:
    try:
        orchestrator.merge(winner, losers)
    except StickyRollbackError as exc:
        # Escalated: escrow still holds the receipts, so compensation is possible.
        raise StickyRollbackError(
            f"merge aborted; compensating required: {exc}"
        ) from exc
