# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-abort-a-byzantine-commit-when-quorum-weights-are-recomputed-mid-round-the-equivocation-window-invariant-in-delegated-task-commi.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-abort-a-byzantine-commit-when-quorum-weights-are-recomputed-mid-round-the-equivocation-window-invariant-in-delegated-task-commi.warrant.json
# Markdown SHA-256:   0635bc33285bc3b8e1a83a0c7a84233852717392d6de3e1ebd247ae1d7c10a3c
# Code AST SHA-256:   e2a6509613406f64804e2900f27c74a324694bd0441aabf20ab9f9ed416611ce
# Verified Classes:   WeightDigestMismatch, Vote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WeightDigestMismatch(RuntimeError):
    """Raised when a COMMIT vote was tallied under a weight map that differs
    from the one committed in the PREPARE certificate. This is a protocol
    violation (equivocation or mid-round reconfiguration), not a liveness
    failure, and must abort the round rather than be silently discarded."""


@dataclass(frozen=True)
class Vote:
    voter_id: str
    weight_digest: str
    signature: bytes


def weight_digest(weights: dict[str, float]) -> str:
    canonical = ";".join(f"{k}={v}" for k, v in sorted(weights.items()))
    return hashlib.sha256(canonical.encode()).hexdigest()


def tally_commit(
    prepare_digest: str,
    votes: list[Vote],
    committed_weights: dict[str, float],
    threshold: float,
) -> float:
    """Tally a COMMIT certificate strictly under the PREPARE-committed weights.

    Any vote carrying a different weight digest is a protocol violation and
    aborts the round; it is never re-tallied under newer weights.
    """
    total = 0.0
    for v in votes:
        if v.weight_digest != prepare_digest:
            raise WeightDigestMismatch(
                f"vote from {v.voter_id} tallied under digest "
                f"{v.weight_digest[:12]} != prepare digest {prepare_digest[:12]}; "
                f"aborting round to force view-change"
            )
        total += committed_weights.get(v.voter_id, 0.0)
    if total < threshold:
        # Genuine liveness shortfall: escalate to view-change, do not commit.
        raise WeightDigestMismatch(
            f"tally {total} below threshold {threshold} under committed weights"
        )
    return total


def commit_round(
    weights_t: dict[str, float],
    votes: list[Vote],
    threshold: float,
) -> str:
    prepare_digest = weight_digest(weights_t)
    tally_commit(prepare_digest, votes, weights_t, threshold)
    return prepare_digest
