# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-agent-s-equivocated-commit-vote-as-a-first-class-ordering-hazard-rather-than-a-recoverable-me.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-agent-s-equivocated-commit-vote-as-a-first-class-ordering-hazard-rather-than-a-recoverable-me.warrant.json
# Markdown SHA-256:   f788408777b28cdd24e5a0a0cb9a983366eb47188d0726edc0b79ebf1d5bb69f
# Code AST SHA-256:   ac3d9c73d2246e9f2c77f34dfbc4cb024b882a875d00b74955da455735982093
# Verified Classes:   EquivocationOrderingHazard, Vote, QuorumCertifier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Tuple


class EquivocationOrderingHazard(RuntimeError):
    """Raised when one agent emits divergent well-formed votes for the same (task, slot, epoch)."""
    pass


@dataclass(frozen=True)
class Vote:
    agent_id: str
    task_id: str
    slot: int
    epoch: int
    decision_hash: str
    nonce: str


class QuorumCertifier:
    def __init__(self, quorum_size: int):
        self.quorum_size = quorum_size
        self._consumed_nonces: set[str] = set()

    def _key(self, v: Vote) -> Tuple[str, str, int, int]:
        return (v.agent_id, v.task_id, v.slot, v.epoch)

    def certify(self, votes: list[Vote]) -> str:
        # Step 1: bind votes to nonces; a re-used nonce is a re-vote and is rejected.
        for v in votes:
            if v.nonce in self._consumed_nonces:
                raise EquivocationOrderingHazard(
                    f"nonce {v.nonce} already consumed: agent {v.agent_id} "
                    f"attempted a second vote for slot {v.slot} epoch {v.epoch}"
                )

        # Step 2: duplicate-key divergence audit BEFORE counting toward quorum.
        seen: Dict[Tuple[str, str, int, int], str] = {}
        for v in votes:
            k = self._key(v)
            if k in seen and seen[k] != v.decision_hash:
                raise EquivocationOrderingHazard(
                    f"duplicate-key divergence on {k}: "
                    f"{seen[k]} vs {v.decision_hash}; force epoch bump, "
                    f"do not certify either quorum"
                )
            seen[k] = v.decision_hash

        if len(votes) < self.quorum_size:
            raise EquivocationOrderingHazard(
                f"quorum not reached: {len(votes)}/{self.quorum_size}"
            )

        for v in votes:
            self._consumed_nonces.add(v.nonce)
        return votes[0].decision_hash
