# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-an-auditor-whose-vote-it-cannot-re-derive-a-boundary-invariant-for-heterogeneous-bft-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-an-auditor-whose-vote-it-cannot-re-derive-a-boundary-invariant-for-heterogeneous-bft-consensus.warrant.json
# Markdown SHA-256:   1fbfab1cab7330f6a3fba02f387872b9bce9e6447ed65b77ee2731d3b1f10c24
# Code AST SHA-256:   16351593f14f0df37d386da9c39806e20f7aa930f9d2617e1e17827f14df3f15
# Verified Classes:   EquivocationInvariantError, SignedVote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, Tuple


class EquivocationInvariantError(RuntimeError):
    """Raised when a quorum component attempts to treat cross-family
    re-derivation disagreement as proof of Byzantine equivocation."""
    pass


@dataclass(frozen=True)
class SignedVote:
    auditor_id: str
    round: int
    evidence_digest: str  # H(sorted(tool_call_outputs)), committed with the vote
    verdict: str          # "APPROVE" | "REJECT"
    signature: str


def record_vote(ledger: Dict[Tuple[str, str], str], vote: SignedVote) -> None:
    """Bind (auditor_id, evidence_digest) -> verdict. Two distinct verdicts
    on the SAME digest is provable equivocation; anything else is not."""
    key = (vote.auditor_id, vote.evidence_digest)
    prior = ledger.get(key)
    if prior is not None and prior != vote.verdict:
        raise EquivocationInvariantError(
            f"PROVABLE equivocation: auditor {vote.auditor_id} signed "
            f"{prior!r} and {vote.verdict!r} on identical digest "
            f"{vote.evidence_digest}. Slash and exclude."
        )
    ledger[key] = vote.verdict


def classify_dissent(
    vote_a: SignedVote,
    vote_peer: SignedVote,
    peer_rederived_verdict: str,
) -> str:
    """Decide which fault regime a dissent falls into.

    Re-derivation disagreement is NEVER a slashing signal; it is honest
    cross-family divergence and must be absorbed by threshold slack.
    """
    if vote_a.evidence_digest != vote_peer.evidence_digest:
        # Distinct judgments on distinct evidence: not comparable.
        return "DISTINCT_JUDGMENTS"

    if vote_a.verdict != peer_rederived_verdict:
        # Same digest, different model family, different label.
        # This is the boundary. Treating it as malice breaks liveness.
        return "CROSS_FAMILY_DIVERGENCE"

    # Same digest, same verdict, but the peer's own signed vote differs.
    if vote_peer.verdict != vote_a.verdict:
        raise EquivocationInvariantError(
            f"Peer {vote_peer.auditor_id} signed {vote_peer.verdict!r} on "
            f"digest {vote_a.evidence_digest} while re-deriving "
            f"{peer_rederived_verdict!r}; digest-bound equivocation."
        )
    return "AGREEMENT"


def quorum_decision(
    votes: list[SignedVote],
    threshold: int,
    divergence_budget: float,
) -> str:
    """Threshold must be set with slack for honest divergence, not just f."""
    ledger: Dict[Tuple[str, str], str] = {}
    for v in votes:
        record_vote(ledger, v)  # raises on provable equivocation
    approves = sum(1 for v in votes if v.verdict == "APPROVE")
    if approves >= threshold:
        return "COMMIT"
    if divergence_budget < 0.0:
        raise EquivocationInvariantError(
            "negative divergence budget: quorum cannot absorb honest "
            "cross-family disagreement and will deadlock"
        )
    return "RETRY"
