# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-byzantine-quorum-equivocation-when-an-adversarial-agent-votes-in-two-sub-quorums-of-the-same-decision-round.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-byzantine-quorum-equivocation-when-an-adversarial-agent-votes-in-two-sub-quorums-of-the-same-decision-round.warrant.json
# Markdown SHA-256:   8d3c2f711246c7395256422b4c318af0eb5e65af92f68edea8b4edd0a27fa55b
# Code AST SHA-256:   9956e6470676355ee9e6257fc1dbe989f0f07b30ae829f00eb2364cc83cd7ebe
# Verified Classes:   QuorumEquivocationError, Ballot
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class QuorumEquivocationError(RuntimeError):
    """Raised when two accepted sub-quorum certificates in the same round
    are backed by ballots that cannot be reconciled into a single agreeing
    set of size >= 2f+1 under a per-identity single-slot binding."""


@dataclass(frozen=True)
class Ballot:
    round_id: str
    agent_id: str
    value: str
    signature: str  # opaque; verified upstream


def verify_round_union(
    ballots: Iterable[Ballot],
    roster_size: int,
    round_id: str,
) -> str:
    """Return the single agreed value for the round, or raise.

    Invariant: a round is valid iff there exists a value v such that the
    set of agents voting v has size >= 2f+1 (f = (roster_size-1)//3) AND no
    agent appears with two distinct values in this round. Sub-quorum
    thresholds alone are NOT sufficient.
    """
    f = (roster_size - 1) // 3
    required = 2 * f + 1

    per_agent_values: dict[str, set[str]] = {}
    for b in ballots:
        if b.round_id != round_id:
            raise QuorumEquivocationError(
                f"ballot for agent {b.agent_id} carries round {b.round_id}, "
                f"expected {round_id}"
            )
        per_agent_values.setdefault(b.agent_id, set()).add(b.value)

    equivocators = {a for a, vals in per_agent_values.items() if len(vals) > 1}
    if equivocators:
        # Slash both certificates: the round is poisoned, not merely contested.
        raise QuorumEquivocationError(
            f"equivocation in round {round_id}: agents {sorted(equivocators)} "
            f"cast multiple values; both sub-quorum certificates invalidated"
        )

    # Union view: each agent contributes exactly one value.
    tally: dict[str, set[str]] = {}
    for agent, vals in per_agent_values.items():
        (value,) = vals
        tally.setdefault(value, set()).add(agent)

    winners = [v for v, agents in tally.items() if len(agents) >= required]
    if len(winners) != 1:
        raise QuorumEquivocationError(
            f"round {round_id} has no unique 2f+1 agreeing set "
            f"(required={required}, candidates={winners})"
        )
    return winners[0]


def commit_decision(
    ballots: list[Ballot],
    roster_size: int,
    round_id: str,
) -> str:
    # A commit gate of f+1 over a sub-quorum is unsafe on its own; route
    # every commit through the union verifier so equivocation is fatal.
    return verify_round_union(ballots, roster_size, round_id)
