# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-heterogeneous-llm-agents-from-silently-collapsing-a-byzantine-quorum-into-a-plurality-vote.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-heterogeneous-llm-agents-from-silently-collapsing-a-byzantine-quorum-into-a-plurality-vote.warrant.json
# Markdown SHA-256:   0cfdbda901ffc37e2a4d8c5d1bc702119fd1d7a72a4740edbb91ce44c9a58269
# Code AST SHA-256:   b54a0b2c963dbb9a4caf12012929394b9403f20283657b059f3ec54db24d8a1c
# Verified Classes:   CorrelatedQuorumError, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence
from collections import defaultdict


class CorrelatedQuorumError(RuntimeError):
    """Raised when a committing quorum spans fewer than f+1 distinct evidence clusters."""
    pass


@dataclass(frozen=True)
class Vote:
    agent_id: str
    value: str
    evidence_cluster: str  # normalized rationale: cited heuristic / tool / source


def commit_quorum(votes: Sequence[Vote], f: int) -> str:
    """
    Enforce the independence invariant: a value may commit only if the
    winning quorum spans >= f+1 distinct evidence clusters.
    """
    if len(votes) < 3 * f + 1:
        raise CorrelatedQuorumError(
            f"insufficient agents: {len(votes)} < 3f+1 = {3*f+1}"
        )

    by_value: dict[str, list[Vote]] = defaultdict(list)
    for v in votes:
        by_value[v.value].append(v)

    threshold = 2 * f + 1
    for value, supporters in by_value.items():
        if len(supporters) < threshold:
            continue
        clusters = {s.evidence_cluster for s in supporters}
        if len(clusters) < f + 1:
            # Quorum met numerically but not evidentially: correlated prior.
            raise CorrelatedQuorumError(
                f"value={value!r} reached {len(supporters)} votes but only "
                f"{len(clusters)} evidence cluster(s) {sorted(clusters)}; "
                f"need >= {f+1}. Quorum is a plurality vote, not Byzantine."
            )
        return value

    raise CorrelatedQuorumError(
        f"no value reached threshold {threshold} with sufficient evidence diversity"
    )
