# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-warrant-whose-revocation-epoch-it-cannot-verify-the-transitive-attenuation-revocation-gap-in-a2a-authority-ch.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-warrant-whose-revocation-epoch-it-cannot-verify-the-transitive-attenuation-revocation-gap-in-a2a-authority-ch.warrant.json
# Markdown SHA-256:   68c9a16fb432c0b8054fca62f2edc4cd1388ea06dbd255e2988f8d0b88080806
# Code AST SHA-256:   fd269592ea68fe4cc0e183ec399145466efbeb5ea4102afa304057c08756e086
# Verified Classes:   RevocationEpochUnverifiable, AncestorEpoch, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class RevocationEpochUnverifiable(RuntimeError):
    """Raised when a leaf cannot establish an ancestor's current revocation epoch."""
    pass


@dataclass(frozen=True)
class AncestorEpoch:
    issuer_id: str
    epoch_at_mint: int
    epoch_receipt_age_s: float  # age of the freshest signed epoch receipt we hold
    lineage_scoped: bool        # True if revoke invalidates all descendants


@dataclass(frozen=True)
class Warrant:
    leaf_id: str
    scope: frozenset[str]
    ancestors: tuple[AncestorEpoch, ...]
    irreversible_effect: bool


MAX_STALENESS_S = 60.0


def authorize(w: Warrant, requested: frozenset[str]) -> None:
    if not requested <= w.scope:
        raise RevocationEpochUnverifiable(
            f"requested {requested} exceeds leaf scope {w.scope}"
        )

    for anc in w.ancestors:
        stale = anc.epoch_receipt_age_s > MAX_STALENESS_S

        # Lineage-scoped revoke at any ancestor invalidates the whole subtree.
        # Without a fresh epoch receipt we cannot tell "valid" from "revoked".
        if anc.lineage_scoped and stale:
            raise RevocationEpochUnverifiable(
                f"ancestor {anc.issuer_id} is lineage-scoped and epoch receipt "
                f"is {anc.epoch_receipt_age_s:.0f}s old (> {MAX_STALENESS_S:.0f}s); "
                f"cannot prove epoch_at_mint={anc.epoch_at_mint} is current"
            )

        # Staleness on an irreversible effect is a hard stop even for
        # scope-scoped revokes: interior may have re-attenuated below us.
        if stale and w.irreversible_effect:
            raise RevocationEpochUnverifiable(
                f"ancestor {anc.issuer_id} epoch receipt stale "
                f"({anc.epoch_receipt_age_s:.0f}s) on irreversible effect; "
                f"re-attenuation may have inverted containment"
            )

    # Only reached when every ancestor epoch is fresh enough to trust.
    return None
