# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-byzantine-fault-tolerant-consensus-but-its-signed-warrant-outlives-the-peer-set-that-notarized-i.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-byzantine-fault-tolerant-consensus-but-its-signed-warrant-outlives-the-peer-set-that-notarized-i.warrant.json
# Markdown SHA-256:   f7642c4ceea2140f21dc64c586cc8d38d0e50938c43870c9ac9d3ea950db7eb9
# Code AST SHA-256:   303989471bb16f109e67e49833ef719e00f358b21775e965ce48079313185584
# Verified Classes:   QuorumSetSkewError, Certificate, Epoch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Mapping


class QuorumSetSkewError(RuntimeError):
    """Raised when a commit certificate's notarizing quorum cannot be reconciled
    with the verifier's epoch chain, or when acceptance would open the
    rotated-quorum equivocation window."""


@dataclass(frozen=True)
class Certificate:
    task_id: str
    epoch: int
    signers: FrozenSet[str]


@dataclass(frozen=True)
class Epoch:
    number: int
    members: FrozenSet[str]
    fault_tolerance: int

    @property
    def threshold(self) -> int:
        return 2 * self.fault_tolerance + 1


def verify_certificate(
    cert: Certificate,
    epoch_chain: Mapping[int, Epoch],
    current_epoch: int,
) -> str:
    """Returns 'accept', 're-attest', or raises QuorumSetSkewError.

    A certificate is only counted against the epoch it names. Trust in that
    epoch requires it to be a prefix of the verifier's chain.
    """
    if cert.epoch not in epoch_chain:
        raise QuorumSetSkewError(
            f"certificate for task {cert.task_id!r} names epoch {cert.epoch}, "
            f"which is not in the verifier's epoch chain "
            f"(known: {sorted(epoch_chain)})"
        )

    cert_epoch = epoch_chain[cert.epoch]
    counted = cert.signers & cert_epoch.members
    if len(counted) < cert_epoch.threshold:
        raise QuorumSetSkewError(
            f"certificate for task {cert.task_id!r} has only "
            f"{len(counted)} valid signers under epoch {cert.epoch} "
            f"(threshold {cert_epoch.threshold}); "
            f"signers not in epoch: {sorted(cert.signers - cert_epoch.members)}"
        )

    if cert.epoch == current_epoch:
        return "accept"

    if cert.epoch > current_epoch:
        raise QuorumSetSkewError(
            f"certificate for task {cert.task_id!r} claims epoch {cert.epoch} "
            f"ahead of verifier's current epoch {current_epoch}"
        )

    current = epoch_chain[current_epoch]
    intersection = cert_epoch.members & current.members
    honest_intersection_floor = len(intersection) - current.fault_tolerance
    if honest_intersection_floor < current.fault_tolerance + 1:
        raise QuorumSetSkewError(
            f"certificate for task {cert.task_id!r} from superseded epoch "
            f"{cert.epoch} intersects current epoch {current_epoch} in only "
            f"{len(intersection)} replicas "
            f"({honest_intersection_floor} honest at f={current.fault_tolerance}); "
            f"rotated-quorum equivocation window is open"
        )

    return "re-attest"
