# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-as-valid-when-the-vote-set-is-internally-consistent-but-the-witness-signatures-attest.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-as-valid-when-the-vote-set-is-internally-consistent-but-the-witness-signatures-attest.warrant.json
# Markdown SHA-256:   6caf24205906213d3ca3ab077c2050c93a8f5775ef6835aa6e63ff4f035713b8
# Code AST SHA-256:   32fbe7c61fc8972e721f22d29c1c05cb57367a6625a45abb1ef2a38fa6082057
# Verified Classes:   QuorumDigestDivergence, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from collections import defaultdict
from dataclasses import dataclass


class QuorumDigestDivergence(RuntimeError):
    """Raised when a vote set is signer-valid but not digest-coherent."""


@dataclass(frozen=True)
class Vote:
    signer: str
    decision_id: str
    label: str
    payload_digest: str
    signature_valid: bool


def canonical_digest(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()


def commit_quorum(votes: list[Vote], f: int, executed_payload: bytes) -> str:
    """Commit only if a single digest reaches 2f+1 distinct valid signers,
    and the executed payload hashes to that committed digest."""
    threshold = 2 * f + 1

    by_digest: dict[str, set[str]] = defaultdict(set)
    for v in votes:
        if not v.signature_valid:
            continue
        by_digest[v.payload_digest].add(v.signer)  # dedupe equivocating signers

    if len(by_digest) > 1:
        # Signer cardinality may pass, but the witness set is divergent.
        raise QuorumDigestDivergence(
            f"vote set spans {len(by_digest)} payload digests: "
            f"{ {d: len(s) for d, s in by_digest.items()} }; "
            "refusing to commit on signer cardinality alone"
        )

    (digest, signers), = by_digest.items()
    if len(signers) < threshold:
        raise QuorumDigestDivergence(
            f"digest {digest[:12]} has {len(signers)} signers, "
            f"threshold is {threshold}"
        )

    if canonical_digest(executed_payload) != digest:
        raise QuorumDigestDivergence(
            "executed payload does not hash to committed digest; "
            "aborting before tool-call side effects"
        )

    return digest
