# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-byzantine-equivocation-from-benign-latency-in-agent-quorum-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-byzantine-equivocation-from-benign-latency-in-agent-quorum-attestation.warrant.json
# Markdown SHA-256:   4996dbb17c965e7da9c754bfc9c313bf4ad386535c174bd2d27b97d4575863d4
# Code AST SHA-256:   b4a1fbd8f6ee5025de034548f78529a0b283c3458975e88625e85e97cde40500
# Verified Classes:   EquivocationDetected, QuorumUnreachable, SignedVote, QuorumTracker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EquivocationDetected(RuntimeError):
    """Raised when an identity signs conflicting votes for the same epoch."""
    pass


class QuorumUnreachable(RuntimeError):
    """Raised when quarantine shrinks the honest set below 2f+1."""
    pass


@dataclass(frozen=True)
class SignedVote:
    peer_id: str
    task_id: str
    epoch: int
    payload: str          # e.g. "COMMIT" | "ABORT"
    signature: bytes


@dataclass
class QuorumTracker:
    f: int
    _seen: Dict[Tuple[str, str, int], SignedVote] = field(default_factory=dict)
    _quarantined: set = field(default_factory=set)

    def admit(self, vote: SignedVote) -> None:
        key = (vote.peer_id, vote.task_id, vote.epoch)
        if vote.peer_id in self._quarantined:
            return  # already excluded; ignore
        prior = self._seen.get(key)
        if prior is None:
            self._seen[key] = vote
            return
        if prior.payload != vote.payload:
            # Two distinct signed payloads from one identity: Byzantine proof.
            self._quarantined.add(vote.peer_id)
            raise EquivocationDetected(
                f"peer {vote.peer_id} signed {prior.payload!r} and "
                f"{vote.payload!r} for task {vote.task_id} epoch {vote.epoch}"
            )
        # Identical re-delivery is benign; keep the first.

    def seal(self, task_id: str, epoch: int, total_peers: int) -> str:
        honest = total_peers - len(self._quarantined)
        needed = 2 * self.f + 1
        if honest < needed:
            raise QuorumUnreachable(
                f"only {honest} non-quarantined peers, need {needed}"
            )
        votes = [
            v for (p, t, e), v in self._seen.items()
            if t == task_id and e == epoch and p not in self._quarantined
        ]
        payloads = {v.payload for v in votes}
        if len(payloads) != 1:
            raise EquivocationDetected(
                f"conflicting payloads in quorum for {task_id}: {payloads}"
            )
        if len(votes) < needed:
            raise QuorumUnreachable(
                f"{len(votes)} consistent votes, need {needed}"
            )
        return next(iter(payloads))
