# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-quorum-certify-a-commit-when-the-byzantine-threshold-is-satisfied-only-by-agents-whose-votes-were-cast-against-a-different-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-quorum-certify-a-commit-when-the-byzantine-threshold-is-satisfied-only-by-agents-whose-votes-were-cast-against-a-different-task.warrant.json
# Markdown SHA-256:   7affec40f5ef92fa06afd90412defa734b335743080011c819c8182384505697
# Code AST SHA-256:   10dc05bc13080ac7c002fc258f744b376e3d80a8f834157f6116cb868cfe832d
# Verified Classes:   HeterogeneousCertificateError, Vote, Certificate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class HeterogeneousCertificateError(RuntimeError):
    """Raised when a commit certificate's epoch-coherent vote subset is below threshold."""


@dataclass(frozen=True)
class Vote:
    signer: str
    epoch: int
    proposal_hash: str
    signature: bytes


@dataclass(frozen=True)
class Certificate:
    epoch: int
    proposal_hash: str
    votes: tuple[Vote, ...]


def certify(
    epoch: int,
    proposal_hash: str,
    votes: Iterable[Vote],
    n: int,
    verify_sig,
) -> Certificate:
    f = (n - 1) // 3
    threshold = 2 * f + 1

    votes = tuple(votes)
    for v in votes:
        if not verify_sig(v):
            raise HeterogeneousCertificateError(
                f"invalid signature from {v.signer}"
            )

    coherent = tuple(
        v for v in votes
        if v.epoch == epoch and v.proposal_hash == proposal_hash
    )

    if len(coherent) < threshold:
        observed = {(v.epoch, v.proposal_hash) for v in votes}
        raise HeterogeneousCertificateError(
            f"epoch-coherent votes {len(coherent)} < threshold {threshold} "
            f"for (epoch={epoch}, proposal={proposal_hash[:8]}); "
            f"observed reference frames: {sorted(observed)}"
        )

    return Certificate(epoch=epoch, proposal_hash=proposal_hash, votes=coherent)
