# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-heterogeneous-llm-byzantine-consensus-from-collapsing-into-silent-equivocation-under-partial-synchrony.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-heterogeneous-llm-byzantine-consensus-from-collapsing-into-silent-equivocation-under-partial-synchrony.warrant.json
# Markdown SHA-256:   ee7acec06e865d6c0e0cbee4be3791040cb9df4238cf24f775e82b14abb12b68
# Code AST SHA-256:   7f9858f6d6b504599ba219d3c75e858f0bf934fc0807cff522110706b7496464
# Verified Classes:   EquivocationDetected, NonTransitiveVerdict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Iterable


class EquivocationDetected(RuntimeError):
    """Raised when quorum is claimed over non-identical vote hashes (silent equivocation)."""


class NonTransitiveVerdict(RuntimeError):
    """Raised when a similarity judge's pairwise verdicts violate transitivity."""


def canonicalize(value: dict) -> bytes:
    # Freeze the vote: sorted keys, NFC-ish normalization assumed upstream, fixed encoding.
    normalized = {k: (v.strip().lower() if isinstance(v, str) else v) for k, v in value.items()}
    return json.dumps(normalized, sort_keys=True, separators=(",", ":")).encode("utf-8")


def vote_hash(value: dict) -> str:
    return hashlib.sha256(canonicalize(value)).hexdigest()


def assert_quorum_identical(votes: Iterable[dict], quorum: int) -> str:
    """Quorum must be counted over byte-identical canonical votes, never over judge verdicts."""
    hashes = [vote_hash(v) for v in votes]
    distinct = set(hashes)
    if len(distinct) != 1:
        raise EquivocationDetected(
            f"quorum claimed over {len(distinct)} distinct vote hashes: {sorted(distinct)}"
        )
    if len(hashes) < quorum:
        raise EquivocationDetected(f"only {len(hashes)} votes, quorum requires {quorum}")
    return hashes[0]


def assert_transitive(judge, a: dict, b: dict, c: dict) -> None:
    """Reject any judge whose verdicts are not transitive; non-transitive => unsafe tally."""
    ab, bc, ac = judge(a, b), judge(b, c), judge(a, c)
    if ab and bc and not ac:
        raise NonTransitiveVerdict(f"judge says a~b and b~c but not a~c: {ab},{bc},{ac}")


def commit_view(votes: list[dict], quorum: int, judge=None) -> str:
    if judge is not None:
        # Similarity must be confined to normalization, never to quorum counting.
        assert_transitive(judge, votes[0], votes[1], votes[2])
        raise NonTransitiveVerdict("judge-mediated tally is outside the safe boundary")
    return assert_quorum_identical(votes, quorum)
