# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-rotated-peer-key-the-revocation-propagation-lag-window-in-aaif-compliant-federated-agent-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-rotated-peer-key-the-revocation-propagation-lag-window-in-aaif-compliant-federated-agent-identity.warrant.json
# Markdown SHA-256:   b0288577bba118d022eeb172a52dbc4159e1086e9206e278c1deefb8ef0c5cd7
# Code AST SHA-256:   72f8dff9ee428c0a522d2cbf7547edce766462f9263cbb6a1cb5121d97b2ceb8
# Verified Classes:   RevocationEpochError, Warrant, FeedSnapshot
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class RevocationEpochError(RuntimeError):
    """Raised when a delegated warrant cannot be proven valid against the
    verifier's revocation feed snapshot. Fails closed by design."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    delegate: str
    not_after: float
    mint_epoch: Optional[int]  # revocation epoch of `subject` at mint time
    chain_parent: Optional["Warrant"] = None


@dataclass(frozen=True)
class FeedSnapshot:
    fetched_at: float
    max_epoch_seen: dict  # identity -> max revocation epoch observed
    max_staleness: float


def verify_warrant(w: Warrant, now: float, snap: FeedSnapshot) -> None:
    if now > w.not_after:
        raise RevocationEpochError(f"warrant for {w.delegate} expired at {w.not_after}")

    if w.mint_epoch is None:
        # Legacy warrant: no epoch binding. Reject; do not accept-by-default.
        raise RevocationEpochError(
            f"warrant {w.subject}->{w.delegate} lacks mint_epoch; cannot bound revocation window"
        )

    observed = snap.max_epoch_seen.get(w.subject, 0)
    if w.mint_epoch < observed:
        raise RevocationEpochError(
            f"warrant {w.subject}->{w.delegate} minted at epoch {w.mint_epoch} "
            f"but subject revoked through epoch {observed}"
        )

    age = now - snap.fetched_at
    if age >= snap.max_staleness:
        # Halt-and-refresh, not accept. Caller must retry with a fresh snapshot.
        raise RevocationEpochError(
            f"feed snapshot stale by {age:.1f}s (max {snap.max_staleness}s); "
            f"cannot prove {w.subject} unrevoked"
        )

    # Re-walk the chain: a valid leaf does not imply a valid chain.
    if w.chain_parent is not None:
        verify_warrant(w.chain_parent, now, snap)
