# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-to-a-byzantine-quorum-the-equivocation-witness-gap-in-multi-agent-task-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-to-a-byzantine-quorum-the-equivocation-witness-gap-in-multi-agent-task-commit.warrant.json
# Markdown SHA-256:   57a7a51082b46e6d94cb37f45d9aa23cb7bf51887b81d0387a0cb42d5eb45c2c
# Code AST SHA-256:   d2e4cbd66f8337f700500ff31481a050ac04217f9770f49ebed13eb732b78bf8
# Verified Classes:   EquivocationWitnessGap, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class EquivocationWitnessGap(RuntimeError):
    """Raised when a quorum is reachable by count but at least one vote
    lacks a verifiable non-equivocation witness, making split-brain
    commit undetectable from the receiver's local view."""
    pass


@dataclass(frozen=True)
class Vote:
    voter: str
    proposal_hash: str
    view: int
    signature: bytes
    predecessor_hash: Optional[str]  # hash of voter's prior vote in same view; None = no witness


def certify_commit(
    votes: list[Vote],
    f: int,
    self_id: str,
    known_predecessors: set[str],
) -> str:
    """Return the committed proposal hash, or raise if the quorum cannot
    be certified as non-equivocating. Quorum = 2f+1."""
    quorum = 2 * f + 1
    if len(votes) < quorum:
        raise EquivocationWitnessGap(
            f"insufficient votes: {len(votes)} < quorum {quorum}"
        )

    proposals = {v.proposal_hash for v in votes}
    if len(proposals) > 1:
        # Two distinct proposals already in-hand: equivocation is provable.
        raise EquivocationWitnessGap(
            f"conflicting proposals in quorum: {sorted(proposals)}"
        )

    for v in votes:
        if v.voter == self_id:
            continue  # self-votes are trivially non-equivocating
        if v.predecessor_hash is None:
            raise EquivocationWitnessGap(
                f"vote from {v.voter} in view {v.view} carries no "
                f"non-equivocation witness; cannot distinguish first-vote "
                f"from second-vote-in-disguise"
            )
        if v.predecessor_hash not in known_predecessors:
            raise EquivocationWitnessGap(
                f"vote from {v.voter} references predecessor "
                f"{v.predecessor_hash} not locally verifiable; "
                f"refusing to commit on un-walkable chain"
            )

    return votes[0].proposal_hash
