# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-commit-a-speculative-branch-when-rollback-cannot-restore-a-non-idempotent-external-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-commit-a-speculative-branch-when-rollback-cannot-restore-a-non-idempotent-external-effect.warrant.json
# Markdown SHA-256:   7b2933bb56c1c1f30e32c8a3b9d705a2b02f447b84f4c59d8f61b5ff08faebc4
# Code AST SHA-256:   1021478d9c7feffd2996cacf1fa75f16d91cac4b8d9ff1267dcba533082ea340
# Verified Classes:   IrreversibleEffectLeak, EffectKind, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class IrreversibleEffectLeak(RuntimeError):
    """Raised when a speculative commit would strand an un-compensated external effect."""
    pass


class EffectKind(Enum):
    FENCED = "fenced"          # observable only on commit
    COMPENSABLE = "compensable"  # has a registered, idempotent compensator
    IRREVERSIBLE = "irreversible"  # neither; leaks if branch loses


@dataclass
class Effect:
    branch_id: str
    kind: EffectKind
    emitted: bool = False
    compensated: bool = False


@dataclass
class Branch:
    branch_id: str
    effects: list = field(default_factory=list)
    committed: bool = False


def commit_branch(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 IrreversibleEffectLeak(f"winner {winner_id} not among branches")

    losers = [b for b in branches if b.branch_id != winner_id]
    for loser in losers:
        for eff in loser.effects:
            if not eff.emitted:
                continue
            if eff.kind is EffectKind.FENCED:
                continue  # never became observable; safe to drop
            if eff.kind is EffectKind.COMPENSABLE and eff.compensated:
                continue
            # emitted, irreversible (or compensable but not yet compensated)
            raise IrreversibleEffectLeak(
                f"branch {loser.branch_id} emitted {eff.kind.value} effect "
                f"that rollback cannot restore; refusing to commit {winner_id}. "
                f"Reconcile or compensate before commit."
            )

    winner.committed = True
    return winner
