# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-speculative-branch-as-un-rollbackable-once-it-has-emitted-an-external-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-speculative-branch-as-un-rollbackable-once-it-has-emitted-an-external-side-effect.warrant.json
# Markdown SHA-256:   dd19c94ce19c6085cb6e2c7aaad026f3eef040e78f3940d1d06ec185d0b4c06d
# Code AST SHA-256:   bbd2662c3cd06815cfaf9ddd5e9246745139d0e36d11f262e3ab010c69ed3c4e
# Verified Classes:   UnrollbackableBranchError, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnrollbackableBranchError(RuntimeError):
    """Raised when a speculative branch is asked to roll back after committing
    an external, non-idempotent effect that no compensation handle covers."""
    pass


class Branch:
    def __init__(self, branch_id, idempotency_token):
        self.branch_id = branch_id
        self.idempotency_token = idempotency_token
        self.committed_effects = []   # list of (tool, handle)
        self.rolled_back = False

    def commit(self, tool_name, compensation_handle=None):
        # A committing tool has already produced an externally observable effect.
        self.committed_effects.append((tool_name, compensation_handle))

    def is_rollbackable(self):
        # Rollback is valid only if every committed effect has a compensation handle
        # the external system honors. A bare external effect is irreversible.
        return all(handle is not None for _, handle in self.committed_effects)

    def rollback(self):
        if self.rolled_back:
            return
        if not self.is_rollbackable():
            bare = [t for t, h in self.committed_effects if h is None]
            raise UnrollbackableBranchError(
                f"branch {self.branch_id} committed irreversible effect(s) {bare}; "
                f"cannot roll back, must reconcile against external truth"
            )
        for tool_name, handle in reversed(self.committed_effects):
            # Compensation is a no-op on the external system via idempotency token.
            handle.compensate(idempotency_token=self.idempotency_token)
        self.rolled_back = True


def select_winner_and_collapse(branches, winner_id):
    winner = next(b for b in branches if b.branch_id == winner_id)
    for b in branches:
        if b.branch_id == winner_id:
            continue
        # Guardrail: collapse is only legal while the loser is still roll-backable.
        if not b.is_rollbackable():
            raise UnrollbackableBranchError(
                f"cannot collapse branch {b.branch_id}: it crossed the rollback "
                f"boundary before selection; escalate to reconciliation"
            )
        b.rollback()
    return winner
