# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-quorum-certificate-equivocation-equivariance-loss-in-byzantine-committed-agent-task-ledgers.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-quorum-certificate-equivocation-equivariance-loss-in-byzantine-committed-agent-task-ledgers.warrant.json
# Markdown SHA-256:   2407344b0c89ff481fdb11227fa8b3b89ba537eee93aadca49ab9eb3f968c1a6
# Code AST SHA-256:   84089485377fd3d4e3cb6e1a5d48334df2e2ddfb0ed86dc0fa3d21613c738afa
# Verified Classes:   ContextDivergenceFork, EquivocationDetected, Vote
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

class ContextDivergenceFork(RuntimeError):
    """Raised when two QCs at the same height/round certify different context hashes."""
    pass

class EquivocationDetected(RuntimeError):
    """Raised only on identical (h, r, P, H(C_vote)) with conflicting decisions."""
    pass

@dataclass(frozen=True)
class Vote:
    replica_id: str
    height: int
    round: int
    proposal_digest: str
    context_hash: str          # H(C_vote) — MUST be signed
    decision: str              # "accept" | "reject"
    model_version: str
    seed: int

def context_hash(snapshot_bytes: bytes) -> str:
    return hashlib.sha256(snapshot_bytes).hexdigest()

def verify_vote_against_frozen_context(vote: Vote, frozen_snapshot: bytes) -> None:
    if context_hash(frozen_snapshot) != vote.context_hash:
        # Honest replica could not reproduce its own signed context.
        raise ContextDivergenceFork(
            f"replica {vote.replica_id} signed H(C)={vote.context_hash} "
            f"but frozen snapshot hashes to {context_hash(frozen_snapshot)}"
        )

def classify_conflict(a: Vote, b: Vote) -> str:
    if (a.replica_id, a.height, a.round, a.proposal_digest) != \
       (b.replica_id, b.height, b.round, b.proposal_digest):
        return "unrelated"
    if a.context_hash != b.context_hash:
        # Different context -> divergence, NOT equivocation.
        return "context_divergence"
    if a.decision != b.decision:
        raise EquivocationDetected(
            f"replica {a.replica_id} double-signed same context "
            f"{a.context_hash} at h={a.height} r={a.round}: "
            f"{a.decision} vs {b.decision}"
        )
    return "duplicate"

def form_quorum_certificate(votes: list[Vote], f: int) -> str:
    quorum = 2 * f + 1
    if len(votes) < quorum:
        raise ContextDivergenceFork(f"insufficient votes: {len(votes)} < {quorum}")
    hashes = {v.context_hash for v in votes}
    if len(hashes) != 1:
        raise ContextDivergenceFork(
            f"QC signers committed to {len(hashes)} distinct context hashes: {hashes}"
        )
    versions = {v.model_version for v in votes}
    if len(versions) != 1:
        raise ContextDivergenceFork(f"QC spans rolling model versions: {versions}")
    return next(iter(hashes))
