# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-before-its-rollback-barrier-is-acknowledged.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-before-its-rollback-barrier-is-acknowledged.warrant.json
# Markdown SHA-256:   592a31dc2322aa1507d5a111699b02839fedd7d8c0d8615c8e0d8872c2f2d75b
# Code AST SHA-256:   e5f184668e7a06159c5095eed66d4dcf07e9e4d70438421656b824b69fbebf00
# Verified Classes:   AckState, RollbackBarrierViolation, DispatchEntry, DispatchLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set


class AckState(Enum):
    PENDING = "pending"
    ACKED = "acked"
    CANCELLED = "cancelled"
    RETRY_SHADOW = "retry_shadow"  # peer re-dispatched after cancel


class RollbackBarrierViolation(RuntimeError):
    """Raised when re-commit is attempted while escaped side effects are unresolved."""
    pass


@dataclass
class DispatchEntry:
    branch_id: str
    call_id: str
    peer_id: str
    state: AckState = AckState.PENDING


@dataclass
class DispatchLedger:
    entries: Dict[str, DispatchEntry] = field(default_factory=dict)
    epoch: int = 0

    def record_dispatch(self, branch_id: str, call_id: str, peer_id: str) -> None:
        self.entries[call_id] = DispatchEntry(branch_id, call_id, peer_id)

    def mark(self, call_id: str, state: AckState) -> None:
        if call_id not in self.entries:
            raise RollbackBarrierViolation(f"unknown call_id {call_id}")
        self.entries[call_id].state = state

    def unresolved_for_epoch(self) -> Set[str]:
        return {
            cid for cid, e in self.entries.items()
            if e.state in (AckState.PENDING, AckState.RETRY_SHADOW)
        }


def gate_recommit(ledger: DispatchLedger, survivor_branch: str, aborted: Set[str]) -> None:
    """Re-commit is legal only when every escaped call is terminal."""
    # Any aborted branch with a PENDING or RETRY_SHADOW call blocks the gate.
    for cid in ledger.unresolved_for_epoch():
        entry = ledger.entries[cid]
        if entry.branch_id in aborted:
            raise RollbackBarrierViolation(
                f"branch {entry.branch_id} aborted but call {cid} on peer "
                f"{entry.peer_id} is {entry.state.value}; re-commit of "
                f"{survivor_branch} would land under a zombie side effect"
            )
    # Survivor's own outstanding calls must also be terminal before it commits.
    for cid, entry in ledger.entries.items():
        if entry.branch_id == survivor_branch and entry.state is AckState.PENDING:
            raise RollbackBarrierViolation(
                f"survivor {survivor_branch} has unacked call {cid}"
            )


# --- failure trace reproduction ---
ledger = DispatchLedger(epoch=41)
ledger.record_dispatch("C", "call-7", "peer-writer")
ledger.record_dispatch("B", "call-9", "peer-writer")
ledger.mark("call-9", AckState.ACKED)

# C aborts; orchestrator issues cancel, but peer's retry policy re-dispatches.
ledger.mark("call-7", AckState.RETRY_SHADOW)

# Naive orchestrator would re-commit B here; the gate refuses.
try:
    gate_recommit(ledger, survivor_branch="B", aborted={"A", "C"})
except RollbackBarrierViolation as exc:
    print(f"BLOCKED: {exc}")
    # Escalate to full-epoch abort or wait for call-7 terminal.
