# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-equivocation-detection-under-byzantine-quorum-thresholds-in-multi-agent-task-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-equivocation-detection-under-byzantine-quorum-thresholds-in-multi-agent-task-commitment.warrant.json
# Markdown SHA-256:   c1c5a639412b01a7f3e6230f0ac3939fbd395cf0d2cf39074bdea5ce1c10fc9b
# Code AST SHA-256:   284d8a873b8ab72c4ed11d6beeed94bab55d0151c3afe2ef57c3afd49bfcd791
# Verified Classes:   EquivocationDetected, QuorumUnavailable, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Set


class EquivocationDetected(RuntimeError):
    """Raised when a single sender casts conflicting votes in one round."""
    pass


class QuorumUnavailable(RuntimeError):
    """Raised when excluding faulty senders drops below BFT liveness bound."""
    pass


@dataclass(frozen=True)
class Vote:
    round_id: int
    sender: str
    plan: str
    prior_state_hash: str
    signature: str  # verified upstream; assumed valid here


def commit_plan(votes: list[Vote], n_replicas: int, round_id: int) -> str:
    # BFT quorum for crash+Byzantine tolerance: ceil((2N+1)/3)
    q = (2 * n_replicas + 1 + 2) // 3

    # Key strictly by sender: one counted vote per (round, sender).
    by_sender: Dict[str, Vote] = {}
    for v in votes:
        if v.round_id != round_id:
            continue
        prior = by_sender.get(v.sender)
        if prior is None:
            by_sender[v.sender] = v
            continue
        # Same sender, same round: must agree on plan AND state binding.
        if prior.plan != v.plan or prior.prior_state_hash != v.prior_state_hash:
            # Pre-commit halt: do NOT pick a majority. Emit proof and abort.
            raise EquivocationDetected(
                f"sender={v.sender} round={round_id} "
                f"voted {prior.plan!r} then {v.plan!r}"
            )
        # Identical duplicate: idempotent, ignore.

    tally: Dict[str, Set[str]] = {}
    for sender, v in by_sender.items():
        tally.setdefault(v.plan, set()).add(sender)

    committed = [plan for plan, senders in tally.items() if len(senders) >= q]
    if len(committed) > 1:
        # Should be unreachable if equivocation check above is sound,
        # but guard the invariant explicitly.
        raise EquivocationDetected(
            f"multiple plans reached distinct-sender quorum: {committed}"
        )
    if not committed:
        # Check liveness after hypothetical exclusion of one faulty sender.
        n_prime = n_replicas - 1
        f = (n_replicas - 1) // 3
        if n_prime < 3 * f + 1:
            raise QuorumUnavailable(
                f"cannot exclude sender and retain BFT liveness: "
                f"N'={n_prime}, need >= {3*f+1}"
            )
        raise QuorumUnavailable(
            f"no plan reached distinct-sender quorum q={q}"
        )
    return committed[0]
