# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-before-the-consensus-quorum-has-fully-drained-its-in-flight-votes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-before-the-consensus-quorum-has-fully-drained-its-in-flight-votes.warrant.json
# Markdown SHA-256:   e4a83ff4107d11d9a3390f3782dae6af2c90e7806213bf008265596e0aed10bd
# Code AST SHA-256:   d03736f0dff90697187c8262b11eaea961057d27ad2eb8180312056272b15270
# Verified Classes:   ConsensusCommitError, BranchState, Branch, ConsensusReconciler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ConsensusCommitError(RuntimeError):
    """Raised when a branch attempts to commit while dissent votes are still in flight."""
    pass


class BranchState(Enum):
    SPECULATIVE = "speculative"
    PREPARED = "prepared"
    COMMITTED = "committed"
    ROLLED_BACK = "rolled_back"


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.SPECULATIVE
    accepts: int = 0
    rejects: int = 0
    in_flight_votes: Set[str] = field(default_factory=set)
    commit_ts: float = 0.0
    last_vote_ts: float = 0.0


class ConsensusReconciler:
    def __init__(self, auditor_ids: Set[str], quorum: int):
        self.auditor_ids = auditor_ids
        self.quorum = quorum
        self.branches: Dict[str, Branch] = {}

    def propose(self, branch_id: str) -> Branch:
        b = Branch(branch_id=branch_id)
        b.in_flight_votes = set(self.auditor_ids)
        self.branches[branch_id] = b
        return b

    def record_vote(self, branch_id: str, auditor_id: str, accept: bool) -> None:
        b = self.branches[branch_id]
        b.in_flight_votes.discard(auditor_id)
        b.last_vote_ts = time.monotonic()
        if accept:
            b.accepts += 1
        else:
            b.rejects += 1
        if b.state == BranchState.COMMITTED and not accept:
            # Late dissent against a committed branch: memory poisoning.
            raise ConsensusCommitError(
                f"late reject for committed branch {branch_id} from {auditor_id}; "
                f"commit_ts={b.commit_ts}, vote_ts={b.last_vote_ts}, "
                f"provenance must be invalidated"
            )

    def try_commit(self, branch_id: str) -> None:
        b = self.branches[branch_id]
        if b.accepts < self.quorum:
            return
        # Guardrail: refuse commit while any vote is still in flight.
        if b.in_flight_votes:
            raise ConsensusCommitError(
                f"branch {branch_id} reached quorum ({b.accepts}/{self.quorum}) "
                f"but {len(b.in_flight_votes)} votes still in flight: "
                f"{sorted(b.in_flight_votes)}; refusing commit"
            )
        if b.rejects > 0:
            b.state = BranchState.ROLLED_BACK
            return
        b.state = BranchState.COMMITTED
        b.commit_ts = time.monotonic()
