# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-peer-s-commitment-vote-as-a-liveness-attack-rather-than-a-safety-violation-in-multi-agent-task-co.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-peer-s-commitment-vote-as-a-liveness-attack-rather-than-a-safety-violation-in-multi-agent-task-co.warrant.json
# Markdown SHA-256:   32fcfd41dff7dd8fb1bf50ad0b6822afd45961afc110a659a9ee15a7fa6544b8
# Code AST SHA-256:   a60fe189f9f4f37d44edce3aea881064e7d4048b88b09133ca08c934baed7ba2
# Verified Classes:   ByzantineLivenessError, InsufficientQuorumConfigError, Vote, EquivocationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ByzantineLivenessError(RuntimeError):
    """Raised when a marginal peer blocks quorum across bounded retries,
    indicating equivocation or selective abstention rather than a partition."""
    pass


class InsufficientQuorumConfigError(RuntimeError):
    pass


@dataclass
class Vote:
    peer_id: str
    round_id: int
    recipient_id: str
    nonce: str
    decision: str          # "commit" | "abstain" | "reject"
    plan_hash: str

    def fingerprint(self) -> str:
        raw = f"{self.peer_id}|{self.round_id}|{self.nonce}|{self.decision}|{self.plan_hash}"
        return hashlib.sha256(raw.encode()).hexdigest()


@dataclass
class EquivocationLedger:
    entries: list = field(default_factory=list)

    def record(self, v: Vote) -> None:
        self.entries.append(v)

    def cross_view_proof(self, peer_id: str, round_id: int) -> Optional[tuple]:
        views = [e for e in self.entries if e.peer_id == peer_id and e.round_id == round_id]
        by_recipient = {}
        for e in views:
            by_recipient.setdefault(e.recipient_id, set()).add((e.decision, e.nonce, e.plan_hash))
        distinct = {fp for fps in by_recipient.values() for fp in fps}
        if len(distinct) > 1:
            return (peer_id, round_id, sorted(distinct))
        return None


def evaluate_round(
    n: int,
    f: int,
    q: int,
    round_id: int,
    votes: list,
    retries: int,
    ledger: EquivocationLedger,
    r_max: int = 2,
) -> str:
    if n < 3 * f + 1 or q < 2 * f + 1:
        raise InsufficientQuorumConfigError(
            f"n={n}, f={f}, q={q} violates BFT bound n>=3f+1 and q>=2f+1"
        )

    commits = [v for v in votes if v.decision == "commit"]
    blockers = [v for v in votes if v.decision != "commit"]

    if len(commits) >= q:
        return "COMMIT"

    # marginal blocker: removing it would not change the shortfall, but its
    # vote is the difference between quorum and non-quorum
    marginal = len(commits) == q - 1 and len(blockers) >= 1

    for b in blockers:
        proof = ledger.cross_view_proof(b.peer_id, round_id)
        if proof is not None:
            # cross-view contradiction: this is a safety-relevant ejection,
            # not merely a liveness stall
            return f"EJECT_SAFETY:{b.peer_id}"

    if marginal and retries >= r_max:
        # bounded retries exhausted with a marginal blocker and no cross-view
        # proof yet: escalate to view-change, do NOT eject
        suspect = blockers[0].peer_id
        raise ByzantineLivenessError(
            f"round {round_id}: marginal blocker {suspect} stalled quorum "
            f"({len(commits)}/{q}) across {retries} retries with no cross-view proof; "
            f"escalating to view-change (not ejection)"
        )

    return "RETRY"


def run_round(ledger: EquivocationLedger, votes: list, retries: int) -> str:
    result = evaluate_round(n=7, f=2, q=5, round_id=41, votes=votes,
                            retries=retries, ledger=ledger)
    if result.startswith("EJECT_SAFETY"):
        peer = result.split(":")[1]
        return f"ejected {peer} on cross-view proof"
    return result
