# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-quorum-poisoning-in-byzantine-multi-agent-decision-councils-before-the-vote-tally-closes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-quorum-poisoning-in-byzantine-multi-agent-decision-councils-before-the-vote-tally-closes.warrant.json
# Markdown SHA-256:   52cb7d156c898ef9a3a4c5d1320242f288c97e5fe30f537909f2c2bbc86dce8c
# Code AST SHA-256:   b404cf5490cfccffa17e6c31c3d53c0aabce3d8a3f278d4583dead045e3388e9
# Verified Classes:   QuorumPoisoningError, RoundResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import itertools
from dataclasses import dataclass
from typing import Sequence

class QuorumPoisoningError(RuntimeError):
    """Raised when a quorum's convergence is context-correlated rather than evidence-robust."""
    pass

@dataclass(frozen=True)
class RoundResult:
    votes: dict[str, str]          # agent_id -> decision label
    cited_chunks: dict[str, list[str]]  # agent_id -> evidence chunk ids cited
    threshold: int
    f: int

def pairwise_agreement(a: dict[str, str], b: dict[str, str]) -> float:
    agents = sorted(set(a) & set(b))
    if not agents:
        return 0.0
    agree = sum(1 for k in agents if a[k] == b[k])
    return agree / len(agents)

def winning_coalition(votes: dict[str, str]) -> set[str]:
    from collections import Counter
    label, count = Counter(votes.values()).most_common(1)[0]
    if count < 1:
        return set()
    return {a for a, v in votes.items() if v == label}

def validate_quorum(
    committed: RoundResult,
    ablated: RoundResult,
    cross_context: RoundResult,
    agreement_ceiling: float = 0.85,
    cross_context_floor: float = 0.5,
) -> None:
    """
    Gate a committed quorum on vote-independence invariants.

    Raises QuorumPoisoningError if the winning coalition's convergence is
    an artifact of shared context rather than evidence robustness.
    """
    coalition = winning_coalition(committed.votes)
    if len(coalition) < committed.threshold:
        raise QuorumPoisoningError(
            f"coalition size {len(coalition)} < threshold {committed.threshold}"
        )

    # Signal 1: context-ablation delta. Removing f cited chunks must not flip >f agents.
    flips = sum(
        1 for a in coalition
        if committed.votes.get(a) != ablated.votes.get(a)
    )
    if flips > committed.f:
        raise QuorumPoisoningError(
            f"context-ablation flipped {flips} agents (> f={committed.f}); "
            "convergence was context-correlated, not evidence-robust"
        )

    # Signal 2: within-round agreement vs cross-context agreement.
    within = pairwise_agreement(
        {a: committed.votes[a] for a in coalition},
        {a: committed.votes[a] for a in coalition},
    )
    cross = pairwise_agreement(
        {a: committed.votes[a] for a in coalition},
        {a: cross_context.votes.get(a, "UNKNOWN") for a in coalition},
    )
    if within > agreement_ceiling and cross < cross_context_floor:
        raise QuorumPoisoningError(
            f"within-round agreement {within:.2f} >> cross-context {cross:.2f}; "
            "winning coalition collapsed onto shared evidence misreading"
        )
