# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-authority-warrant-when-aaif-credential-rotation-races-an-asymmetric-partition-and-the-revocation-epoch-advances-on.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-authority-warrant-when-aaif-credential-rotation-races-an-asymmetric-partition-and-the-revocation-epoch-advances-on.warrant.json
# Markdown SHA-256:   826f2fbc4d0f11b9ac894ece94b76e163e691798ad960fe6912d547cd193abfc
# Code AST SHA-256:   4df3220de81ae462e403d87bd2ecdf2a90b7a16162d6c230b179456b19302ad9
# Verified Classes:   WarrantBlindError, EpochRegressedError, Warrant, EpochView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class WarrantBlindError(RuntimeError):
    """Raised when a warrant's revocation epoch cannot be confirmed within its staleness bound."""


class EpochRegressedError(RuntimeError):
    """Raised when a confirmed epoch is older than the locally-held epoch (rollback attack)."""


@dataclass
class Warrant:
    epoch: int
    staleness_bound_s: float  # carried inside the signed warrant; issuer-controlled
    capability: str


@dataclass
class EpochView:
    confirmed_epoch: int
    last_confirmed_at: float  # monotonic seconds


def authorize_side_effect(
    warrant: Warrant,
    view: EpochView,
    now: float,
    retry_cap: int,
    retries_used: int,
) -> None:
    """Gate a side-effecting action on epoch freshness, not just signature validity."""
    age = now - view.last_confirmed_at

    # Blind: we cannot confirm the epoch within the warrant's own bound.
    if age > warrant.staleness_bound_s:
        raise WarrantBlindError(
            f"warrant epoch={warrant.epoch} unconfirmed for {age:.1f}s "
            f"> bound {warrant.staleness_bound_s:.1f}s; "
            f"capability '{warrant.capability}' must not execute"
        )

    # Confirmed epoch advanced past ours: warrant definitively revoked.
    if view.confirmed_epoch > warrant.epoch:
        raise WarrantBlindError(
            f"warrant epoch={warrant.epoch} superseded by confirmed "
            f"epoch={view.confirmed_epoch}; revoked"
        )

    # Rollback: a confirmed epoch lower than ours signals replayed/stale gossip.
    if view.confirmed_epoch < warrant.epoch:
        raise EpochRegressedError(
            f"confirmed epoch={view.confirmed_epoch} < held epoch="
            f"{warrant.epoch}; possible replay of stale revocation state"
        )

    # Retry budget must not be allowed to consume the staleness budget.
    if retries_used >= retry_cap:
        raise WarrantBlindError(
            f"retry cap {retry_cap} exhausted on ambiguous rejection for "
            f"epoch={warrant.epoch}; escalating as authority-ambiguous"
        )
