# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-rollback-and-why-commit-order-inversion-makes-late-rollback-unsafe.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-rollback-and-why-commit-order-inversion-makes-late-rollback-unsafe.warrant.json
# Markdown SHA-256:   9762c2dc1fa4cfde9d08979607d379421ba4d88a6bb2c51e6f85e467dc7505f0
# Code AST SHA-256:   6cc3475754eaf3e9e641680e643f8e446a8b427948a8ee2bdaea57a570f00f0a
# Verified Classes:   CommitOrderInversion, Branch, Orchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class CommitOrderInversion(RuntimeError):
    """Raised when a stale, non-quiescent branch would be rolled back unsafely."""
    pass


@dataclass
class Branch:
    branch_id: str
    fork_epoch: int
    outstanding_timer: bool = False
    grants_revoked: bool = False
    poisoned: bool = False

    def is_quiescent(self) -> bool:
        # A branch in retry backoff is NOT quiescent.
        return not self.outstanding_timer and not self.grants_revoked


@dataclass
class Orchestrator:
    commit_epoch: int
    ledger: dict = field(default_factory=dict)

    def reclaim_branch(self, branch: Branch) -> str:
        if branch.fork_epoch > self.commit_epoch:
            raise CommitOrderInversion(
                f"branch {branch.branch_id} fork_epoch {branch.fork_epoch} "
                f"ahead of commit_epoch {self.commit_epoch}; commit pointer moved backward"
            )

        stale = branch.fork_epoch < self.commit_epoch

        if stale and not branch.is_quiescent():
            # Abort BEFORE rollback: revoke grants, poison epoch, refuse rollback record.
            branch.grants_revoked = True
            branch.poisoned = True
            self.ledger[branch.branch_id] = "aborted"
            raise CommitOrderInversion(
                f"branch {branch.branch_id} is stale (fork={branch.fork_epoch}, "
                f"commit={self.commit_epoch}) and non-quiescent; rollback unsafe, aborted"
            )

        self.ledger[branch.branch_id] = "rolled_back"
        return "rolled_back"


def drain_fork_set(orch: Orchestrator, branches: list[Branch], max_wait_s: float = 2.0) -> dict:
    deadline = time.monotonic() + max_wait_s
    results = {}
    for b in branches:
        while not b.is_quiescent() and time.monotonic() < deadline:
            time.sleep(0.05)
        results[b.branch_id] = orch.reclaim_branch(b)
    return results
