# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branches-when-rollback-is-cheaper-than-verification-but-the-branch-s-external-effects-are-not-reversible.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branches-when-rollback-is-cheaper-than-verification-but-the-branch-s-external-effects-are-not-reversible.warrant.json
# Markdown SHA-256:   18ba7032246c440d1454cc7e9c9c65157774c02899271a7113360be4995bd7ef
# Code AST SHA-256:   144a64bfb0490db7c87d65bc473ae102f144fa382b017e3ab51c33143e30e4fe
# Verified Classes:   EffectState, SpeculationRollbackError, EffectEntry, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EffectState(Enum):
    NEVER_ISSUED = "never_issued"
    PENDING = "pending"          # issued, compensation not yet confirmed
    COMPENSATED = "compensated"  # idempotent undo confirmed by downstream
    UNKNOWN = "unknown"          # compensation failed / timed out


class SpeculationRollbackError(RuntimeError):
    """Raised when a losing branch is discarded before its external
    effects are provably compensated. Halts reconciliation rather than
    letting the winner observe phantom state."""


@dataclass
class EffectEntry:
    branch_id: str
    idempotency_key: str
    state: EffectState = EffectState.NEVER_ISSUED


@dataclass
class Branch:
    branch_id: str
    score: float
    effects: dict[str, EffectEntry] = field(default_factory=dict)
    suspended: bool = False


def issue_effect(branch: Branch, key: str) -> EffectEntry:
    # Journal BEFORE the external call so a crash cannot orphan the effect.
    entry = EffectEntry(branch.branch_id, key, EffectState.PENDING)
    branch.effects[key] = entry
    return entry


def reconcile(winner: Branch, losers: list[Branch]) -> list[Branch]:
    """Return branches safe to DISCARD. SUSPEND the rest. Refuse to let
    the winner advance while any sibling holds a live effect."""
    discardable: list[Branch] = []
    for b in losers:
        live = [e for e in b.effects.values()
                if e.state in (EffectState.PENDING, EffectState.UNKNOWN)]
        if live:
            b.suspended = True
            # Do NOT drop context or tool log while effects are live.
            raise SpeculationRollbackError(
                f"branch {b.branch_id} has {len(live)} uncompensated "
                f"effect(s) {[e.idempotency_key for e in live]}; "
                f"cannot discard. Suspending and draining compensation "
                f"before winner {winner.branch_id} may proceed."
            )
        discardable.append(b)
    return discardable


def drain_compensation(branch: Branch, confirm) -> None:
    """confirm(key) -> bool is the downstream idempotent undo check."""
    for e in branch.effects.values():
        if e.state is EffectState.PENDING:
            e.state = EffectState.COMPENSATED if confirm(e.idempotency_key) \
                else EffectState.UNKNOWN
    if any(e.state is EffectState.UNKNOWN for e in branch.effects.values()):
        raise SpeculationRollbackError(
            f"branch {branch.branch_id} compensation did not confirm; "
            f"state is UNKNOWN and task must halt, not degrade."
        )
