# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-equivocation-before-byzantine-quorum-commitment-a-single-epoch-fork-in-agent-task-commitment-under-adversarial-peers.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-equivocation-before-byzantine-quorum-commitment-a-single-epoch-fork-in-agent-task-commitment-under-adversarial-peers.warrant.json
# Markdown SHA-256:   607c904f12ced922952fb5a3e950102d2c53d8bf06dd35f0ac9d0d5a3f400049
# Code AST SHA-256:   d0fe5e0e14f776c1777be1e60004d998866702d3df88c0a214c9149b75aedaee
# Verified Classes:   EquivocationDetected, VoteIndexNotDurable, Vote, Aggregator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EquivocationDetected(RuntimeError):
    """Raised when a replica votes for two commitments in the same epoch."""
    pass


class VoteIndexNotDurable(RuntimeError):
    """Raised when aggregation is attempted without a durable vote index."""
    pass


@dataclass
class Vote:
    replica_id: int
    epoch: int
    commitment_id: str
    signature: str


@dataclass
class Aggregator:
    epoch: int
    quorum_size: int
    durable_index: bool
    _vote_index: Dict[Tuple[int, int], str] = field(default_factory=dict)
    _counts: Dict[str, int] = field(default_factory=dict)
    _lock: threading.Lock = field(default_factory=threading.Lock)

    def accept_vote(self, vote: Vote) -> bool:
        if not self.durable_index:
            raise VoteIndexNotDurable(
                "aggregator lacks durable vote index; refusing to aggregate"
            )
        if vote.epoch != self.epoch:
            raise EquivocationDetected(
                f"vote epoch {vote.epoch} != aggregator epoch {self.epoch}"
            )
        key = (vote.replica_id, vote.epoch)
        with self._lock:
            prior = self._vote_index.get(key)
            if prior is not None and prior != vote.commitment_id:
                raise EquivocationDetected(
                    f"replica {vote.replica_id} voted {prior} and "
                    f"{vote.commitment_id} in epoch {vote.epoch}"
                )
            self._vote_index[key] = vote.commitment_id
            self._counts[vote.commitment_id] = (
                self._counts.get(vote.commitment_id, 0) + 1
            )
            return self._counts[vote.commitment_id] >= self.quorum_size

    def certify(self, commitment_id: str) -> str:
        with self._lock:
            if self._counts.get(commitment_id, 0) < self.quorum_size:
                raise EquivocationDetected(
                    f"cannot certify {commitment_id}: "
                    f"{self._counts.get(commitment_id, 0)}/{self.quorum_size}"
                )
            return f"QC({commitment_id}, epoch={self.epoch})"


# Reproduction of the epoch-88 fork: two disjoint aggregators, one Byzantine replica.
agg_a = Aggregator(epoch=88, quorum_size=5, durable_index=True)
agg_b = Aggregator(epoch=88, quorum_size=5, durable_index=True)

for r in (0, 1, 2):
    agg_a.accept_vote(Vote(r, 88, "C_A", f"sig{r}"))
agg_a.accept_vote(Vote(4, 88, "C_A", "sig4"))
agg_a.accept_vote(Vote(0, 88, "C_A", "sig0-dup"))  # idempotent re-vote, same commitment

for r in (3, 5, 6):
    agg_b.accept_vote(Vote(r, 88, "C_B", f"sig{r}"))

# Byzantine replica-4 attempts the second leg of the equivocation.
try:
    agg_b.accept_vote(Vote(4, 88, "C_B", "sig4"))
except EquivocationDetected as e:
    print(f"fork blocked at aggregation: {e}")
    # QC_B cannot reach quorum; fork is closed before commit.
