# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-quorum-stall-when-a-byzantine-auditor-equivocates-across-the-prepare-and-commit-phases.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-quorum-stall-when-a-byzantine-auditor-equivocates-across-the-prepare-and-commit-phases.warrant.json
# Markdown SHA-256:   0b1c00de1e2e67922e538c169bf739015e35a07af207c4098ecce32d56255395
# Code AST SHA-256:   249d09da92e7723c6817ca2f2f11f67dd1c40939e1f0de2e364c77e26c04a9a7
# Verified Classes:   QuorumEquivocationError, Vote, PhaseBoundQuorum
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Tuple


class QuorumEquivocationError(RuntimeError):
    """Raised when a signer's phase-ordered vote history is inconsistent,
    or when detected equivocators exceed the fault budget f."""


@dataclass(frozen=True)
class Vote:
    proposal_id: str
    epoch: int
    phase: str          # "prepare" | "commit"
    decision: str       # "accept" | "reject"
    signer: str
    signature: bytes    # covers (proposal_id, epoch, phase, decision, signer)

    def signed_digest(self) -> Tuple:
        # Phase and epoch MUST be inside the signed digest, not envelope metadata.
        return (self.proposal_id, self.epoch, self.phase, self.decision, self.signer)


class PhaseBoundQuorum:
    def __init__(self, n: int, f: int):
        self.n, self.f = n, f
        self.threshold = 2 * f + 1
        # Single log keyed by (proposal, signer) preserving phase order.
        self._log: Dict[Tuple[str, str], List[Vote]] = {}
        self._equivocators: set = set()

    def _check_monotonic(self, prior: List[Vote], incoming: Vote) -> None:
        seen_phases = {v.phase for v in prior}
        if incoming.phase in seen_phases:
            raise QuorumEquivocationError(
                f"duplicate phase {incoming.phase!r} from {incoming.signer} "
                f"on {incoming.proposal_id} epoch {incoming.epoch}"
            )
        if prior and prior[-1].epoch > incoming.epoch:
            raise QuorumEquivocationError(
                f"epoch regression from {incoming.signer}: "
                f"{incoming.epoch} < {prior[-1].epoch}"
            )
        if prior and prior[-1].decision != incoming.decision:
            # Non-monotonic decision across phases => equivocation signal.
            self._equivocators.add(incoming.signer)
            raise QuorumEquivocationError(
                f"cross-phase decision flip by {incoming.signer} on "
                f"{incoming.proposal_id}: {prior[-1].decision} -> {incoming.decision}"
            )

    def record(self, vote: Vote) -> None:
        key = (vote.proposal_id, vote.signer)
        prior = self._log.get(key, [])
        self._check_monotonic(prior, vote)
        self._log[key] = prior + [vote]

    def tally(self, proposal_id: str, phase: str, epoch: int) -> int:
        signers = {
            s for (p, s), votes in self._log.items()
            if p == proposal_id
            and any(v.phase == phase and v.epoch == epoch and v.decision == "accept" for v in votes)
        }
        # Exclude any signer flagged as equivocating on this cohort.
        return len(signers - self._equivocators)

    def decide(self, proposal_id: str, epoch: int) -> str:
        if len(self._equivocators) > self.f:
            raise QuorumEquivocationError(
                f"fault budget exceeded: {len(self._equivocators)} distinct "
                f"equivocators > f={self.f}; abort and re-form cohort"
            )
        if self.tally(proposal_id, "prepare", epoch) < self.threshold:
            return "abstain"
        if self.tally(proposal_id, "commit", epoch) < self.threshold:
            return "abstain"
        return "commit"


def run_round(quorum: PhaseBoundQuorum, votes: List[Vote], proposal_id: str, epoch: int) -> str:
    for v in votes:
        try:
            quorum.record(v)
        except QuorumEquivocationError:
            # Exclude-and-continue while within fault budget; decide() enforces the cap.
            continue
    result = quorum.decide(proposal_id, epoch)
    if result == "commit" and quorum.tally(proposal_id, "commit", epoch) < quorum.threshold:
        raise QuorumEquivocationError(
            f"commit recorded below threshold after equivocation exclusion on {proposal_id}"
        )
    return result
