# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-peer-agent-before-committing-shared-state-under-byzantine-fault-tolerant-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-peer-agent-before-committing-shared-state-under-byzantine-fault-tolerant-consensus.warrant.json
# Markdown SHA-256:   84fe75045593c1eb35f863130a1698bce94fa5f4cb788ddcadffe101baf1e251
# Code AST SHA-256:   7a34e2cce8083d41d5b8d17129114d665c3108b4a621b356780ba08f23dc4bca
# Verified Classes:   EquivocationDetected, CommitWindowExpired, SignedVote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass

class EquivocationDetected(RuntimeError):
    """Raised when a peer is proven to have signed conflicting digests at the same (view, seq)."""
    pass

class CommitWindowExpired(EquivocationDetected):
    """Raised when the equivocation-detection window elapses without a no-equivocation certificate."""
    pass

@dataclass(frozen=True)
class SignedVote:
    agent_id: str
    view: int
    seq: int
    digest: str
    signature: bytes

def detect_equivocation(votes: list[SignedVote]) -> tuple[str, str]:
    """Return (digest_a, digest_b) if any agent signed two digests at same (view, seq)."""
    seen: dict[tuple[str, int, int], str] = {}
    for v in votes:
        key = (v.agent_id, v.view, v.seq)
        if key in seen and seen[key] != v.digest:
            return seen[key], v.digest
        seen[key] = v.digest
    return ("", "")

def commit(
    votes: list[SignedVote],
    f: int,
    p99_latency_s: float,
    sig_verify_s: float,
    window_start: float,
    now: float,
    no_equivocation_cert: bool,
) -> str:
    n = len({v.agent_id for v in votes})
    quorum = 2 * f + 1
    if n < quorum:
        raise EquivocationDetected(f"insufficient quorum: {n} < {quorum}")

    d1, d2 = detect_equivocation(votes)
    if d1 and d2:
        raise EquivocationDetected(
            f"peer equivocated at (view={votes[0].view}, seq={votes[0].seq}): "
            f"digests {d1!r} vs {d2!r}"
        )

    window = 2.0 * p99_latency_s + sig_verify_s
    if not no_equivocation_cert and (now - window_start) < window:
        raise CommitWindowExpired(
            f"equivocation window not elapsed: {(now - window_start):.3f}s < {window:.3f}s"
        )

    digests = {v.digest for v in votes}
    if len(digests) != 1:
        raise EquivocationDetected(f"conflicting digests in quorum: {digests}")
    return digests.pop()
