# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-quorum-boundary-when-byzantine-auditors-vote-over-non-deterministic-llm-outputs.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-quorum-boundary-when-byzantine-auditors-vote-over-non-deterministic-llm-outputs.warrant.json
# Markdown SHA-256:   890ac569f77abdd7971bbd313400fef0b6b868f452427dc5a930d9065ff1bea4
# Code AST SHA-256:   fe3a63ecb6fcb1a180d41f8c41187dca3f1099869595ff98bc0def3a68a32eef
# Verified Classes:   QuorumIntegrityError, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QuorumIntegrityError(RuntimeError):
    """Raised when a BFT ballot set adjudicates non-identical objects."""
    pass


@dataclass(frozen=True)
class Vote:
    auditor_id: str
    artifact_hash: str
    spec_hash: str
    verdict: str  # "ACCEPT" | "REJECT"
    cited_clause: str | None


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


def tally_quorum(
    votes: list[Vote],
    candidate_hash: str,
    spec_hash: str,
    f: int,
) -> str:
    # Guardrail: every counted vote must reference the pinned artifact and spec.
    # A single drifted vote can be the decisive f+1 reject, so we void the ballot.
    for v in votes:
        if v.artifact_hash != candidate_hash:
            raise QuorumIntegrityError(
                f"auditor {v.auditor_id} voted on artifact {v.artifact_hash[:12]}, "
                f"candidate is {candidate_hash[:12]} — regeneration drift, ballot void"
            )
        if v.spec_hash != spec_hash:
            raise QuorumIntegrityError(
                f"auditor {v.auditor_id} adjudicated spec {v.spec_hash[:12]}, "
                f"pinned spec is {spec_hash[:12]} — predicate divergence, ballot void"
            )
        if v.verdict not in ("ACCEPT", "REJECT"):
            raise QuorumIntegrityError(
                f"auditor {v.auditor_id} returned non-binary verdict {v.verdict!r}"
            )

    accepts = sum(1 for v in votes if v.verdict == "ACCEPT")
    rejects = sum(1 for v in votes if v.verdict == "REJECT")

    if rejects >= f + 1:
        return "REJECT"
    if accepts >= 2 * f + 1:
        return "COMMIT"
    raise QuorumIntegrityError(
        f"no quorum: accepts={accepts}, rejects={rejects}, f={f} — "
        f"insufficient agreement over pinned artifact"
    )
