# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-hallucinating-peer-as-byzantine-rather-than-merely-lossy-quorum-certificate-divergence-in-bft-task-allocation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-hallucinating-peer-as-byzantine-rather-than-merely-lossy-quorum-certificate-divergence-in-bft-task-allocation.warrant.json
# Markdown SHA-256:   15e06accd62075869b4fa8364243173871b93e505e78586b019697fb5a311945
# Code AST SHA-256:   b0f4edeb0533977ea8d25de5473c6f1f2a097650eca2b636a7928f42c7d82f88
# Verified Classes:   QuorumDivergenceError, HallucinatingPeerExcluded
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from collections import defaultdict


class QuorumDivergenceError(RuntimeError):
    """Raised when quorum cardinality is met but view-hash agreement is not."""
    pass


class HallucinatingPeerExcluded(RuntimeError):
    """Raised when a peer shows stable divergence and must be excluded."""
    pass


def canonical_view_hash(assignment_map: dict) -> str:
    # Canonical serialization is mandatory; non-canonical hashing is itself
    # a divergence source that mimics hallucination.
    payload = json.dumps(assignment_map, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def commit_quorum(votes: list[dict], threshold: int,
                  local_view_hash: str,
                  divergence_counts: dict[str, int]) -> str:
    """
    votes: [{'peer': str, 'view_hash': str, 'sig': str}]
    Returns the committed view hash if and only if a single hash partition
    reaches threshold AND matches the locally recomputed hash.
    """
    partitions: dict[str, list[str]] = defaultdict(list)
    for v in votes:
        partitions[v["view_hash"]].append(v["peer"])

    # Track stable divergence per peer for escalation.
    for v in votes:
        if v["view_hash"] != local_view_hash:
            divergence_counts[v["peer"]] = divergence_counts.get(v["peer"], 0) + 1

    # Escalate stable divergence: a peer that diverges twice is not lossy,
    # it is hallucinating (or Byzantine) and must be excluded.
    for peer, count in divergence_counts.items():
        if count >= 2:
            raise HallucinatingPeerExcluded(
                f"peer {peer} diverged {count}x over view hash; exclude and resync"
            )

    if not partitions:
        raise QuorumDivergenceError("no votes received; cannot form quorum")

    largest_hash, largest_peers = max(partitions.items(), key=lambda kv: len(kv[1]))

    if len(largest_peers) < threshold:
        raise QuorumDivergenceError(
            f"cardinality {len(largest_peers)} < threshold {threshold} "
            f"for hash {largest_hash[:12]}"
        )

    if largest_hash != local_view_hash:
        # Cardinality met, but over a hash we did not compute. This is the
        # hallucination signature: self-consistent, signed, and wrong.
        raise QuorumDivergenceError(
            f"quorum reached over {largest_hash[:12]} but local view is "
            f"{local_view_hash[:12]}; refusing commit"
        )

    return largest_hash
