# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-quorum-fail-silently-when-a-hallucinating-agent-s-fabricated-vote-is-structurally-indistinguishable-from-an-advers.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-quorum-fail-silently-when-a-hallucinating-agent-s-fabricated-vote-is-structurally-indistinguishable-from-an-advers.warrant.json
# Markdown SHA-256:   9328cb06595300036d4bec0ea42deb35e3499d0b4e5869277233dc4ae2b12cb1
# Code AST SHA-256:   03c6f83ee614c84e9194a284c27324b9281757eebfea2da314521c941222f278
# Verified Classes:   QuorumGroundingError, Vote
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from collections import defaultdict


class QuorumGroundingError(RuntimeError):
    """Raised when a quorum's tally cannot be certified against correlated hallucination."""
    pass


@dataclass
class Vote:
    agent_id: str
    value: str
    grounded: bool          # True only if agent independently re-read source via a verifiable tool trace
    trace_id: str | None    # required when grounded=True


def certify_quorum(votes: list[Vote], adversarial_budget: int) -> str:
    if not votes:
        raise QuorumGroundingError("empty quorum: no votes to certify")

    grounded = [v for v in votes if v.grounded]
    ungrounded = [v for v in votes if not v.grounded]

    # Grounded votes must carry a distinct trace; a shared trace is one vote.
    grounded_by_value: dict[str, set[str]] = defaultdict(set)
    for v in grounded:
        if v.trace_id is None:
            raise QuorumGroundingError(
                f"agent {v.agent_id} marked grounded without a trace_id"
            )
        grounded_by_value[v.value].add(v.trace_id)

    # Collapse correlated ungrounded agreement: each distinct ungrounded value
    # contributes at most ONE vote regardless of how many agents emitted it.
    ungrounded_values = {v.value for v in ungrounded}

    # Grounded score per value = number of independent traces.
    grounded_score = {val: len(traces) for val, traces in grounded_by_value.items()}

    if not grounded_score:
        raise QuorumGroundingError(
            "no grounded votes: quorum cannot distinguish truth from correlated confabulation"
        )

    # Winning value must beat the adversarial budget using grounded evidence only.
    best_value, best_score = max(grounded_score.items(), key=lambda kv: kv[1])

    if best_score <= adversarial_budget:
        raise QuorumGroundingError(
            f"grounded support for {best_value!r} is {best_score}, "
            f"not strictly greater than adversarial budget {adversarial_budget}; "
            f"ungrounded values seen: {sorted(ungrounded_values)}"
        )

    # A competing ungrounded value that matches or exceeds grounded support
    # signals correlated hallucination masquerading as consensus.
    for val in ungrounded_values:
        if val != best_value and len(ungrounded) >= best_score:
            raise QuorumGroundingError(
                f"ungrounded block of size {len(ungrounded)} on {val!r} "
                f"rivals grounded support {best_score} for {best_value!r}; "
                "refusing to certify majority"
            )

    return best_value
