# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-stale-warrant-replay-when-federated-agent-identity-revocation-propagates-sub-second.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-stale-warrant-replay-when-federated-agent-identity-revocation-propagates-sub-second.warrant.json
# Markdown SHA-256:   4c9e3115d902ffa45bdf6460879ca37fda3e620998ce2eeb05d6e1749c34a6a6
# Code AST SHA-256:   baf45e14548b248b57ab6896ffcda6e0f03166d39abf33f70cf0c107bda3fe42
# Verified Classes:   StaleRevocationStateError, RevokedWarrantError, Warrant, RevocationState, FederatedValidator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleRevocationStateError(RuntimeError):
    """Raised when a validator cannot prove revocation state is fresh."""
    pass


class RevokedWarrantError(RuntimeError):
    """Raised when a presented warrant is known-revoked."""
    pass


@dataclass
class Warrant:
    subject: str
    issuer: str
    mint_epoch: int      # issuer's revocation epoch at mint time (C4)
    exp: float           # wall-clock expiry


@dataclass
class RevocationState:
    last_sync_epoch: int
    last_sync_at: float
    revoked_subjects: set


class FederatedValidator:
    def __init__(self, ttl_seconds: float, now=time.monotonic):
        self.ttl = ttl_seconds
        self._now = now
        self._state: dict[str, RevocationState] = {}

    def _state_for(self, issuer: str) -> RevocationState:
        st = self._state.get(issuer)
        if st is None:
            # No state at all is the most stale possible state.
            raise StaleRevocationStateError(
                f"no revocation state for issuer {issuer!r}"
            )
        age = self._now() - st.last_sync_at
        if age > self.ttl:
            # Freshness lease on revocation state itself expired.
            raise StaleRevocationStateError(
                f"revocation state for {issuer!r} stale by {age:.3f}s "
                f"(lease {self.ttl:.3f}s)"
            )
        return st

    def validate(self, w: Warrant) -> None:
        now = self._now()
        if now >= w.exp:
            raise RevokedWarrantError(f"warrant for {w.subject!r} expired")
        st = self._state_for(w.issuer)
        # C4: reject warrants minted before our known revocation epoch.
        if w.mint_epoch < st.last_sync_epoch:
            raise RevokedWarrantError(
                f"warrant for {w.subject!r} minted at epoch {w.mint_epoch} "
                f"< known epoch {st.last_sync_epoch}"
            )
        if w.subject in st.revoked_subjects:
            raise RevokedWarrantError(f"subject {w.subject!r} is revoked")
        # ACCEPT: signature verified upstream, exp fresh, state fresh, not revoked.
