# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-during-byzantine-fault-tolerant-task-commitment-when-signed-vote-batches-arrive-out-of-order.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-during-byzantine-fault-tolerant-task-commitment-when-signed-vote-batches-arrive-out-of-order.warrant.json
# Markdown SHA-256:   e546ea523977dcaed87d44095a7cc2bc83baba0a9063310ca7765088a1d98cdc
# Code AST SHA-256:   b2b549673d76bad6cbaf7bcd6a524dd40a0a481aa42d720ef315a3dcbd7d122e
# Verified Classes:   EquivocationDetected, SignedCommit, EquivocationIndex
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when a signer is proven to have double-voted on the same tuple."""
    pass


@dataclass(frozen=True)
class SignedCommit:
    agent_id: str
    view: int
    task_id: str
    commit_value: str
    signature: bytes


class EquivocationIndex:
    """Retains the first signed commitment per (agent_id, view, task_id) tuple
    and proves equivocation when a differing second commitment arrives."""

    def __init__(self) -> None:
        self._seen: Dict[Tuple[str, int, str], SignedCommit] = {}

    def record(self, vote: SignedCommit) -> None:
        key = (vote.agent_id, vote.view, vote.task_id)
        prior = self._seen.get(key)
        if prior is None:
            self._seen[key] = vote
            return
        if prior.commit_value != vote.commit_value:
            # Both artifacts are signed; the pair is a portable proof.
            raise EquivocationDetected(
                f"agent {vote.agent_id} equivocated on task {vote.task_id} "
                f"view {vote.view}: {prior.commit_value!r} vs {vote.commit_value!r}"
            )
        # Identical re-send: idempotent, ignore.

    def conflicting_signer(self, quorum: list[SignedCommit]) -> str | None:
        """Return the first signer whose recorded commitment conflicts with
        the quorum vote it contributed, else None."""
        for vote in quorum:
            key = (vote.agent_id, vote.view, vote.task_id)
            prior = self._seen.get(key)
            if prior is not None and prior.commit_value != vote.commit_value:
                return vote.agent_id
        return None


def finalize_commit(
    index: EquivocationIndex,
    quorum: list[SignedCommit],
    f: int,
) -> str:
    """Declare finality only if no quorum signer is a proven equivocator."""
    if len(quorum) < 2 * f + 1:
        raise EquivocationDetected(f"quorum too small: {len(quorum)} < {2 * f + 1}")
    bad = index.conflicting_signer(quorum)
    if bad is not None:
        raise EquivocationDetected(
            f"refusing finality: signer {bad} has a conflicting signed artifact"
        )
    values = {v.commit_value for v in quorum}
    if len(values) != 1:
        raise EquivocationDetected(f"inconsistent quorum values: {values}")
    return values.pop()
