# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-speculative-branches-when-rollback-crosses-a-shared-external-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-speculative-branches-when-rollback-crosses-a-shared-external-side-effect.warrant.json
# Markdown SHA-256:   95042c474542996ef62046a636c348bcade8cb5593c93649e0b0fcc5c70361a3
# Code AST SHA-256:   979f8441ac78652c8e19e855f971a8e0da5fa32b4ecde637ee67ccd575360473
# Verified Classes:   RollbackPreconditionError, EffectState, EffectRecord, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class RollbackPreconditionError(RuntimeError):
    """Raised when a branch is rolled back while an external effect is indeterminate."""
    pass


class EffectState(enum.Enum):
    PENDING_ACK = "pending_ack"                 # async accept, no durable handle yet
    ACCEPTED_WITHOUT_HANDLE = "accepted_without_handle"
    COMMITTED_WITH_HANDLE = "committed_with_handle"
    REJECTED = "rejected"
    EXPIRED = "expired"
    COMPENSATED = "compensated"


@dataclass
class EffectRecord:
    tool: str
    idempotent: bool
    fenced: bool
    state: EffectState
    handle: Optional[str] = None


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


TERMINAL = {EffectState.REJECTED, EffectState.EXPIRED, EffectState.COMPENSATED}


def rollback(branch: Branch, compensate) -> None:
    """Mark a branch rolled back only if every external effect is terminal."""
    for eff in branch.effects:
        if eff.state in (EffectState.PENDING_ACK, EffectState.ACCEPTED_WITHOUT_HANDLE):
            raise RollbackPreconditionError(
                f"branch {branch.branch_id}: effect on {eff.tool} is "
                f"{eff.state.value}; external state indeterminate, "
                f"quarantine and resolve via status API before rollback"
            )
        if eff.state == EffectState.COMMITTED_WITH_HANDLE:
            if not eff.idempotent and eff.handle is None:
                raise RollbackPreconditionError(
                    f"branch {branch.branch_id}: committed non-idempotent "
                    f"effect on {eff.tool} has no handle; cannot compensate"
                )
            compensate(eff.handle)
            eff.state = EffectState.COMPENSATED
        if eff.state not in TERMINAL and eff.state != EffectState.COMMITTED_WITH_HANDLE:
            raise RollbackPreconditionError(
                f"branch {branch.branch_id}: unexpected effect state "
                f"{eff.state.value} on {eff.tool}"
            )
    branch.rolled_back = True


# Trigger: branch A got a 202 with no captured handle, then lost reconciliation.
a = Branch("A", [EffectRecord("payments.authorize_refund",
                              idempotent=False, fenced=False,
                              state=EffectState.PENDING_ACK)])
try:
    rollback(a, compensate=lambda h: None)
except RollbackPreconditionError as e:
    # Correct behavior: quarantine, do NOT mark rolled_back.
    print("quarantined:", e)
    assert not a.rolled_back
