# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-byzantine-peer-s-signed-vote-when-heterogeneous-models-disagree-on-the-same-evidence.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-byzantine-peer-s-signed-vote-when-heterogeneous-models-disagree-on-the-same-evidence.warrant.json
# Markdown SHA-256:   d15cbc8526efbc112a3da83167ee188bf8ea63fc71160adad394125f91a9d6ff
# Code AST SHA-256:   b6fd02d5fee117583300d535b0ea9a38e6f6ee92dd97ccb8f062cb69f8230394
# Verified Classes:   UnbudgetedVarianceError, Ballot
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnbudgetedVarianceError(RuntimeError):
    """Raised when observed honest disagreement exceeds the pre-registered
    baseline and the aggregator has no disambiguation path, meaning the
    quorum cannot be safely computed."""
    pass


@dataclass(frozen=True)
class Ballot:
    claim_id: str
    verdict: str
    confidence: float
    model_fingerprint: str
    signature: bytes

    def ballot_hash(self) -> str:
        h = hashlib.sha256()
        h.update(self.claim_id.encode())
        h.update(self.verdict.encode())
        h.update(self.model_fingerprint.encode())
        return h.hexdigest()


def compute_quorum(n: int, f_byz: int, d_baseline: float) -> int:
    """Quorum must exceed the larger honest camp plus Byzantine weight.
    Classical (n+f)/2 is unsafe when d_baseline > 0."""
    honest = n - f_byz
    larger_honest_camp = d_baseline * honest
    byzantine_weight = f_byz
    return int((n + f_byz) / 2 + larger_honest_camp + byzantine_weight) + 1


def adjudicate(
    ballots: list[Ballot],
    f_byz: int,
    d_baseline: float,
    d_observed: float,
    epsilon: float = 0.05,
) -> str:
    n = len(ballots)
    if n < 3 * f_byz + 1:
        raise UnbudgetedVarianceError(
            f"swarm size {n} below 3f+1 for f_byz={f_byz}"
        )

    # Measure variance before trusting any quorum computation.
    verdicts = [b.verdict for b in ballots]
    modal = max(set(verdicts), key=verdicts.count)
    dissent_fraction = (len(verdicts) - verdicts.count(modal)) / n

    if dissent_fraction > d_baseline + epsilon:
        # Dissent exceeds honest-variance baseline. This is either a harder
        # evidence bundle or a genuine Byzantine peer. Do NOT quarantine on
        # hash divergence; escalate to a challenge round with re-fetched
        # evidence and compare reasoning consistency.
        raise UnbudgetedVarianceError(
            f"dissent {dissent_fraction:.2f} exceeds baseline "
            f"{d_baseline:.2f}+{epsilon:.2f}; escalate to challenge round, "
            f"do not quarantine"
        )

    # Within baseline: dissent is honest variance. Widen quorum accordingly.
    q = compute_quorum(n, f_byz, d_baseline)
    if verdicts.count(modal) < q:
        raise UnbudgetedVarianceError(
            f"modal camp {verdicts.count(modal)} below variance-adjusted "
            f"quorum {q}; disambiguate evidence bundle"
        )
    return modal
