# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-when-llm-agent-quorums-commit-shared-state-under-byzantine-peers.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-when-llm-agent-quorums-commit-shared-state-under-byzantine-peers.warrant.json
# Markdown SHA-256:   c91f97578bcdecde9cb884104e57adb8109cb0ff978c28fb2030f3d126f4ccf2
# Code AST SHA-256:   88f63a4143f0afd6ba83baf3936ad624ea5470d28af75d52b40d0f48796f627f
# Verified Classes:   EquivocationCollapse, Commitment
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationCollapse(RuntimeError):
    """Raised when a quorum would commit on commitments that cannot be
    distinguished from equivocation, or when an identity-bound digest
    invariant is violated at the commitment boundary."""


@dataclass(frozen=True)
class Commitment:
    identity: str
    proposal_hash: str
    epoch: int
    salt: str
    digest: str  # H(proposal_hash || identity || epoch || salt)


def make_commitment(identity: str, proposal_hash: str, epoch: int, salt: str) -> Commitment:
    payload = f"{proposal_hash}|{identity}|{epoch}|{salt}".encode()
    return Commitment(identity, proposal_hash, epoch, salt, hashlib.sha256(payload).hexdigest())


def tally_quorum(commitments: list[Commitment], proposal_hash: str, epoch: int,
                 quorum: int, validator_set: set[str]) -> str:
    """Count identity-bound digests. Any identity emitting two distinct digests
    for the same (proposal_hash, epoch) is treated as equivocating — including
    benign re-sampling, because the protocol cannot distinguish them."""
    seen: dict[str, str] = {}
    for c in commitments:
        if c.proposal_hash != proposal_hash or c.epoch != epoch:
            continue
        if c.identity not in validator_set:
            raise EquivocationCollapse(f"commitment from non-validator {c.identity}")
        expected = make_commitment(c.identity, c.proposal_hash, c.epoch, c.salt).digest
        if c.digest != expected:
            raise EquivocationCollapse(
                f"digest mismatch for {c.identity}: claimed {c.digest} != {expected}"
            )
        prior = seen.get(c.identity)
        if prior is not None and prior != c.digest:
            # Two distinct digests from one identity in one epoch: equivocation
            # OR benign nondeterminism. Both are faults at this boundary.
            raise EquivocationCollapse(
                f"identity {c.identity} equivocated in epoch {epoch}: {prior} vs {c.digest}"
            )
        seen[c.identity] = c.digest
    if len(seen) < quorum:
        raise EquivocationCollapse(
            f"quorum not reached: {len(seen)} distinct identity-bound commitments < {quorum}"
        )
    return proposal_hash


def commit_shared_state(commitments, proposal_hash, epoch, quorum, validator_set):
    # Guardrail: refuse to commit if the commitment set is not digest-bound.
    for c in commitments:
        if not c.digest or len(c.digest) != 64:
            raise EquivocationCollapse(
                f"unbound commitment from {c.identity}: free-form output cannot be a vote"
            )
    return tally_quorum(commitments, proposal_hash, epoch, quorum, validator_set)
