# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-orphaned-branch-commits-from-resurrecting-after-speculative-multi-agent-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-orphaned-branch-commits-from-resurrecting-after-speculative-multi-agent-rollback.warrant.json
# Markdown SHA-256:   ef3faf2253c660c17ee9e3182e5a7a301064d88236a04218078d98ace88bbaac
# Code AST SHA-256:   0694fbf6301a5a67fc28827406cce8db0b94c1a27bbdff138d44a6f6b33a9f89
# Verified Classes:   ResurrectionFault, BranchState, Branch
# 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 ResurrectionFault(RuntimeError):
    """Raised when a winner commit would be serialized while a loser branch
    still has in-flight or unflushed side effects that could land afterward."""
    pass


class BranchState(Enum):
    RUNNING = "running"
    ABORTED = "aborted"      # cancellation flag set; NOT terminal
    QUIESCENT = "quiescent"  # terminal: no in-flight calls, no buffered writes
    DRAIN_TIMEOUT = "drain_timeout"


@dataclass
class Branch:
    name: str
    state: BranchState = BranchState.RUNNING
    in_flight_calls: int = 0
    buffered_writes: int = 0
    fence_token: str = ""

    def signal_abort(self) -> None:
        # Phase one: stop new dispatches. Does NOT await in-flight work.
        if self.state == BranchState.RUNNING:
            self.state = BranchState.ABORTED

    def drain(self, deadline_s: float) -> None:
        # Phase two: await in-flight calls and flush buffered writes.
        start = time.monotonic()
        while self.in_flight_calls > 0 or self.buffered_writes > 0:
            if time.monotonic() - start > deadline_s:
                self.state = BranchState.DRAIN_TIMEOUT
                return
            time.sleep(0.001)  # in production: await executor futures
            if self.in_flight_calls > 0:
                self.in_flight_calls -= 1  # simulated completion
        self.state = BranchState.QUIESCENT


def commit_winner(
    winner: Branch,
    losers: list[Branch],
    drain_deadline_s: float,
    serialize_commit: Callable[[Branch], None],
    reconcile_substrate: Callable[[], list[str]],
) -> None:
    # Two-phase abort: signal all losers, then drain all losers.
    for loser in losers:
        loser.signal_abort()
    for loser in losers:
        loser.drain(drain_deadline_s)

    # Invariant: winner commit is fenced behind universal loser quiescence.
    non_quiescent = [b for b in losers if b.state != BranchState.QUIESCENT]
    if non_quiescent:
        names = ", ".join(f"{b.name}:{b.state.value}" for b in non_quiescent)
        raise ResurrectionFault(
            f"refusing to serialize winner '{winner.name}'; "
            f"losers not quiescent: {names}. "
            f"Committing here risks orphaned branch commits resurrecting "
            f"after rollback."
        )

    serialize_commit(winner)

    # Post-commit reconciliation: any unexpected hunk is a hard fault.
    unexpected = reconcile_substrate()
    if unexpected:
        raise ResurrectionFault(
            f"post-commit substrate contains unexpected hunks: {unexpected}. "
            f"Fence token may have failed; roll back entire speculative txn."
        )
