# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-peer-s-cached-revocation-state-stale-crl-windows-across-federated-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-peer-s-cached-revocation-state-stale-crl-windows-across-federated-agent-handoffs.warrant.json
# Markdown SHA-256:   dcaaa9732453fc5eaf88d907c738fa7958a6e5eaeaa515373f2a0d7f88123270
# Code AST SHA-256:   305c8e5e1fc1fddba299b1df620e5c05d742ae718e674983f3f05250aeb40158
# Verified Classes:   StaleRevocationViewError, RevocationView, HandoffEnvelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleRevocationViewError(RuntimeError):
    """Raised when a receiver cannot prove its revocation view is not older
    than the delegator's at the instant of a handoff."""
    pass


@dataclass(frozen=True)
class RevocationView:
    crl_number: int          # signed, monotonic
    next_update_epoch: int   # absolute expiry of this artifact


@dataclass(frozen=True)
class HandoffEnvelope:
    warrant_id: str
    delegator_crl_number: int | None   # None if delegator omitted it


def validate_handoff(
    envelope: HandoffEnvelope,
    local: RevocationView,
    now_epoch: int,
    revoked_warrant_ids: frozenset[str],
) -> None:
    # 1. Fail closed if the delegator did not bind its revocation generation.
    if envelope.delegator_crl_number is None:
        raise StaleRevocationViewError(
            f"handoff {envelope.warrant_id!r}: delegator omitted crl_number; "
            "cannot prove non-staleness, refusing to execute"
        )

    # 2. Refuse if the delegator was operating under a newer revocation view
    #    than we hold -- we are provably stale and may miss a revocation.
    if envelope.delegator_crl_number > local.crl_number:
        raise StaleRevocationViewError(
            f"handoff {envelope.warrant_id!r}: delegator crl_number "
            f"{envelope.delegator_crl_number} > local {local.crl_number}; "
            "receiver is stale, refresh required before execution"
        )

    # 3. Refuse if our own artifact has expired -- we cannot vouch for it.
    if now_epoch >= local.next_update_epoch:
        raise StaleRevocationViewError(
            f"local revocation artifact expired at {local.next_update_epoch}, "
            f"now={now_epoch}; refresh required"
        )

    # 4. Only now is the warrant's revocation status meaningful.
    if envelope.warrant_id in revoked_warrant_ids:
        raise StaleRevocationViewError(
            f"handoff {envelope.warrant_id!r}: warrant is revoked under "
            f"crl_number {local.crl_number}"
        )
