# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-quorum-equivocation-when-byzantine-agents-return-divergent-votes-across-concurrent-decision-rounds.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-quorum-equivocation-when-byzantine-agents-return-divergent-votes-across-concurrent-decision-rounds.warrant.json
# Markdown SHA-256:   401fc0a391038bad7aa8b516d4ff9b2f33cf883180e66f550e56325463eca396
# Code AST SHA-256:   3a64bc3e4a6ebbb9a1b87759210c370eefe8ed06618cc0217581224b81b47444
# Verified Classes:   QuorumEquivocationError, Vote, SignatureIndex
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class QuorumEquivocationError(RuntimeError):
    """Raised when a quorum's signers cannot be proven single-voting."""


@dataclass
class Vote:
    agent_id: str
    epoch: int
    proposal_hash: str
    signature: str  # assumed validly signed over (epoch, proposal_hash)


@dataclass
class SignatureIndex:
    # agent_id -> epoch -> set of proposal hashes it has signed
    records: dict = field(default_factory=dict)

    def record(self, v: Vote) -> None:
        self.records.setdefault(v.agent_id, {}).setdefault(v.epoch, set()).add(
            v.proposal_hash
        )


def verify_quorum_safety(
    quorum: list[Vote],
    index: SignatureIndex,
    n: int,
    f: int,
    threshold: int,
) -> None:
    # Static arithmetic invariant: any two quorums must intersect in > f members.
    if 2 * threshold <= n + f:
        raise QuorumEquivocationError(
            f"threshold {threshold} too small for N={n}, f={f}: "
            "quorum intersection cannot guarantee an honest member"
        )

    if len(quorum) < threshold:
        raise QuorumEquivocationError(
            f"quorum cardinality {len(quorum)} < threshold {threshold}"
        )

    for v in quorum:
        prior = index.records.get(v.agent_id, {}).get(v.epoch)
        if prior is None:
            # Cold-start gap: honest agent indistinguishable from equivocator.
            raise QuorumEquivocationError(
                f"agent {v.agent_id} has no durable vote record for epoch "
                f"{v.epoch}; safety unverifiable, require fresh epoch"
            )
        if len(prior) > 1:
            raise QuorumEquivocationError(
                f"PROVEN equivocation: agent {v.agent_id} signed "
                f"{sorted(prior)} in epoch {v.epoch}"
            )
        if v.proposal_hash not in prior:
            raise QuorumEquivocationError(
                f"agent {v.agent_id} vote hash {v.proposal_hash} not in "
                f"durable record {prior}"
            )


def commit_round(
    quorum: list[Vote], index: SignatureIndex, n: int, f: int, threshold: int
) -> str:
    verify_quorum_safety(quorum, index, n, f, threshold)
    # All signers verified single-voting; safe to commit.
    return hashlib.sha256(
        b"".join(v.signature.encode() for v in sorted(quorum, key=lambda x: x.agent_id))
    ).hexdigest()
