# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-byzantine-quorum-verdict-it-cannot-locally-re-derive-signed-warrant-replay-gaps-in-multi-agent-decision-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-byzantine-quorum-verdict-it-cannot-locally-re-derive-signed-warrant-replay-gaps-in-multi-agent-decision-consensus.warrant.json
# Markdown SHA-256:   85151e0ccf2a6fc9606b6bf9953453eb7864da59ab91660f976d0e5ba903a665
# Code AST SHA-256:   b1c805877cc803e8b0ca05c52364f7cc19a344f0f86376b3b6044340229118c0
# Verified Classes:   QuorumVerificationError, SignedVerdict, EpochBoundQuorumVerifier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Set, Tuple


class QuorumVerificationError(RuntimeError):
    """Raised when an attestational quorum cannot be safely accepted."""


@dataclass(frozen=True)
class SignedVerdict:
    signer: str
    decision_id: str
    epoch: int
    member_set_hash: str
    ballot: str


class EpochBoundQuorumVerifier:
    def __init__(self, committed_epoch: int, committed_hash: str, threshold: int):
        self.committed_epoch = committed_epoch
        self.committed_hash = committed_hash
        self.threshold = threshold
        self._seen: Dict[Tuple[str, str, int], str] = {}

    def accept(self, verdicts: list[SignedVerdict]) -> str:
        counted: Set[str] = set()
        for v in verdicts:
            # Invariant 1: signatures must be drawn from the verifier's epoch.
            if v.member_set_hash != self.committed_hash or v.epoch != self.committed_epoch:
                raise QuorumVerificationError(
                    f"stale-epoch warrant from {v.signer}: "
                    f"epoch={v.epoch} hash={v.member_set_hash} "
                    f"!= committed epoch={self.committed_epoch} hash={self.committed_hash}"
                )
            # Invariant 2: at most one ballot per (signer, decision, epoch).
            key = (v.signer, v.decision_id, v.epoch)
            prior = self._seen.get(key)
            if prior is not None and prior != v.ballot:
                raise QuorumVerificationError(
                    f"equivocation by {v.signer} on {v.decision_id}@{v.epoch}: "
                    f"{prior!r} vs {v.ballot!r}"
                )
            self._seen[key] = v.ballot
            counted.add(v.signer)

        # Invariant 3: quorum drawn from a single, verified epoch.
        if len(counted) < self.threshold:
            raise QuorumVerificationError(
                f"insufficient verified quorum: {len(counted)} < {self.threshold}"
            )
        return "committed"
