# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-equivocation-when-llm-agents-vote-on-shared-state-under-partial-synchrony.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-equivocation-when-llm-agents-vote-on-shared-state-under-partial-synchrony.warrant.json
# Markdown SHA-256:   23ecdb18ed1df37628ddd5bc487c1add5f36a3aafdc778169241b7d1d40e112a
# Code AST SHA-256:   bad6fcaf448b75162163cfc58f2161a4a1f8e4f676e326aabf752adc590a1fad
# Verified Classes:   QuorumEquivocationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class QuorumEquivocationError(RuntimeError):
    """Raised when a quorum certificate contains a duplicate voter for a round,
    or when two conflicting certificates both verify — the safety invariant
    (unique vote per agent per view/round) has been violated."""
    pass


def verify_certificate(cert, threshold):
    # cert: {"view": int, "round": int, "proposal_hash": str,
    #        "votes": [{"agent_id": str, "view": int, "round": int, "proposal_hash": str}]}
    seen = set()
    for vote in cert["votes"]:
        # Bind vote to the certificate's round, not the vote's claimed round.
        if (vote["view"], vote["round"]) != (cert["view"], cert["round"]):
            raise QuorumEquivocationError(
                f"vote from {vote['agent_id']} carries mismatched round "
                f"{vote['view']}/{vote['round']} vs cert {cert['view']}/{cert['round']}"
            )
        key = (vote["agent_id"], cert["view"], cert["round"])
        if key in seen:
            raise QuorumEquivocationError(
                f"agent {vote['agent_id']} voted twice in view {cert['view']} "
                f"round {cert['round']} (equivocation or un-fenced re-entry)"
            )
        seen.add(key)
    if len(seen) < threshold:
        raise QuorumEquivocationError(
            f"certificate has {len(seen)} distinct voters, threshold is {threshold}"
        )
    return True


def commit(certs, threshold):
    # certs: list of certificates for conflicting proposals in the same view/round
    validated = [c for c in certs if verify_certificate(c, threshold)]
    by_round = {}
    for c in validated:
        by_round.setdefault((c["view"], c["round"]), []).append(c)
    for (view, rnd), group in by_round.items():
        hashes = {c["proposal_hash"] for c in group}
        if len(hashes) > 1:
            # Two conflicting certs both verified in one round => protocol bug, halt.
            raise QuorumEquivocationError(
                f"conflicting certificates verified in view {view} round {rnd}: "
                f"{sorted(hashes)} — safety invariant broken, halting"
            )
    return validated[0]["proposal_hash"] if validated else None
