# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-whose-sibling-branch-already-emitted-an-irreversible-external-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-whose-sibling-branch-already-emitted-an-irreversible-external-side-effect.warrant.json
# Markdown SHA-256:   17439bd922574ff05ec61c7b4ab58658142349a52de10f41b1cdcb46576f12ad
# Code AST SHA-256:   da5d49a9d3bc18581e20d6a4c8b6d9dd7e26e66a4323f3a3d7d063f4ad21507d
# Verified Classes:   ReconciliationError, EffectKind, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ReconciliationError(RuntimeError):
    """Raised when a speculative commit would contradict an unreconciled sibling effect."""


class EffectKind(Enum):
    DEFERRED = "deferred"          # recorded as intent, not yet executed
    IDEMPOTENT = "idempotent"      # safe to replay under a task-scoped key
    IRREVERSIBLE = "irreversible"  # moved money, sent mail, mutated shared row


@dataclass
class Effect:
    branch_id: str
    kind: EffectKind
    idempotency_key: Optional[str] = None
    compensation: Optional[str] = None  # descriptor; None means no undo path
    executed: bool = False


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect] = field(default_factory=list)
    frozen: bool = False


def reconcile_and_commit(winner: Branch, siblings: list[Branch], ledger: list[Effect]) -> None:
    # 1. Freeze siblings so no new effects can be emitted mid-reconciliation.
    for sib in siblings:
        sib.frozen = True

    # 2. Enumerate emitted effects from the LEDGER, not the branch transcript.
    for effect in ledger:
        if effect.branch_id == winner.branch_id:
            continue
        if not effect.executed:
            continue
        if effect.kind is EffectKind.DEFERRED:
            # Never executed; safe to drop.
            continue
        if effect.kind is EffectKind.IDEMPOTENT and effect.idempotency_key:
            # Replay-safe under a task-scoped key; no compensation needed.
            continue
        if effect.kind is EffectKind.IRREVERSIBLE:
            if effect.compensation is None:
                raise ReconciliationError(
                    f"branch {effect.branch_id} emitted irreversible effect with no "
                    f"compensation descriptor; commit of {winner.branch_id} would "
                    f"contradict world state. Halting as UNRECONCILED."
                )
            # Apply compensation before winner resumes.
            _apply_compensation(effect)

    # 3. Only now may the winner resume reasoning.
    winner.frozen = False


def _apply_compensation(effect: Effect) -> None:
    # Real implementation dispatches to the tool's undo path.
    if effect.compensation is None:
        raise ReconciliationError(f"no compensation for effect in {effect.branch_id}")
