# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-stale-agent-credentials-from-surviving-revocation-in-federated-meshes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-stale-agent-credentials-from-surviving-revocation-in-federated-meshes.warrant.json
# Markdown SHA-256:   4a479563ad3fce317a7dbe374f9105900bd9e6264d37d7bdd0ead84ddec844b0
# Code AST SHA-256:   1db8e07b4c7024d0b21049c8e537ead2b379a891a02279013b4ded3c07a6cabc
# Verified Classes:   StaleRevocationViewError, Warrant, VerifierState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleRevocationViewError(RuntimeError):
    """Raised when a verifier cannot prove its revocation view is fresh enough
    to admit a warrant. Fail-closed: the caller must reject the tool call."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    subject: str
    issued_at: float
    expires_at: float
    epoch_at_issue: int
    signature_ok: bool


@dataclass
class VerifierState:
    issuer: str
    last_heartbeat: float
    observed_epoch: int
    max_staleness_s: float  # Delta_max


def verify_warrant(
    w: Warrant,
    state: VerifierState,
    now: float,
    min_warrant_ttl_s: float,
) -> None:
    # Invariant: Delta_max must be <= exp_min / 2 for soundness across the mesh.
    if state.max_staleness_s > min_warrant_ttl_s / 2:
        raise StaleRevocationViewError(
            f"max_staleness {state.max_staleness_s}s exceeds half of "
            f"min warrant TTL {min_warrant_ttl_s}s; heartbeat cannot bound "
            f"staleness within warrant lifetime"
        )

    # Fail-closed on staleness: a partitioned issuer takes down delegated access.
    age = now - state.last_heartbeat
    if age > state.max_staleness_s:
        raise StaleRevocationViewError(
            f"revocation view for issuer {state.issuer} is {age:.2f}s stale, "
            f"exceeds max_staleness {state.max_staleness_s}s; rejecting warrant "
            f"{w.warrant_id} regardless of signature or TTL"
        )

    # Epoch monotonicity: the verifier must have observed at least the epoch
    # that was current when the warrant was issued. Otherwise a revocation
    # between issue and now is invisible.
    if state.observed_epoch < w.epoch_at_issue:
        raise StaleRevocationViewError(
            f"verifier epoch {state.observed_epoch} < warrant issue epoch "
            f"{w.epoch_at_issue} for {w.warrant_id}; revocation delta unobserved"
        )

    if not w.signature_ok:
        raise StaleRevocationViewError(f"bad signature on {w.warrant_id}")
    if now >= w.expires_at:
        raise StaleRevocationViewError(f"warrant {w.warrant_id} expired")
