# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-plan-under-byzantine-quorum-with-equivocating-peers-the-vote-count-commitment-divergence-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-plan-under-byzantine-quorum-with-equivocating-peers-the-vote-count-commitment-divergence-boundary.warrant.json
# Markdown SHA-256:   ec8b2a2aa74cc339502174a22a245467ccefbe9c09aa098a739cd581dcbb3ee2
# Code AST SHA-256:   639a1bccacf848752d98130b885411c0375a5ebe6e57bca386380ae087ecae74
# Verified Classes:   EquivocationSafetyViolation, SignedVote, QuorumCollector
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Tuple


class EquivocationSafetyViolation(RuntimeError):
    """Raised when a quorum certificate is threshold-satisfying but not single-valued."""


@dataclass(frozen=True)
class SignedVote:
    signer: str
    plan: str
    epoch: int


@dataclass
class QuorumCollector:
    n: int
    f: int
    # signer -> plan observed this epoch; a second distinct plan = equivocation
    observed: Dict[str, str] = field(default_factory=dict)

    @property
    def quorum(self) -> int:
        return 2 * self.f + 1

    def receive(self, vote: SignedVote) -> None:
        prior = self.observed.get(vote.signer)
        if prior is not None and prior != vote.plan:
            # Same signer, two values in one epoch: this signer is Byzantine.
            # Mark it poisoned so it can never count toward a quorum.
            self.observed[vote.signer] = "__EQUIVOCATED__"
        else:
            self.observed[vote.signer] = vote.plan

    def commit(self, plan: str) -> Tuple[bool, str]:
        signers = [s for s, p in self.observed.items() if p == plan]
        poisoned = [s for s, p in self.observed.items() if p == "__EQUIVOCATED__"]
        if len(signers) >= self.quorum:
            return True, f"commit {plan} on {len(signers)} single-valued signers"
        if poisoned:
            raise EquivocationSafetyViolation(
                f"cannot commit {plan}: signers {poisoned} equivocated; "
                f"threshold-met does not imply single-valued quorum"
            )
        return False, f"insufficient: {len(signers)}/{self.quorum} for {plan}"


def commit_plan(collector: QuorumCollector, plan: str) -> str:
    ok, reason = collector.commit(plan)
    if not ok and "__EQUIVOCATED__" not in collector.observed.values():
        return reason
    if not ok:
        # Explicitly re-raise to make the unsafe path loud, not silent.
        raise EquivocationSafetyViolation(
            f"refusing commit of {plan}: quorum certificate not single-valued"
        )
    return reason
