# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-quorum-certificate-equivocation-equivariance-failure-in-bft-agent-task-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-quorum-certificate-equivocation-equivariance-failure-in-bft-agent-task-commitment.warrant.json
# Markdown SHA-256:   a388a9c7832190a7dcc5134ce59f3036321497203c97d8dbca18bec6908deb0e
# Code AST SHA-256:   bee67cca8966c15c1bf6963a65947307fb442343917523353d54d96da16519ee
# Verified Classes:   UnprovableEquivocationError, CommitmentVote, EquivocationProof
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Iterable


class UnprovableEquivocationError(RuntimeError):
    """Raised when an auditor attempts to assert equivocation without a
    same-key signature pair. This is the guard that prevents honest
    equivariance failure from being misadjudicated as Byzantine fault."""


@dataclass(frozen=True)
class CommitmentVote:
    epoch: int
    task_id: str
    signer: str          # public key fingerprint
    digest: str          # sha256 of canonical commitment payload
    signature: bytes


@dataclass
class EquivocationProof:
    signer: str
    digest_a: str
    digest_b: str
    sig_a: bytes
    sig_b: bytes


def canonical_digest(payload: dict) -> str:
    # Deterministic canonicalization. Note: for LLM-produced payloads this
    # is only approximately stable; see Condition of Validity.
    return hashlib.sha256(
        json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def build_equivocation_proof(
    votes: Iterable[CommitmentVote],
) -> EquivocationProof | None:
    """Construct an equivocation proof ONLY from two signatures by the same
    key over distinct digests in the same epoch. Set-level digest diversity
    is explicitly NOT sufficient and must not be accepted."""
    by_key: dict[str, list[CommitmentVote]] = {}
    for v in votes:
        by_key.setdefault(v.signer, []).append(v)

    for signer, vs in by_key.items():
        digests = {v.digest for v in vs}
        if len(digests) > 1:
            # Same key, two distinct digests -> genuine equivocation.
            a, b = next(v for v in vs if v.digest == next(iter(digests))), None
            for v in vs:
                if v.digest != a.digest:
                    b = v
                    break
            assert b is not None
            return EquivocationProof(
                signer=signer,
                digest_a=a.digest,
                digest_b=b.digest,
                sig_a=a.signature,
                sig_b=b.signature,
            )
    return None


def adjudicate_epoch(votes: list[CommitmentVote]) -> str:
    """Returns 'commit', 'reconcile', or 'slash'."""
    if not votes:
        raise UnprovableEquivocationError("empty vote set cannot be adjudicated")

    proof = build_equivocation_proof(votes)
    if proof is not None:
        return "slash"

    # Distinct-key digest divergence is NOT equivocation. It is honest
    # equivariance failure and must route to reconciliation, never slashing.
    digests = {v.digest for v in votes}
    if len(digests) > 1:
        return "reconcile"

    # Unanimous digest: commit if quorum satisfied.
    if len(votes) >= 3:  # 2f+1 with f=1
        return "commit"

    raise UnprovableEquivocationError(
        f"insufficient votes for quorum: {len(votes)} < 3, and no equivocation proof"
    )


def assert_slashable(votes: list[CommitmentVote]) -> EquivocationProof:
    """Entry point for the slashing subsystem. Refuses any verdict not backed
    by a same-key signature pair."""
    proof = build_equivocation_proof(votes)
    if proof is None:
        raise UnprovableEquivocationError(
            "slashing attempted without same-key equivocation proof; "
            "this is honest equivariance failure, route to reconcile"
        )
    return proof
