# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-quorum-bound-agent-cluster-accept-a-decision-that-no-honest-majority-ever-voted-for.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-quorum-bound-agent-cluster-accept-a-decision-that-no-honest-majority-ever-voted-for.warrant.json
# Markdown SHA-256:   b380ebdc32a5c0357ababd69f6c8a63d6b88861fd71edbb7ddf283705769a0dc
# Code AST SHA-256:   60e84c73cbc98431fec840e88039cc95d821fd96f5bc72ea786523f9d7b64368
# Verified Classes:   QuorumIdentityCollapse, Ballot, CommitCertificate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class QuorumIdentityCollapse(RuntimeError):
    """Raised when a commit certificate's distinct-signer set falls below threshold,
    even though the raw ballot count meets it. Indicates retry-amplified double-voting."""


@dataclass(frozen=True)
class Ballot:
    signer: str          # public key / agent id
    round_no: int
    op_hash: str         # H(op) — must be in the dedup key
    nonce: str           # differs on retry; must NOT be in the dedup key
    vote: str            # "PREPARE" | "REJECT"
    sig: str             # covers (signer, round_no, op_hash, nonce, vote)

    def dedup_key(self) -> tuple:
        # The safety-critical choice: nonce is excluded so retries collapse.
        return (self.signer, self.round_no, self.op_hash)


@dataclass
class CommitCertificate:
    round_no: int
    op_hash: str
    ballots: list = field(default_factory=list)   # full ballots, never pre-aggregated


def verify_certificate(cert: CommitCertificate, threshold: int) -> set:
    """Return the distinct-signer set that actually supports the commit.
    Raises QuorumIdentityCollapse if the signer set is below threshold."""
    seen = {}
    for b in cert.ballots:
        if b.round_no != cert.round_no or b.op_hash != cert.op_hash:
            continue
        if b.vote != "PREPARE":
            continue
        # Signature check omitted for brevity; assume verify_sig(b) passed.
        key = b.dedup_key()
        if key not in seen:
            seen[key] = b
        # else: duplicate ballot from same signer for same (round, op) — discarded.

    distinct_signers = {k[0] for k in seen}
    if len(distinct_signers) < threshold:
        raise QuorumIdentityCollapse(
            f"round={cert.round_no} op={cert.op_hash[:8]} "
            f"raw_ballots={len(cert.ballots)} distinct_signers={len(distinct_signers)} "
            f"threshold={threshold} — quorum met by count, not by identity"
        )
    return distinct_signers


def commit(cert: CommitCertificate, threshold: int) -> str:
    signers = verify_certificate(cert, threshold)
    return hashlib.sha256(
        (cert.op_hash + "|" + ",".join(sorted(signers))).encode()
    ).hexdigest()
