# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-heterogeneous-agent-byzantine-consensus-as-unsound-when-the-adversarial-minority-controls-the-evaluation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-heterogeneous-agent-byzantine-consensus-as-unsound-when-the-adversarial-minority-controls-the-evaluation.warrant.json
# Markdown SHA-256:   438c5b2aa80854a20c2343dadc13181ba9035f00762ec1171fb9c857489ad43b
# Code AST SHA-256:   16274f0bb1eb6576708369cd21858816ee2f0921befaac3969dff08782c2364d
# Verified Classes:   SerializationCaptureError, Ballot
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

class SerializationCaptureError(RuntimeError):
    """Raised when ballot derivation is not a frozen, auditable function of judgment."""
    pass

@dataclass(frozen=True)
class Ballot:
    agent_id: str
    rationale: str
    vote: str          # "PASS" | "FAIL"
    sigma_hash: str    # hash of the serialization function used

def derive_ballot(agent_id: str, rationale: str, sigma, sigma_hash: str,
                  frozen_sigma_hash: str) -> Ballot:
    if sigma_hash != frozen_sigma_hash:
        raise SerializationCaptureError(
            f"agent {agent_id}: sigma hash {sigma_hash[:12]} != frozen "
            f"{frozen_sigma_hash[:12]}; rubric mutated mid-round"
        )
    vote = sigma(rationale)
    # audit: re-derive and confirm the ballot is a stable function of rationale
    if sigma(rationale) != vote:
        raise SerializationCaptureError(
            f"agent {agent_id}: non-deterministic sigma; ballot not reproducible"
        )
    return Ballot(agent_id, rationale, vote, sigma_hash)

def tally(ballots, n: int, frozen_sigma_hash: str) -> str:
    required = (2 * n) // 3 + 1
    for b in ballots:
        if b.sigma_hash != frozen_sigma_hash:
            raise SerializationCaptureError(
                "tally refused: ballot serialized under non-frozen rubric"
            )
    passes = sum(1 for b in ballots if b.vote == "PASS")
    fails = len(ballots) - passes
    if passes >= required:
        return "PASS"
    if fails >= required:
        return "FAIL"
    return "NO_CONSENSUS"
