# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-slow-byzantine-peer-from-an-honest-straggler-during-multi-agent-plan-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-slow-byzantine-peer-from-an-honest-straggler-during-multi-agent-plan-commitment.warrant.json
# Markdown SHA-256:   8d66b70941ceadb0843b3289b50abec98866b499610e66432b29b22cf69c515f
# Code AST SHA-256:   9d7105c2a64f09ab50bb75efb02ccf56713720682b150013feacf22c92c70669
# Verified Classes:   CommitmentAttributionError, SignedVote, PeerState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CommitmentAttributionError(RuntimeError):
    """Raised when a peer is ejected on unprovable (silence-only) evidence."""


@dataclass(frozen=True)
class SignedVote:
    instance_id: str
    view: int
    plan_hash: str
    signature: str  # valid iff signed by instance_id over (view, plan_hash)


@dataclass
class PeerState:
    instance_id: str
    last_vote: Optional[SignedVote] = None
    silent_views: int = 0
    quarantined: bool = False


def attribute_peer(
    peer: PeerState,
    incoming_votes: list[SignedVote],
    stall_budget: int,
    honest_quorum_after_removal: int,
    required_quorum: int,
) -> str:
    """
    Decide fault attribution for one peer under the deferral invariant.

    Returns one of: 'ok', 'quarantined', 'ejected', 'halt'.
    """
    # Tier 2: only a signed, contradictory pair proves Byzantine fault.
    seen: dict[tuple[int, str], SignedVote] = {}
    for v in incoming_votes:
        if v.instance_id != peer.instance_id:
            raise CommitmentAttributionError(
                f"vote for {v.instance_id} routed to peer {peer.instance_id}"
            )
        key = (v.view, v.plan_hash)
        if key in seen and seen[key].signature != v.signature:
            # Two distinct valid signatures for the same (view, plan): equivocation.
            peer.quarantined = True
            return "ejected"
        seen[key] = v

    # Detect equivocation across plan_hash within the same view.
    by_view: dict[int, set[str]] = {}
    for v in incoming_votes:
        by_view.setdefault(v.view, set()).add(v.plan_hash)
    for view, plans in by_view.items():
        if len(plans) > 1:
            peer.quarantined = True
            return "ejected"

    # Tier 1: silence is not evidence. Extend, then quarantine, never eject.
    if not incoming_votes:
        peer.silent_views += 1
        if peer.silent_views >= stall_budget:
            if honest_quorum_after_removal < required_quorum:
                # Ejecting here would drop below quorum: halt, do not eject.
                raise CommitmentAttributionError(
                    f"peer {peer.instance_id} silent for {peer.silent_views} views "
                    f"but removal leaves quorum {honest_quorum_after_removal} "
                    f"< required {required_quorum}; halt and escalate"
                )
            peer.quarantined = True
            return "quarantined"
        return "ok"

    peer.silent_views = 0
    return "ok"
