# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-collapse-in-byzantine-fault-tolerant-consensus-among-heterogeneous-llm-agents-with-non-deterministic-votes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-collapse-in-byzantine-fault-tolerant-consensus-among-heterogeneous-llm-agents-with-non-deterministic-votes.warrant.json
# Markdown SHA-256:   36d72eaac54cc2edd3250d87c6b2f962ba17c505c06b96be8e301689d6085fbc
# Code AST SHA-256:   26829f24de54a50b31de7d0850978792daabe6cf0c692080abc3b0d188715e88
# Verified Classes:   QuorumSafetyViolation, AgentVote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Iterable


class QuorumSafetyViolation(RuntimeError):
    """Raised when non-deterministic votes can admit two distinct committed values."""


@dataclass(frozen=True)
class AgentVote:
    agent_id: str
    raw_text: str


def check_stable_vote_invariant(
    votes_by_agent: dict[str, Iterable[AgentVote]],
    canonicalize: Callable[[str], str],
    quorum: int,
) -> None:
    """
    Enforce the Stable-Vote Invariant before any quorum count is trusted.

    Safety requires, for every honest agent, that canonicalize maps all of that
    agent's sampled votes to a single value, OR that canonicalize is injective
    on the union of supports. We check the stronger, cheap condition: each
    agent's canonical support must be a singleton. A non-singleton support with
    a non-injective canonicalizer is exactly the quorum-collapse condition.
    """
    if quorum < 1:
        raise QuorumSafetyViolation(f"invalid quorum threshold {quorum}")

    supports: dict[str, set[str]] = {}
    for agent_id, samples in votes_by_agent.items():
        canon = {canonicalize(s.raw_text) for s in samples}
        if not canon:
            raise QuorumSafetyViolation(
                f"agent {agent_id} produced no samples; cannot establish support"
            )
        supports[agent_id] = canon

    unstable = {a: s for a, s in supports.items() if len(s) > 1}
    if unstable:
        # Non-singleton support: only safe if canonicalize is injective on the
        # union of supports. We cannot prove injectivity from samples, so we
        # refuse to certify safety and surface the condition explicitly.
        union = set().union(*supports.values())
        raise QuorumSafetyViolation(
            "non-deterministic canonical votes detected; quorum intersection no "
            f"longer bounds committed values to one. Unstable agents: {unstable}. "
            f"Distinct canonical values in play: {sorted(union)}. "
            "Mitigation: freeze canonicalizer, force temperature 0 for the voting "
            "call, or require agents to re-sign the canonicalized token."
        )

    # Singleton supports: counting agents (not samples) is now sound.
    tally: dict[str, int] = {}
    for canon in supports.values():
        (value,) = canon
        tally[value] = tally.get(value, 0) + 1

    committed = [v for v, c in tally.items() if c >= quorum]
    if len(committed) > 1:
        raise QuorumSafetyViolation(
            f"multiple values reached quorum {quorum}: {committed}; "
            "this indicates the invariant was checked on an inconsistent snapshot"
        )
