# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-stale-warrant-replay-when-aaif-revocation-crosses-a-federated-trust-domain-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-stale-warrant-replay-when-aaif-revocation-crosses-a-federated-trust-domain-boundary.warrant.json
# Markdown SHA-256:   003d695c5de43aaefce43239e29264d104d416708314efe82ffba693c420642d
# Code AST SHA-256:   75d8af796d243f2fb1cc19f614222a8b01b37b3a224711a9bdebb79edab92a95
# Verified Classes:   StaleWarrantReplayError, RevocationProofUnavailableError, RevocationProof, Warrant, VerifierState
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class StaleWarrantReplayError(RuntimeError):
    """Raised when a warrant's signing key is not authoritative at evaluation time."""
    pass


class RevocationProofUnavailableError(RuntimeError):
    """Raised when a fresh revocation proof cannot be obtained; verifier must fail closed."""
    pass


@dataclass
class RevocationProof:
    key_id: str
    revoked: bool
    issued_at: float          # issuer monotonic timestamp of proof
    ledger_head: int          # monotonic version, must be >= last seen


@dataclass
class Warrant:
    key_id: str
    issued_at: float
    not_after: float
    signature_valid: bool


@dataclass
class VerifierState:
    trust_bundle_key_ids: set
    last_ledger_head: int = -1
    max_proof_staleness_s: float = 30.0
    clock_skew_bound_s: float = 5.0


def admit_warrant(
    warrant: Warrant,
    proof: Optional[RevocationProof],
    state: VerifierState,
    now: float,
    issuer_clock: float,
) -> bool:
    # Invariant 1: signing key must be in the trust bundle (issuance authority).
    if warrant.key_id not in state.trust_bundle_key_ids:
        raise StaleWarrantReplayError(
            f"key {warrant.key_id} absent from trust bundle at evaluation"
        )

    # Invariant 2: warrant must be within its own validity window.
    if not (warrant.issued_at <= now <= warrant.not_after):
        raise StaleWarrantReplayError(
            f"warrant window [{warrant.issued_at},{warrant.not_after}] excludes now={now}"
        )

    # Invariant 3: signature must validate.
    if not warrant.signature_valid:
        raise StaleWarrantReplayError(f"signature invalid for key {warrant.key_id}")

    # Invariant 4: fail closed if no fresh revocation proof is available.
    if proof is None:
        raise RevocationProofUnavailableError(
            f"no revocation proof for key {warrant.key_id}; refusing to fall back to cache"
        )

    # Invariant 5: proof must be fresh relative to verifier clock.
    if now - proof.issued_at > state.max_proof_staleness_s:
        raise RevocationProofUnavailableError(
            f"revocation proof age {now - proof.issued_at:.1f}s exceeds "
            f"max_staleness {state.max_proof_staleness_s}s"
        )

    # Invariant 6: proof must be monotonic (no rollback of ledger head).
    if proof.ledger_head < state.last_ledger_head:
        raise StaleWarrantReplayError(
            f"ledger head rollback: proof={proof.ledger_head} < seen={state.last_ledger_head}"
        )

    # Invariant 7: clock skew must be bounded below propagation SLA.
    if abs(now - issuer_clock) > state.clock_skew_bound_s:
        raise RevocationProofUnavailableError(
            f"clock skew {abs(now - issuer_clock):.1f}s exceeds bound {state.clock_skew_bound_s}s"
        )

    # Invariant 8: evaluation-time non-revocation.
    if proof.revoked:
        raise StaleWarrantReplayError(
            f"key {warrant.key_id} revoked at evaluation time (ledger head {proof.ledger_head})"
        )

    state.last_ledger_head = proof.ledger_head
    return True
