# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-certificate-as-stale-when-the-certificate-s-view-number-is-valid-but-its-membership-ep.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-certificate-as-stale-when-the-certificate-s-view-number-is-valid-but-its-membership-ep.warrant.json
# Markdown SHA-256:   1bb9a11d668e8b529411fc8cb519664bb9ba8c75e18cdadd8ecbb7824baec0bf
# Code AST SHA-256:   21e1473479205cba6d778183e1c76b335acf955d94e0e75a218fff41df718c20
# Verified Classes:   StaleQuorumCertificateError, QuorumCertificate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class StaleQuorumCertificateError(RuntimeError):
    """Raised when a QC is cryptographically valid but epoch-bound to a
    membership set that is no longer current, and no carry-forward proof
    accompanies it."""


@dataclass(frozen=True)
class QuorumCertificate:
    epoch: int
    view: int
    digest: str
    signers: FrozenSet[str]
    carry_forward_epoch: int | None = None  # epoch in which commitment was re-signed


def verify_qc_for_commitment(
    qc: QuorumCertificate,
    current_epoch: int,
    membership: FrozenSet[str],
    threshold: int,
    committed_epoch_watermark: int,
) -> bool:
    # Replay fence: never re-commit below the watermark.
    if qc.epoch < committed_epoch_watermark:
        raise StaleQuorumCertificateError(
            f"QC epoch {qc.epoch} below committed watermark "
            f"{committed_epoch_watermark}; replay resurrection blocked."
        )

    # Future-epoch QC: agent is behind; must resync, not commit.
    if qc.epoch > current_epoch:
        raise StaleQuorumCertificateError(
            f"QC epoch {qc.epoch} ahead of current epoch {current_epoch}; "
            f"resync membership before committing."
        )

    # Same-epoch QC: verify signers against *current* membership.
    if qc.epoch == current_epoch:
        if not qc.signers.issubset(membership):
            raise StaleQuorumCertificateError(
                f"QC signers {sorted(qc.signers - membership)} not in current "
                f"epoch-{current_epoch} membership; assembled against stale cache."
            )
        if len(qc.signers) < threshold:
            raise StaleQuorumCertificateError(
                f"QC threshold {len(qc.signers)} < {threshold} under current membership."
            )
        return True

    # Past-epoch QC: only acceptable with a carry-forward proof into current epoch.
    if qc.carry_forward_epoch != current_epoch:
        raise StaleQuorumCertificateError(
            f"QC from epoch {qc.epoch} lacks carry-forward into epoch "
            f"{current_epoch}; must re-propose under current membership."
        )
    return True
