# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-withhold-quorum-attestation-under-equivocating-peer-agents-the-attestation-epoch-fork-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-withhold-quorum-attestation-under-equivocating-peer-agents-the-attestation-epoch-fork-invariant.warrant.json
# Markdown SHA-256:   2108705ca4bbe27ee79e996c0e889c883b9d122d85b019f95a3eaeae1247532a
# Code AST SHA-256:   a94ab6ec128676567713d0ab7eb99a627d2728de25fcb59835d684f6123a84a6
# Verified Classes:   AttestationEpochMismatch, Commitment, AttestationRequest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class AttestationEpochMismatch(RuntimeError):
    """Raised when an instance is asked to sign a result attestation whose
    epoch does not match the epoch recorded at task commitment. Signing
    across an epoch boundary is what enables split-quorum forgery, even
    when the attested content is locally correct."""


@dataclass(frozen=True)
class Commitment:
    task_id: str
    epoch: int


@dataclass(frozen=True)
class AttestationRequest:
    task_id: str
    result_hash: str
    epoch: int


def attest(
    commitment: Commitment,
    request: AttestationRequest,
    recomputed_hash: str,
) -> str:
    if request.task_id != commitment.task_id:
        raise AttestationEpochMismatch(
            f"request task {request.task_id} != committed {commitment.task_id}"
        )
    if request.result_hash != recomputed_hash:
        raise AttestationEpochMismatch(
            f"content invalid for {request.task_id}: "
            f"{request.result_hash} != {recomputed_hash}"
        )
    if request.epoch != commitment.epoch:
        # Content is correct, but the epoch is wrong. Withhold the signature.
        raise AttestationEpochMismatch(
            f"epoch mismatch for {request.task_id}: "
            f"request epoch {request.epoch} != committed epoch {commitment.epoch}; "
            f"withholding attestation to preserve quorum disjointness"
        )
    return f"signed:{request.task_id}:{request.result_hash}:{request.epoch}"


def count_epoch_quorum(votes: list[tuple[str, int]], quorum: int) -> int:
    """Return the largest same-epoch signer count; aggregator must use this,
    never a raw signature count keyed only on (task_id, result_hash)."""
    tally: dict[int, int] = {}
    for _signer, epoch in votes:
        tally[epoch] = tally.get(epoch, 0) + 1
    return max(tally.values(), default=0)
