# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-equivocation-tolerant-blackboard-replication-from-silently-collapsing-when-agent-quorums-disagree-about-which-write-history-t.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-equivocation-tolerant-blackboard-replication-from-silently-collapsing-when-agent-quorums-disagree-about-which-write-history-t.warrant.json
# Markdown SHA-256:   6f0a25891ae31f7cc9a049540cc873379a5d786e27bd97a825b365748a4c6999
# Code AST SHA-256:   bb8b52c3e80b3d3adf1e1a5a746b451b177d499c965b9db74d9946004d01cad1
# Verified Classes:   EquivocationGuardError, SignedCommitment, VoteCollector
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Dict, Set, Tuple


class EquivocationGuardError(RuntimeError):
    """Raised when the quorum/vote layer cannot soundly certify a write."""
    pass


def canonical(content: dict) -> bytes:
    # Total function: fixed key order, no float freedom (floats pre-quantized),
    # no whitespace. This is the ONLY serialization allowed before signing.
    return json.dumps(
        content, sort_keys=True, separators=(",", ":"), ensure_ascii=True
    ).encode("utf-8")


def digest(content: dict) -> str:
    return hashlib.sha256(canonical(content)).hexdigest()


@dataclass
class SignedCommitment:
    writer: str
    seq: int
    prev: str
    content_digest: str  # signature is assumed to cover this field
    signature: str


@dataclass
class VoteCollector:
    # Keyed on (writer, seq, digest) — NOT on (writer, seq) or header hash.
    votes: Dict[Tuple[str, int, str], Set[str]] = field(default_factory=dict)
    quorum: int = 4

    def add_vote(self, writer: str, seq: int, content_digest: str, signer: str) -> None:
        key = (writer, seq, content_digest)
        self.votes.setdefault(key, set()).add(signer)
        # A single signer voting for two digests at one seq is a collector/replay
        # fault; halt rather than mint two certificates.
        conflicting = [
            k for k in self.votes
            if k[0] == writer and k[1] == seq and k[2] != content_digest
            and signer in self.votes[k]
        ]
        if conflicting:
            raise EquivocationGuardError(
                f"signer {signer} counted under two digests at "
                f"({writer},{seq}): {content_digest} vs {conflicting[0][2]}"
            )

    def certify(self, commitment: SignedCommitment, received_content: dict) -> bool:
        recomputed = digest(received_content)
        if recomputed != commitment.content_digest:
            # Payload does not match the signed commitment: reject, do NOT evict.
            raise EquivocationGuardError(
                f"content digest mismatch for {commitment.writer}@{commitment.seq}: "
                f"signed {commitment.content_digest}, got {recomputed}"
            )
        key = (commitment.writer, commitment.seq, commitment.content_digest)
        signers = self.votes.get(key, set())
        if len(signers) < self.quorum:
            return False
        # Equivocation is two *signed digest commitments* at one seq.
        rival_digests = {
            k[2] for k in self.votes
            if k[0] == commitment.writer and k[1] == commitment.seq
            and k[2] != commitment.content_digest
            and len(self.votes[k]) >= self.quorum
        }
        if rival_digests:
            raise EquivocationGuardError(
                f"two certified digests at ({commitment.writer},{commitment.seq}): "
                f"{commitment.content_digest} vs {rival_digests}"
            )
        return True


def resume_from_checkpoint(collector: VoteCollector,
                           commitment: SignedCommitment,
                           stored_content: dict) -> dict:
    try:
        if not collector.certify(commitment, stored_content):
            raise EquivocationGuardError(
                f"insufficient quorum for {commitment.writer}@{commitment.seq}"
            )
    except EquivocationGuardError:
        # Halt and escalate; never pick a side silently.
        raise
    return stored_content
