# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-shared-state-under-heterogeneous-byzantine-consensus-and-its-vote-is-silently-re-weighted-by-a-divergent-quor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-shared-state-under-heterogeneous-byzantine-consensus-and-its-vote-is-silently-re-weighted-by-a-divergent-quor.warrant.json
# Markdown SHA-256:   66836d15f7d19157404f283d45c75ae45b8e1076d4cc9b2dac1498f157183b1d
# Code AST SHA-256:   ec2ea5f905c9a8a586ef21be345e8828a9fd31fdf9565dec86dc3bae040df166
# Verified Classes:   UnattestedWeightError, VoteEnvelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class UnattestedWeightError(RuntimeError):
    """Raised when a voter's locally-derived weight diverges from the
    aggregator's signed attestation for the current round. This is not a
    Byzantine fault — it is a memory-distillation divergence that must
    stall the round rather than produce a phantom commitment."""


@dataclass(frozen=True)
class VoteEnvelope:
    round_id: int
    voter_id: str
    vote: str                       # "yay" | "nay" | "abstain"
    claimed_weight: float           # from the voter's LOCAL memory
    attested_weight: float | None   # from aggregator's signed certificate
    attestation_round: int | None


def certify_vote(env: VoteEnvelope, epsilon: float = 1e-3) -> float:
    """Return the weight the aggregator will actually count for this vote.

    Refuses to certify if the voter's local weight is not backed by a
    same-round attestation. This is the guardrail that converts a silent
    quorum divergence into a recoverable stall.
    """
    if env.attested_weight is None or env.attestation_round != env.round_id:
        raise UnattestedWeightError(
            f"voter {env.voter_id} round {env.round_id}: no same-round "
            f"weight attestation; local claimed={env.claimed_weight:.3f} "
            f"is non-authoritative and must not drive quorum arithmetic"
        )
    if abs(env.claimed_weight - env.attested_weight) > epsilon:
        raise UnattestedWeightError(
            f"voter {env.voter_id} round {env.round_id}: weight divergence "
            f"local={env.claimed_weight:.3f} attested={env.attested_weight:.3f}; "
            f"re-sync reputation table from central log before voting"
        )
    return env.attested_weight


def evaluate_quorum(
    envelopes: Mapping[str, VoteEnvelope],
    total_weight: float,
    threshold: float = 2.0 / 3.0,
) -> bool:
    """Compute quorum using ONLY attested weights. Any unattested or
    divergent envelope aborts the round — no partial credit, no local
    arithmetic fallback."""
    yay_weight = 0.0
    for env in envelopes.values():
        weight = certify_vote(env)          # raises on divergence
        if env.vote == "yay":
            yay_weight += weight
    return (yay_weight / total_weight) >= threshold
