# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-from-quorum-when-byzantine-agents-return-valid-but-stale-tool-outputs-during-commitment-rounds.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-from-quorum-when-byzantine-agents-return-valid-but-stale-tool-outputs-during-commitment-rounds.warrant.json
# Markdown SHA-256:   b47a58b12c49e20e4b209a95354dbbd3127140b322ea2bd7f0f651a875f351cb
# Code AST SHA-256:   77af95400c31545c60e399ca20c46b70c60f17f280e5ad314db4694fd8564bda
# Verified Classes:   StaleQuorumVoteError, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleQuorumVoteError(RuntimeError):
    """Raised when a vote's fence token lags the round's max epoch and would corrupt quorum."""
    pass


@dataclass(frozen=True)
class Vote:
    agent_id: str
    value: int
    epoch: int
    signature: str


def commit_quorum(votes: list[Vote], quorum_size: int) -> int:
    if not votes:
        raise StaleQuorumVoteError("no votes received; cannot establish quorum epoch")

    max_epoch = max(v.epoch for v in votes)

    # Reject any vote whose observed epoch is not the round's max epoch.
    # A stale-but-valid vote must abstain, not count toward quorum.
    fresh = [v for v in votes if v.epoch == max_epoch]
    stale = [v for v in votes if v.epoch < max_epoch]

    if stale and len(fresh) < quorum_size:
        raise StaleQuorumVoteError(
            f"quorum unreachable at epoch {max_epoch}: "
            f"{len(fresh)} fresh votes, {len(stale)} stale votes discarded, "
            f"need {quorum_size}"
        )

    # Quorum must be computed over (value) among epoch-matched votes only.
    counts: dict[int, int] = {}
    for v in fresh:
        counts[v.value] = counts.get(v.value, 0) + 1

    winner, count = max(counts.items(), key=lambda kv: kv[1])
    if count < quorum_size:
        raise StaleQuorumVoteError(
            f"no value reached quorum at epoch {max_epoch}: "
            f"best={winner} with {count}/{quorum_size}"
        )
    return winner
