# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-keeps-a-revoked-peer-warrant-alive-across-a-trust-anchor-resync-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-keeps-a-revoked-peer-warrant-alive-across-a-trust-anchor-resync-boundary.warrant.json
# Markdown SHA-256:   d2759fb476ffbefd75394a86769d73a64df97c604fadac44763cfea1ed8a18c7
# Code AST SHA-256:   62566a653bd9b932753ff08792f54cf50065f237797b785fbd2bcb5d56fa854c
# Verified Classes:   AnchorBlindError, StaleEpochDrain, RevokedWarrant, WarrantGate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time


class AnchorBlindError(RuntimeError):
    """Relying agent cannot prove its trust anchor is fresh; must fail closed."""


class StaleEpochDrain(RuntimeError):
    """Warrant names an anchor epoch older than the locally observed epoch."""


class RevokedWarrant(RuntimeError):
    """Revocation record exists for (subject, epoch)."""


class WarrantGate:
    def __init__(self, sync_interval_s: float, jitter_bound_s: float):
        self.staleness_budget = 2.0 * sync_interval_s + jitter_bound_s
        self.local_epoch = 0
        self.last_sync = time.monotonic()
        self.revocations = set()  # {(subject, epoch)}

    def observe_anchor(self, epoch: int) -> None:
        if epoch > self.local_epoch:
            self.local_epoch = epoch
            self.last_sync = time.monotonic()

    def authorize(self, subject: str, warrant_epoch: int,
                  not_after: float, now: float) -> None:
        # Clause 2: fail closed when anchor freshness is unprovable.
        if (time.monotonic() - self.last_sync) > self.staleness_budget:
            raise AnchorBlindError(
                f"anchor stale beyond {self.staleness_budget:.1f}s; "
                f"cannot certify epoch {self.local_epoch} is current"
            )
        # Clause 1: no cross-epoch acceptance.
        if warrant_epoch < self.local_epoch:
            raise StaleEpochDrain(
                f"warrant epoch {warrant_epoch} < local epoch "
                f"{self.local_epoch}; drain, do not retro-apply revocation"
            )
        if warrant_epoch > self.local_epoch:
            raise AnchorBlindError(
                f"warrant epoch {warrant_epoch} ahead of local "
                f"{self.local_epoch}; anchor desync"
            )
        # Clause 3: epoch-keyed revocation.
        if (subject, warrant_epoch) in self.revocations:
            raise RevokedWarrant(f"{subject} revoked at epoch {warrant_epoch}")
        # Clause 4: expiry.
        if now >= not_after:
            raise RevokedWarrant(f"{subject} warrant expired at {not_after}")
