# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-equivocation-drift-when-coalition-agents-vote-on-task-commitment-under-partial-synchrony.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-equivocation-drift-when-coalition-agents-vote-on-task-commitment-under-partial-synchrony.warrant.json
# Markdown SHA-256:   18644e4327935c8358ab06afe17e0afd1fb7c9a84926e2ff7ae7e76c87a0179b
# Code AST SHA-256:   e3acf977bdd3766bac5d82a4b68d7a74109ef9192ce5dd835bc76291e782aab4
# Verified Classes:   EquivocationDriftError, Vote, QuorumAggregator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EquivocationDriftError(RuntimeError):
    """Raised when a quorum assembles signatures over mutually inconsistent tuples."""
    pass


@dataclass(frozen=True)
class Vote:
    member_id: str
    proposal_id: str
    decision: str          # "commit" | "abstain" | "reject"
    plan_hash: str         # canonical digest
    round_nonce: int


@dataclass
class QuorumAggregator:
    proposal_id: str
    round_nonce: int
    quorum_size: int
    votes: List[Vote] = field(default_factory=list)

    def accept(self, vote: Vote) -> None:
        # Guard 1: round-scoped nonce binding
        if vote.round_nonce != self.round_nonce:
            raise EquivocationDriftError(
                f"vote from {vote.member_id} carries stale nonce "
                f"{vote.round_nonce} != {self.round_nonce}"
            )
        # Guard 2: proposal binding
        if vote.proposal_id != self.proposal_id:
            raise EquivocationDriftError(
                f"vote from {vote.member_id} targets {vote.proposal_id}"
            )
        self.votes.append(vote)

    def certify(self) -> Tuple[str, str]:
        """Return the certified (decision, plan_hash) tuple or raise."""
        if len(self.votes) < self.quorum_size:
            raise EquivocationDriftError(
                f"insufficient votes: {len(self.votes)} < {self.quorum_size}"
            )
        # Guard 3: tuple consistency — the invariant that a count check misses
        tuples: Dict[Tuple[str, str], int] = {}
        for v in self.votes:
            tuples[(v.decision, v.plan_hash)] = tuples.get(
                (v.decision, v.plan_hash), 0
            ) + 1
        dominant, count = max(tuples.items(), key=lambda kv: kv[1])
        if count < self.quorum_size:
            raise EquivocationDriftError(
                f"quorum reached on count but not on tuple: {tuples}"
            )
        return dominant


def ratify(aggregator: QuorumAggregator, votes: List[Vote]) -> Tuple[str, str]:
    for v in votes:
        aggregator.accept(v)
    return aggregator.certify()
