# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-heterogeneous-agent-bft-consensus-from-silently-collapsing-into-majority-tyranny-under-non-uniform-fault-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-heterogeneous-agent-bft-consensus-from-silently-collapsing-into-majority-tyranny-under-non-uniform-fault-domains.warrant.json
# Markdown SHA-256:   9d30177cf001fe9a7289aa32b0d1dd17896bbad0b898fd4899daea8ac3193138
# Code AST SHA-256:   7a04cbaccf3025a44c0f5a04bc26e5a25c677755941d96d2c469fa39e8759267
# Verified Classes:   CorrelatedQuorumError, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List


class CorrelatedQuorumError(RuntimeError):
    """Raised when a quorum is formed by votes that are not independent
    across fault domains, or when a degraded agent votes instead of abstaining."""
    pass


@dataclass
class Vote:
    agent_id: str
    fault_domain: str          # (base_model, tokenizer, prompt_tmpl, tools) hash
    decision: str              # "accept" | "reject" | "abstain"
    evidence_complete: bool
    context_utilization: float


def verify_quorum(votes: List[Vote], quorum: int) -> Dict[str, int]:
    # Gate 1: evidence integrity. Degraded agents must abstain, not vote.
    for v in votes:
        if v.decision != "abstain" and (not v.evidence_complete or v.context_utilization > 0.92):
            raise CorrelatedQuorumError(
                f"agent {v.agent_id} voted '{v.decision}' with degraded evidence "
                f"(complete={v.evidence_complete}, ctx={v.context_utilization:.2f}); "
                f"must abstain"
            )

    # Gate 2: collapse votes to independent fault domains.
    domain_accept: Dict[str, bool] = {}
    domain_reject: Dict[str, bool] = {}
    for v in votes:
        if v.decision == "accept":
            domain_accept[v.fault_domain] = True
        elif v.decision == "reject":
            domain_reject[v.fault_domain] = True

    n_accept_domains = len(domain_accept)
    n_reject_domains = len(domain_reject)
    effective_quorum = n_accept_domains + n_reject_domains

    if effective_quorum < quorum:
        raise CorrelatedQuorumError(
            f"insufficient independent fault domains: {effective_quorum} < {quorum}"
        )

    # Gate 3: no single domain may supply more than half the quorum.
    raw_accept_per_domain: Dict[str, int] = {}
    for v in votes:
        if v.decision == "accept":
            raw_accept_per_domain[v.fault_domain] = raw_accept_per_domain.get(v.fault_domain, 0) + 1
    cap = (quorum + 1) // 2
    for dom, count in raw_accept_per_domain.items():
        if count > cap:
            raise CorrelatedQuorumError(
                f"domain '{dom}' contributed {count} accept votes, exceeding cap {cap}; "
                f"correlated cluster cannot form quorum"
            )

    if n_accept_domains >= quorum:
        return {"decision": "commit", "domains": n_accept_domains}
    return {"decision": "escalate", "domains": n_accept_domains}
