# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-credential-replay-across-agent-restarts-when-revocation-state-is-eventually-consistent.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-credential-replay-across-agent-restarts-when-revocation-state-is-eventually-consistent.warrant.json
# Markdown SHA-256:   79013dddf8911f0bda1a2b31967f9e6f950f69d0eda9278258324a1230f2fa98
# Code AST SHA-256:   084f51644ec8363116ae25079734248d76418107871f95d3a00bed35faf59dca
# Verified Classes:   StaleRevocationError, EpochRegressionError, DelegatedWarrant, VerifierView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleRevocationError(RuntimeError):
    """Raised when a delegated credential's age exceeds the verifier's
    max-age bound, meaning revocation state at this verifier cannot be
    trusted to be current for the credential's remaining lifetime."""
    pass


class EpochRegressionError(RuntimeError):
    """Raised when a presented credential's issuance epoch predates the
    verifier's last known revocation epoch, indicating the credential
    was minted before a revocation this verifier already knows about."""
    pass


@dataclass
class DelegatedWarrant:
    warrant_id: str
    subject: str
    scope: str
    issued_at: float          # unix seconds
    ttl: float                # seconds
    epoch: int                # issuance epoch, monotonic per issuer
    nonce: int                # replay counter, persisted by holder


@dataclass
class VerifierView:
    max_age: float                    # local bound on credential age
    last_revocation_epoch: int        # strongly-consistent read
    revocation_propagation_p100: float


def authorize(view: VerifierView, w: DelegatedWarrant, now: float) -> None:
    # 1. Hard age bound: independent of the credential's own ttl.
    age = now - w.issued_at
    if age > view.max_age:
        raise StaleRevocationError(
            f"warrant {w.warrant_id} age {age:.1f}s exceeds verifier "
            f"max_age {view.max_age:.1f}s; revocation view cannot be "
            f"trusted for its remaining lifetime"
        )

    # 2. Epoch floor: refuse anything minted before a known revocation.
    if w.epoch < view.last_revocation_epoch:
        raise EpochRegressionError(
            f"warrant {w.warrant_id} epoch {w.epoch} predates verifier "
            f"revocation epoch {view.last_revocation_epoch}"
        )

    # 3. TTL containment: the credential must die before stale state can
    #    authorize it. This is the invariant, not a heuristic.
    if w.ttl > view.revocation_propagation_p100:
        raise StaleRevocationError(
            f"warrant {w.warrant_id} ttl {w.ttl:.1f}s exceeds revocation "
            f"propagation p100 {view.revocation_propagation_p100:.1f}s; "
            f"shorten ttl or add strongly-consistent epoch reads"
        )

    # 4. Replay defense is intentionally NOT a monotonic nonce check here:
    #    a persisted nonce across restart launders a revoked credential
    #    into a fresh presentation. Freshness is enforced by age, above.


def resume_from_checkpoint(checkpoint: dict, view: VerifierView) -> None:
    """Cold-start path. Authorization state must never be resumed."""
    w = DelegatedWarrant(**checkpoint["authorization_state"]["warrant"])
    # The persisted nonce is deliberately ignored: a restarted agent is a
    # new agent for authorization purposes and must re-acquire.
    authorize(view, w, now=time.time())
    # If authorize raises, the caller must discard the warrant and re-mint
    # through the issuer, which can refuse (it knows the revocation).
