# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-quorum-attestation-divergence-as-a-byzantine-equivocation-rather-than-benign-latency-skew-in-multi-agent-deci.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-quorum-attestation-divergence-as-a-byzantine-equivocation-rather-than-benign-latency-skew-in-multi-agent-deci.warrant.json
# Markdown SHA-256:   81e21cdf3dfb7acc6ec2ca7c364249e6e3e47275a0f7e2a573df25aae488a9e3
# Code AST SHA-256:   5916e664de083938c253d41df1958267a4ddd7dcc39fddd91cc98ab29a6d9cb8
# Verified Classes:   QuorumEquivocationError, Commitment, Attestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class QuorumEquivocationError(RuntimeError):
    """Raised when a voter's per-epoch attestation set is not unique.

    This is the Byzantine equivocation fault: the voter emitted two
    validly-signed attestations with different nonces and different
    verdicts for the same epoch. The quorum cannot be committed over
    this voter's attestation, and the epoch must be re-run with the
    voter excluded.
    """


@dataclass(frozen=True)
class Commitment:
    epoch: int
    voter_id: str
    nonce: str
    verdict_hash: str

    def digest(self) -> str:
        raw = f"{self.epoch}|{self.voter_id}|{self.nonce}|{self.verdict_hash}"
        return hashlib.sha256(raw.encode()).hexdigest()


@dataclass(frozen=True)
class Attestation:
    epoch: int
    voter_id: str
    nonce: str
    verdict: str
    proposal_hash: str
    sig: str


def verify_epoch_uniqueness(
    epoch: int,
    commitments: Dict[str, Commitment],
    attestations: List[Attestation],
) -> Dict[str, Attestation]:
    """Return the unique attestation per voter for the epoch, or raise.

    The collector's received subset is NOT trusted as the quorum.
    Uniqueness is checked against the pre-broadcast commitment set,
    which is gathered from gossip peers independent of collector routing.
    """
    by_voter: Dict[str, List[Attestation]] = {}
    for att in attestations:
        if att.epoch != epoch:
            continue
        by_voter.setdefault(att.voter_id, []).append(att)

    resolved: Dict[str, Attestation] = {}
    for voter_id, atts in by_voter.items():
        commitment = commitments.get(voter_id)
        if commitment is None:
            # No pre-broadcast commitment: protocol violation.
            # Cannot distinguish equivocation from benign re-emission.
            raise QuorumEquivocationError(
                f"voter {voter_id} epoch {epoch}: no commitment present; "
                f"uniqueness unverifiable, refusing to commit"
            )

        distinct_nonces = {a.nonce for a in atts}
        if len(distinct_nonces) == 1:
            # Single nonce: benign (possibly re-emitted). Dedupe.
            resolved[voter_id] = atts[0]
            continue

        # Multiple nonces for one epoch. Check whether verdicts differ.
        distinct_verdicts = {a.verdict for a in atts}
        if len(distinct_verdicts) == 1:
            # Same verdict, different nonce: benign retry. Keep commitment-bound one.
            bound = [a for a in atts if a.nonce == commitment.nonce]
            if not bound:
                raise QuorumEquivocationError(
                    f"voter {voter_id} epoch {epoch}: retry nonce does not match "
                    f"commitment nonce {commitment.nonce}"
                )
            resolved[voter_id] = bound[0]
            continue

        # Different nonces AND different verdicts: equivocation.
        raise QuorumEquivocationError(
            f"voter {voter_id} epoch {epoch}: equivocation detected — "
            f"nonces {sorted(distinct_nonces)} carry verdicts "
            f"{sorted(distinct_verdicts)}; epoch must be re-run with voter excluded"
        )

    return resolved


def commit_quorum(
    epoch: int,
    commitments: Dict[str, Commitment],
    attestations: List[Attestation],
    *,
    n: int,
    threshold: int,
) -> str:
    """Commit a quorum decision only over the verified-unique attestation set."""
    try:
        resolved = verify_epoch_uniqueness(epoch, commitments, attestations)
    except QuorumEquivocationError:
        # Do not commit. Escalate to epoch re-run with offending voter excluded.
        raise

    approvals = [v for v, a in resolved.items() if a.verdict == "approve"]
    if len(approvals) < threshold:
        raise QuorumEquivocationError(
            f"epoch {epoch}: threshold not met after uniqueness verification "
            f"({len(approvals)}/{threshold} approvals over {len(resolved)} unique voters)"
        )
    return f"epoch {epoch}: committed over {len(approvals)} unique approvals"
