# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-committed-task-quorum-as-valid-when-a-byzantine-auditor-can-equivocate-across-the-prepare-and-commit-phases-of-a-multi.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-committed-task-quorum-as-valid-when-a-byzantine-auditor-can-equivocate-across-the-prepare-and-commit-phases-of-a-multi.warrant.json
# Markdown SHA-256:   e7c17e4cbaadff4fc4f03a80bc7c90d6e2a70794330d367926d3ba61ba10813e
# Code AST SHA-256:   1f5b6df33990032d2d56f12f85bada75f4432c814d73770296f52e85dd964d91
# Verified Classes:   EquivocationDetected, Vote
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationDetected(RuntimeError):
    """Raised when a local quorum cannot be certified as globally consistent."""


@dataclass(frozen=True)
class Vote:
    auditor_id: str
    round_id: str
    task_id: str
    assignment: str          # executor id the vote commits the task to
    view: int
    signature: bytes         # authentic signature over the digest below

    def digest(self) -> bytes:
        # The digest MUST cover the assignment, not just (round, task).
        # Omitting `assignment` makes equivocation unprovable.
        payload = f"{self.round_id}|{self.task_id}|{self.assignment}|{self.view}"
        return hashlib.sha256(payload.encode()).digest()


def certify_quorum(votes: list[Vote], f: int, expected_assignment: str) -> str:
    """Return the certified assignment, or raise if the quorum is unsound.

    A quorum is sound only if (a) it has 2f+1 votes, (b) every vote is bound
    to the same round/task/assignment/view digest, and (c) no auditor appears
    twice. Counting alone is insufficient: a Byzantine auditor can contribute
    one authentic vote to two disjoint quorums.
    """
    quorum_size = 2 * f + 1
    if len(votes) < quorum_size:
        raise EquivocationDetected(
            f"short quorum: have {len(votes)}, need {quorum_size}"
        )

    seen_auditors: set[str] = set()
    digests: set[bytes] = set()
    for v in votes:
        if v.auditor_id in seen_auditors:
            raise EquivocationDetected(
                f"auditor {v.auditor_id} voted twice in round {v.round_id}"
            )
        seen_auditors.add(v.auditor_id)
        digests.add(v.digest())

    if len(digests) != 1:
        # This is the equivocation signature: the same round/task produced
        # votes bound to more than one assignment. The quorum is split.
        raise EquivocationDetected(
            f"split quorum in round {votes[0].round_id}: "
            f"{len(digests)} distinct assignment digests across {len(votes)} votes"
        )

    assignment = votes[0].assignment
    if assignment != expected_assignment:
        raise EquivocationDetected(
            f"quorum certifies {assignment}, executor expected {expected_assignment}"
        )
    return assignment


def commit_task(votes: list[Vote], f: int, executor_id: str) -> str:
    """Ratify a task commitment only after quorum certification."""
    try:
        return certify_quorum(votes, f, expected_assignment=executor_id)
    except EquivocationDetected:
        # Do NOT retry blindly: a retry against the same split will re-split.
        # Escalate to a view change so the round is re-run under a new view.
        raise
