# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-byzantine-quorum-thresholds-it-cannot-locally-verify.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-byzantine-quorum-thresholds-it-cannot-locally-verify.warrant.json
# Markdown SHA-256:   e7c395361b837cceeced213616647d9e70679aeec49e767a392fdd38cdb6e83c
# Code AST SHA-256:   839886182199e8c232f2294ce703572d21d07b4bbb1f11176606b89f2595c564
# Verified Classes:   QuorumEvidenceError, Prepare
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Set


class QuorumEvidenceError(RuntimeError):
    """Raised when an agent attempts to commit on evidence that cannot
    establish a Byzantine quorum for the target sequence number."""


@dataclass(frozen=True)
class Prepare:
    replica_id: str
    seq: int
    state_hash: str
    signature_verified: bool


def commit_on_quorum(
    prepares: list[Prepare],
    seq: int,
    state_hash: str,
    f: int,
    evidence_complete: bool,
) -> str:
    """
    Commit to state_hash at seq only if the evidence set proves a 2f+1 quorum
    AND is complete for seq AND contains no equivocating replica.

    evidence_complete must be True only if `prepares` is the full set of
    PREPAREs for `seq` — not a truncated tail, not a summary count.
    """
    quorum = 2 * f + 1

    if not evidence_complete:
        # The agent cannot prove the set is whole; a count here is a summary,
        # not a certificate. Refuse commit authority.
        raise QuorumEvidenceError(
            f"cannot commit at seq={seq}: vote set is truncated or summarized; "
            f"quorum safety requires the full PREPARE set, not a count"
        )

    # Build the per-replica vote map to detect equivocation.
    votes: Dict[str, Set[str]] = {}
    for p in prepares:
        if p.seq != seq:
            raise QuorumEvidenceError(
                f"prepare from {p.replica_id} has seq={p.seq}, expected {seq}; "
                f"sequence reuse invalidates intersection check"
            )
        if not p.signature_verified:
            raise QuorumEvidenceError(
                f"prepare from {p.replica_id} at seq={seq} is unsigned or "
                f"unverified; equivocation detection requires authenticated votes"
            )
        votes.setdefault(p.replica_id, set()).add(p.state_hash)

    equivocators = {r for r, hashes in votes.items() if len(hashes) > 1}
    if equivocators:
        raise QuorumEvidenceError(
            f"equivocation detected at seq={seq} by replicas "
            f"{sorted(equivocators)}; conflicting hashes present, "
            f"no commit is safe until the byzantine set is resolved"
        )

    supporters = {r for r, hashes in votes.items() if state_hash in hashes}
    if len(supporters) < quorum:
        raise QuorumEvidenceError(
            f"insufficient verified support for {state_hash} at seq={seq}: "
            f"got {len(supporters)}, need {quorum} (f={f})"
        )

    return state_hash
