# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-quorum-certificate-it-cannot-re-derive-equivocation-tolerant-commitment-drift-in-multi-agent-task-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-quorum-certificate-it-cannot-re-derive-equivocation-tolerant-commitment-drift-in-multi-agent-task-consensus.warrant.json
# Markdown SHA-256:   139e70f1fe388cce22deefba5d4cefd7ea30c53d73a3b8ba4b0bcdc2cde8f532
# Code AST SHA-256:   9cdc1e37f254de3e6159e015be5a4b7180dd79d1896229287f9b9b0a3846e2ec
# Verified Classes:   UnderivableCertificateError, Vote, QuorumCert, VoteStore, Validator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, FrozenSet


class UnderivableCertificateError(RuntimeError):
    """Raised when a validator is asked to commit or adjudicate a certificate
    whose supporting votes it cannot re-derive from its own durable store."""
    pass


@dataclass(frozen=True)
class Vote:
    validator_id: str
    round: int
    batch_hash: str

    def digest(self) -> str:
        return hashlib.sha256(
            f"{self.validator_id}:{self.round}:{self.batch_hash}".encode()
        ).hexdigest()


@dataclass(frozen=True)
class QuorumCert:
    round: int
    batch_hash: str
    signer_set: FrozenSet[str]
    vote_digests: Dict[str, str]  # validator_id -> digest of the vote they signed
    aggregate_signature_valid: bool


@dataclass
class VoteStore:
    # (round, validator_id) -> Vote
    votes: Dict[tuple, Vote] = field(default_factory=dict)

    def get(self, round: int, validator_id: str) -> Vote | None:
        return self.votes.get((round, validator_id))


class Validator:
    def __init__(self, validator_id: str, quorum: int, store: VoteStore):
        self.validator_id = validator_id
        self.quorum = quorum
        self.store = store
        self.committed_rounds: set[int] = set()

    def derivable(self, cert: QuorumCert) -> bool:
        if not cert.aggregate_signature_valid:
            return False
        if len(cert.signer_set) < self.quorum:
            return False
        for signer in cert.signer_set:
            vote = self.store.get(cert.round, signer)
            if vote is None:
                return False
            if vote.digest() != cert.vote_digests.get(signer):
                return False
            if vote.batch_hash != cert.batch_hash:
                return False
        return True

    def accept_certificate(self, cert: QuorumCert) -> None:
        if not self.derivable(cert):
            # Certificate may be cryptographically valid but is epistemically
            # underivable: we cannot audit it, so we must not commit it.
            raise UnderivableCertificateError(
                f"validator {self.validator_id} cannot re-derive cert for round "
                f"{cert.round}: signer_set={sorted(cert.signer_set)}, "
                f"held={sorted(v for (r, v) in self.store.votes if r == cert.round)}"
            )
        self.committed_rounds.add(cert.round)

    def adjudicate_equivocation(
        self, cert_a: QuorumCert, cert_b: QuorumCert
    ) -> QuorumCert:
        if cert_a.round != cert_b.round:
            raise ValueError("certificates are from different rounds")
        if cert_a.batch_hash == cert_b.batch_hash:
            return cert_a
        # Both certificates claim the same round with different batches.
        # We may only adjudicate if we can re-derive BOTH; otherwise we cannot
        # distinguish a genuine equivocation from our own incomplete evidence.
        if not (self.derivable(cert_a) and self.derivable(cert_b)):
            raise UnderivableCertificateError(
                f"validator {self.validator_id} cannot adjudicate round "
                f"{cert_a.round}: at least one certificate is underivable; "
                f"entering reconciliation-quarantine"
            )
        # Deterministic tiebreak: lexicographically smaller batch hash wins.
        # This is only safe because both certificates are fully re-derivable.
        return cert_a if cert_a.batch_hash < cert_b.batch_hash else cert_b
