# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-quorum-it-helped-form-equivocation-tolerant-voting-under-heterogeneous-model-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-quorum-it-helped-form-equivocation-tolerant-voting-under-heterogeneous-model-drift.warrant.json
# Markdown SHA-256:   fe181ab437062fd21397bb8dfd298a7a17de23efdf1ba96403dd4d634e587d85
# Code AST SHA-256:   a101eb9de4cc2111115ca112d790dd2ff2a8e093f3892c797399888af476e52f
# Verified Classes:   EquivocationFault, Vote
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Iterable


class EquivocationFault(RuntimeError):
    """Raised when a vote cannot be bound to a single canonical proposal digest."""


@dataclass(frozen=True)
class Vote:
    voter_id: str
    proposal_hash: str
    decision: str            # "ACCEPT" | "REJECT"
    model_fingerprint: str   # base model + prompt-version hash + tool-set hash
    decode_params: str       # e.g. "temp=0.7;top_p=0.95"
    epoch_nonce: str         # per-voter, per-epoch; detects double-signing


def canonical_hash(body: dict) -> str:
    # Stable key order, no whitespace, fixed float repr: semantically identical
    # plans must hash identically or heterogeneity guarantees equivocation.
    canonical = json.dumps(body, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def admit_votes(
    votes: Iterable[Vote],
    proposal_body: dict,
    registered: dict[str, tuple[str, str]],  # voter_id -> (fingerprint, decode_params)
    f: int,
) -> list[Vote]:
    target = canonical_hash(proposal_body)
    admitted: list[Vote] = []
    seen_nonce: dict[tuple[str, str], str] = {}

    for v in votes:
        if v.decision != "ACCEPT":
            continue
        # 1. Bind to canonical digest, not to voter identity alone.
        if v.proposal_hash != target:
            raise EquivocationFault(
                f"voter {v.voter_id} signed {v.proposal_hash!r} "
                f"but canonical proposal is {target!r}"
            )
        # 2. Bind to registered configuration; mid-epoch drift invalidates.
        if v.voter_id not in registered:
            raise EquivocationFault(f"unregistered voter {v.voter_id}")
        fp, dp = registered[v.voter_id]
        if (v.model_fingerprint, v.decode_params) != (fp, dp):
            raise EquivocationFault(
                f"voter {v.voter_id} config drift: "
                f"{(v.model_fingerprint, v.decode_params)} != {(fp, dp)}"
            )
        # 3. Detect true double-signing within the epoch.
        key = (v.voter_id, v.epoch_nonce)
        if key in seen_nonce and seen_nonce[key] != v.proposal_hash:
            raise EquivocationFault(
                f"voter {v.voter_id} equivocated in epoch: "
                f"{seen_nonce[key]!r} vs {v.proposal_hash!r}"
            )
        seen_nonce[key] = v.proposal_hash
        admitted.append(v)

    if len(admitted) < 2 * f + 1:
        raise EquivocationFault(
            f"quorum not met after strict binding: "
            f"{len(admitted)} < {2 * f + 1}"
        )
    return admitted
