# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-committed-task-commitment-quorum-as-void-equivocation-induced-commitment-split-brain-under-byzantine-peers.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-committed-task-commitment-quorum-as-void-equivocation-induced-commitment-split-brain-under-byzantine-peers.warrant.json
# Markdown SHA-256:   516ab2d99aa154bb1818f3524b89aafe1fbe7f374d2ac96ad83fb9e1d9a0438c
# Code AST SHA-256:   98c9d57c83c834457e98a65035747e5a78b7110cd87f527daa6eebabf92d213b
# Verified Classes:   CommitmentSplitBrainError, Vote
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CommitmentSplitBrainError(RuntimeError):
    """Raised when a collected quorum is numerically sufficient but does not
    describe a single (digest, epoch) commitment. Fails closed: the instance
    must NOT commit and must escalate to a higher epoch."""


@dataclass(frozen=True)
class Vote:
    voter: str
    task_id: str
    epoch: int
    digest: str          # H(proposal_body || epoch || task_id)
    signature: str       # assumed pre-verified by transport layer


def _digest(proposal_body: str, epoch: int, task_id: str) -> str:
    h = hashlib.sha256()
    h.update(proposal_body.encode())
    h.update(b"|")
    h.update(str(epoch).encode())
    h.update(b"|")
    h.update(task_id.encode())
    return h.hexdigest()


def assert_commitment_safe(
    votes: list[Vote],
    proposal_body: str,
    task_id: str,
    threshold: int,
    max_epoch_seen: int,
    own_prior_vote_digest: str | None,
) -> str:
    """Validate that a collected quorum licenses a commit on exactly one digest.

    Returns the committed digest on success. Raises CommitmentSplitBrainError
    on any violation of: single-digest, epoch fencing, body/digest binding,
    or self-equivocation.
    """
    if len(votes) < threshold:
        raise CommitmentSplitBrainError(
            f"insufficient votes: {len(votes)} < threshold {threshold}"
        )

    digests = {v.digest for v in votes}
    if len(digests) != 1:
        # The core bug: signature count was fine, digest set was not.
        raise CommitmentSplitBrainError(
            f"equivocation across digests {sorted(digests)} for task {task_id}; "
            f"quorum is split, refusing to commit"
        )
    committed_digest = digests.pop()

    # Epoch fencing: reject stale votes from a superseded coordinator.
    stale = [v.voter for v in votes if v.epoch < max_epoch_seen]
    if stale:
        raise CommitmentSplitBrainError(
            f"stale-epoch votes from {stale} (max_epoch_seen={max_epoch_seen}); "
            f"possible unfenced coordinator"
        )

    # Body/digest binding: the votes must reference THIS proposal body.
    expected = _digest(proposal_body, votes[0].epoch, task_id)
    if committed_digest != expected:
        raise CommitmentSplitBrainError(
            f"digest/body mismatch: votes commit {committed_digest}, "
            f"body hashes to {expected}"
        )

    # Self-equivocation: we must not have already voted a different digest
    # in this epoch and then commit a conflicting one.
    if own_prior_vote_digest is not None and own_prior_vote_digest != committed_digest:
        raise CommitmentSplitBrainError(
            f"self-equivocation risk: prior vote {own_prior_vote_digest} "
            f"!= committed {committed_digest}; must advance epoch, not commit"
        )

    return committed_digest
