# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-executes-under-a-warrant-that-was-revoked-between-its-attestation-epoch-and-its-next-tool-dispatch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-executes-under-a-warrant-that-was-revoked-between-its-attestation-epoch-and-its-next-tool-dispatch.warrant.json
# Markdown SHA-256:   080be69fed7e868907f13d17ae044ecc18321d86e9bf9d2ebcb93d4301e2b311
# Code AST SHA-256:   271092dc9301ebaa8dabab61f18275c593721c119d59676fc0fb988695572309
# Verified Classes:   StaleAttestationEpoch, AttestationToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleAttestationEpoch(RuntimeError):
    """Raised when a dispatch presents a warrant whose revocation epoch is
    behind the endpoint's current epoch beyond tolerance. This is the
    enforcement point that closes the attestation epoch gap."""


@dataclass(frozen=True)
class AttestationToken:
    warrant_id: str
    subject: str
    expires_at: float
    rev_epoch: int | None  # None means issuer did not bind an epoch
    signature_valid: bool


def authorize_dispatch(
    token: AttestationToken,
    now: float,
    endpoint_rev_epoch: int,
    epoch_tolerance: int = 0,
) -> None:
    if not token.signature_valid:
        raise StaleAttestationEpoch(f"bad signature on warrant {token.warrant_id}")
    if now >= token.expires_at:
        raise StaleAttestationEpoch(f"warrant {token.warrant_id} expired at {token.expires_at}")
    if token.rev_epoch is None:
        # Default-deny: an unbound token cannot prove it postdates any revocation.
        raise StaleAttestationEpoch(
            f"warrant {token.warrant_id} carries no revocation epoch; "
            "authority freshness is unverifiable"
        )
    if endpoint_rev_epoch - token.rev_epoch > epoch_tolerance:
        raise StaleAttestationEpoch(
            f"warrant {token.warrant_id} attested at rev_epoch {token.rev_epoch}, "
            f"endpoint at {endpoint_rev_epoch}, tolerance {epoch_tolerance}; "
            "possible execution under revoked authority"
        )
