# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-fence-speculative-rollback-before-committing-a-reconciled-branch.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-fence-speculative-rollback-before-committing-a-reconciled-branch.warrant.json
# Markdown SHA-256:   ce7d7d54c061a60bb9d50452c1137ebf016b47cdada1b11ff9e34ed2e9f71971
# Code AST SHA-256:   188fa839ef5509832f2b23050c0e7864e5af951152727b5609552a1a04f32128
# Verified Classes:   RollbackFenceError, BranchState, SpeculativeBranch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class RollbackFenceError(RuntimeError):
    """Raised when reconciliation is attempted against unquiesced branch state."""
    pass


class BranchState(Enum):
    RUNNING = "running"
    ABORTED = "aborted"          # scheduling label only — NOT safe to merge past
    QUIESCED = "quiesced"        # all side effects cancelled or compensated
    COMMITTED = "committed"


@dataclass
class SpeculativeBranch:
    branch_id: str
    state: BranchState = BranchState.RUNNING
    in_flight_ops: list = field(default_factory=list)
    compensations: list = field(default_factory=list)


def abort_branch(branch: SpeculativeBranch) -> None:
    """Phase one: mark aborted and request cancellation of in-flight ops."""
    branch.state = BranchState.ABORTED
    for op in branch.in_flight_ops:
        op.request_cancel()


def quiesce_branch(branch: SpeculativeBranch, deadline_s: float = 2.0) -> None:
    """Phase two: wait for cancellations to ack, then compensate. Must reach QUIESCED."""
    start = time.monotonic()
    for op in branch.in_flight_ops:
        while not op.is_terminal():
            if time.monotonic() - start > deadline_s:
                raise RollbackFenceError(
                    f"branch {branch.branch_id}: op {op!r} failed to quiesce "
                    f"within {deadline_s}s — reconciliation unsafe"
                )
            time.sleep(0.01)
        # A cancelled op may still have leaked a write; compensate it.
        if op.leaked_side_effect:
            branch.compensations.append(op.compensate())
    branch.state = BranchState.QUIESCED


def reconcile(commit_branch: SpeculativeBranch,
              aborted: list[SpeculativeBranch],
              read_shared_store: Callable[[], dict]) -> dict:
    """Merge only after every aborted branch is provably quiesced."""
    for b in aborted:
        if b.state is not BranchState.QUIESCED:
            raise RollbackFenceError(
                f"branch {b.branch_id} in state {b.state.value}; "
                f"refusing to reconcile against unquiesced state"
            )
    # Snapshot is taken after the quiescence barrier — no late writes can race it.
    snapshot = read_shared_store()
    return {"commit": commit_branch.branch_id, "context": snapshot}


def run_speculative_group(branches: list[SpeculativeBranch],
                          commit_id: str,
                          read_shared_store: Callable[[], dict]) -> dict:
    commit = next(b for b in branches if b.branch_id == commit_id)
    aborted = [b for b in branches if b.branch_id != commit_id]
    for b in aborted:
        abort_branch(b)
    for b in aborted:
        quiesce_branch(b)  # may raise RollbackFenceError -> fail closed
    return reconcile(commit, aborted, read_shared_store)
