# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-parallel-branch-has-committed-an-irreversible-external-side-effect-before-rollback-when-the-orchestrato.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-parallel-branch-has-committed-an-irreversible-external-side-effect-before-rollback-when-the-orchestrato.warrant.json
# Markdown SHA-256:   e1bf9614dc49e515d22c5bc7e443a1b79ab286311f4dfef2808e500e27f4ee54
# Code AST SHA-256:   34f4fb7d96cf7c94fdda8b84c640d2a10efd8cb023ee0c82a37e67e449f551e0
# Verified Classes:   Reversibility, LedgerState, SpeculativeRollbackError, Dispatch, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional


class Reversibility(Enum):
    REVERSIBLE = "reversible"
    IDEMPOTENT = "idempotent"
    TERMINAL = "terminal"  # capture_payment, send_email, etc.


class LedgerState(Enum):
    DISPATCHED = "dispatched"
    PENDING = "pending"      # in-flight, remote outcome UNKNOWN
    APPLIED = "applied"      # remote acknowledged committed
    REVERTED = "reverted"    # orchestrator claims clean -- must be truthful
    QUARANTINED = "quarantined"  # indeterminate-dirty, awaiting reconciliation


class SpeculativeRollbackError(RuntimeError):
    """Raised when a branch would be declared clean while an in-flight
    dispatch to a terminal tool may already have committed externally."""


@dataclass
class Dispatch:
    dispatch_id: str
    tool: str
    reversibility: Reversibility
    dispatched_at: float
    acked: bool = False
    acked_committed: bool = False


@dataclass
class Branch:
    branch_id: str
    ledger_state: LedgerState = LedgerState.DISPATCHED
    dispatches: Dict[str, Dispatch] = field(default_factory=dict)

    def in_flight(self) -> List[Dispatch]:
        return [d for d in self.dispatches.values()
                if not d.acked and d.reversibility == Reversibility.TERMINAL]


def rollback_branch(branch: Branch, now: float) -> LedgerState:
    """Attempt to roll back a losing speculative branch.

    The invariant enforced here: a branch may be written REVERTED only if
    it has no outstanding dispatch whose remote outcome is unknown. A
    PENDING branch with an in-flight TERMINAL dispatch is indeterminate,
    not clean, and must be quarantined for reconciliation.
    """
    if branch.ledger_state == LedgerState.APPLIED:
        if branch.dispatches and all(
            d.reversibility == Reversibility.TERMINAL for d in branch.dispatches.values()
        ):
            raise SpeculativeRollbackError(
                f"branch {branch.branch_id} is APPLIED on a TERMINAL tool; "
                f"rollback requires out-of-band compensation, not ledger revert"
            )
        branch.ledger_state = LedgerState.REVERTED
        return branch.ledger_state

    if branch.ledger_state == LedgerState.PENDING:
        outstanding = branch.in_flight()
        if outstanding:
            # The exact boundary: do NOT write REVERTED. Quarantine.
            branch.ledger_state = LedgerState.QUARANTINED
            raise SpeculativeRollbackError(
                f"branch {branch.branch_id} has {len(outstanding)} in-flight "
                f"TERMINAL dispatch(es) {[d.dispatch_id for d in outstanding]}; "
                f"outcome unknown at t={now:.3f}, refusing to declare clean"
            )
        branch.ledger_state = LedgerState.REVERTED
        return branch.ledger_state

    raise SpeculativeRollbackError(
        f"branch {branch.branch_id} in unexpected state {branch.ledger_state}"
    )


def reconcile_quarantined(branch: Branch, ack_timeout: float) -> LedgerState:
    """Resolve a quarantined branch against the remote system of record.
    Returns DIRTY (compensate) or CLEAN (truthful revert)."""
    deadline = time.monotonic() + ack_timeout
    while time.monotonic() < deadline:
        if all(d.acked for d in branch.dispatches.values()):
            if any(d.acked_committed for d in branch.dispatches.values()):
                # External effect committed after we declared rollback.
                branch.ledger_state = LedgerState.APPLIED
                return branch.ledger_state  # caller must compensate
            branch.ledger_state = LedgerState.REVERTED
            return branch.ledger_state
        time.sleep(0.05)
    # Timeout: still indeterminate. Never promote to REVERTED on timeout.
    raise SpeculativeRollbackError(
        f"branch {branch.branch_id} reconciliation timed out after "
        f"{ack_timeout:.2f}s; remains QUARANTINED, resolution event suppressed"
    )
