# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-sub-agent-s-vote-as-byzantine-rather-than-merely-slow-in-bft-plan-commitment-protocols.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-sub-agent-s-vote-as-byzantine-rather-than-merely-slow-in-bft-plan-commitment-protocols.warrant.json
# Markdown SHA-256:   76be8af2fc1aa0b2cb71abd2492506dda6c2884f57db606c2601039962b5121d
# Code AST SHA-256:   72d5de2acc5f9f23c5df6162c5fa9638ccbc24cdb134e8cf66da9b77622287a9
# Verified Classes:   ByzantineMisclassificationError, Vote, CoordinatorState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ByzantineMisclassificationError(RuntimeError):
    """Raised when a stale (memory-truncated) vote is wrongly excluded as Byzantine,
    silently shrinking the quorum set below the safety threshold."""
    pass


@dataclass(frozen=True)
class Vote:
    agent_id: str
    view_epoch: int
    plan_digest: str
    signature: str


@dataclass
class CoordinatorState:
    current_view: int
    current_digest: str
    n_agents: int
    f_tolerance: int
    counted: dict          # agent_id -> Vote admitted to current quorum
    excluded: dict         # agent_id -> list[Vote] proving equivocation

    def quorum_threshold(self) -> int:
        # PBFT-style: need 2f+1 to commit, and counted set must stay >= this
        return 2 * self.f_tolerance + 1


def classify_and_admit(state: CoordinatorState, vote: Vote) -> str:
    # 1. Stale epoch: memory-truncation artifact, NOT Byzantine.
    if vote.view_epoch < state.current_view:
        return "STALE_REFRESH"  # re-request; do not count, do not exclude

    # 2. Future epoch: protocol desync, also not Byzantine.
    if vote.view_epoch > state.current_view:
        return "DESYNC_REJECT"

    # 3. Same epoch, matching digest: honest, admit.
    if vote.plan_digest == state.current_digest:
        state.counted[vote.agent_id] = vote
        return "ADMITTED"

    # 4. Same epoch, conflicting digest: candidate equivocation.
    prior = state.excluded.get(vote.agent_id, [])
    if any(p.plan_digest != vote.plan_digest for p in prior):
        # Two conflicting signatures in one epoch => genuine Byzantine proof.
        state.excluded.setdefault(vote.agent_id, []).append(vote)
        state.counted.pop(vote.agent_id, None)
        # Exclusion shrinks the set; threshold MUST be recomputed, never kept.
        remaining = len(state.counted)
        if remaining < state.quorum_threshold():
            raise ByzantineMisclassificationError(
                f"Excluding {vote.agent_id} as Byzantine leaves {remaining} "
                f"counted agents, below quorum threshold "
                f"{state.quorum_threshold()}; safety invariant violated. "
                f"Recompute threshold or halt commit."
            )
        return "EXCLUDED_BYZANTINE"

    # 5. First conflicting-digest sighting: record but do not yet exclude.
    state.excluded.setdefault(vote.agent_id, []).append(vote)
    return "SUSPECT_AWAIT_PROOF"
