# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-heterogeneous-llm-quorum-lose-byzantine-safety-when-a-single-agent-s-sampling-temperature-crosses-the-vote-flip-threshold-mi.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-heterogeneous-llm-quorum-lose-byzantine-safety-when-a-single-agent-s-sampling-temperature-crosses-the-vote-flip-threshold-mi.warrant.json
# Markdown SHA-256:   5976c3f8c4075924f5a8aba7439790335cee5a7facf1bf0cf1d43d4a2fe5732a
# Code AST SHA-256:   2e2241f3025e2b39cbd9de41734b9ba6f7e3c3c7e54ff92f22fed200960e05fd
# Verified Classes:   QuorumSafetyViolation, VoteCommitment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QuorumSafetyViolation(RuntimeError):
    """Raised when probabilistic equivocation shrinks the effective quorum below the BFT safety margin."""
    pass


@dataclass
class VoteCommitment:
    agent_id: str
    round_id: int
    vote: str          # "APPROVE" | "REJECT"
    nonce: str

    def digest(self) -> str:
        payload = f"{self.agent_id}|{self.round_id}|{self.vote}|{self.nonce}"
        return hashlib.sha256(payload.encode()).hexdigest()


def check_quorum_safety(
    n: int,
    f: int,
    per_agent_flip_rate: dict[str, float],
) -> None:
    """
    Recompute the effective fault bound after accounting for probabilistic
    equivocation. Raises if the safety margin n - 3f goes non-positive.
    """
    equivocation_budget = sum(per_agent_flip_rate.values())
    effective_margin = n - 3 * f - equivocation_budget
    if effective_margin <= 0:
        raise QuorumSafetyViolation(
            f"effective margin {effective_margin:.2f} <= 0: "
            f"n={n}, f={f}, equivocation_budget={equivocation_budget:.2f}. "
            f"Quorum cannot guarantee safety; demote high-flip agents to temp 0.0."
        )


def verify_commitment_consistency(
    commitments_by_replica: dict[str, list[VoteCommitment]],
) -> None:
    """
    Enforce that every agent produced one consistent commitment digest
    across all replicas in the round. Any divergence is a pre-commit
    equivocation and the agent must be excluded before vote counting.
    """
    for agent_id, commitments in commitments_by_replica.items():
        digests = {c.digest() for c in commitments}
        if len(digests) > 1:
            raise QuorumSafetyViolation(
                f"agent {agent_id} emitted {len(digests)} distinct commitment "
                f"digests across replicas in round {commitments[0].round_id}: "
                f"probabilistic equivocation detected pre-commit. "
                f"Exclude from effective n before applying safety proof."
            )
