# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-quorum-certificate-divergence-during-byzantine-agent-task-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-quorum-certificate-divergence-during-byzantine-agent-task-commitment.warrant.json
# Markdown SHA-256:   67aeea1ef52e9afe296d6bd7bca80d2be13d1cdacb51bfd48482d2c2ba122b5b
# Code AST SHA-256:   8a70a399a7d0ca05614a9b1a4595eb4f17e1f5e6b6b5b42fcd6c48a7866ff66a
# Verified Classes:   VoteEquivocationError, CommitVote, VoteCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class VoteEquivocationError(RuntimeError):
    """Raised when one agent identity emits conflicting payloads for the same commit slot."""
    pass


@dataclass(frozen=True)
class CommitVote:
    sender: str
    slot: str
    view: int
    request_id: str
    verdict_payload: dict
    digest: str  # H(task_ref) in the unsound scheme; H(task_ref || payload) in the sound one


def canonical(payload: dict) -> bytes:
    return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()


def sound_digest(task_ref: str, payload: dict) -> str:
    h = hashlib.sha256()
    h.update(task_ref.encode())
    h.update(b"|")
    h.update(canonical(payload))
    return h.hexdigest()


class VoteCache:
    """Enforces the idempotency invariant: vote is a pure function of (slot, view, request_id)."""

    def __init__(self) -> None:
        self._cache: dict[tuple[str, int, str], CommitVote] = {}

    def record(self, vote: CommitVote) -> CommitVote:
        key = (vote.slot, vote.view, vote.request_id)
        prior = self._cache.get(key)
        if prior is None:
            self._cache[key] = vote
            return vote
        # Re-invocation must return the cached vote, never a re-sample.
        if canonical(prior.verdict_payload) != canonical(vote.verdict_payload):
            raise VoteEquivocationError(
                f"agent {vote.sender} re-sampled payload for slot={vote.slot} "
                f"view={vote.view} request_id={vote.request_id}: "
                f"{prior.verdict_payload} != {vote.verdict_payload}"
            )
        return prior


def commit_gate(votes: list[CommitVote], quorum: int) -> dict:
    """Reject if two votes share (sender, slot, digest) but differ in payload hash."""
    seen: dict[tuple[str, str, str], bytes] = {}
    for v in votes:
        key = (v.sender, v.slot, v.digest)
        payload_hash = hashlib.sha256(canonical(v.verdict_payload)).digest()
        prior = seen.get(key)
        if prior is not None and prior != payload_hash:
            raise VoteEquivocationError(
                f"same-digest payload conflict on slot={v.slot} digest={v.digest[:12]} "
                f"from {v.sender}: payload hash divergence"
            )
        seen[key] = payload_hash
    if len(votes) < quorum:
        raise VoteEquivocationError(f"quorum not met: {len(votes)} < {quorum}")
    return {"committed": votes[0].slot, "payload": votes[0].verdict_payload}
