# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-rotated-credential-revocation-lag-and-the-warrant-epoch-invariant-in-federated-agent-meshes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-rotated-credential-revocation-lag-and-the-warrant-epoch-invariant-in-federated-agent-meshes.warrant.json
# Markdown SHA-256:   f8ca0579d222aded43c044a93a7da2f2e4556fd54678df5390c6bf40cb83b30d
# Code AST SHA-256:   e9b1fe0b7c83ec6cd36c703387e9cd0c80aeeb48ad43e05a2c70ff268a287c21
# Verified Classes:   WarrantEpochAhead, RevocationWatermarkUnknown, Warrant, VerifierView
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class WarrantEpochAhead(RuntimeError):
    """Raised when a warrant's issuance epoch is newer than the verifier's
    revocation watermark, so the verifier cannot prove the issuer was
    un-revoked at mint time. Fail closed; force a sync."""
    pass


class RevocationWatermarkUnknown(RuntimeError):
    """Raised when the verifier has no trustworthy watermark (cold start,
    replica promotion). An unknown watermark must be treated as epoch 0."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    issuance_epoch: int      # signed by issuer at mint time, monotonic per issuer
    expires_at: float
    signature_valid: bool


@dataclass(frozen=True)
class VerifierView:
    watermark: int | None    # revocation epoch known as of last sync; None = unknown
    max_epoch_lag: int = 0   # 0 => conservative: any epoch ahead of watermark rejected


def verify_warrant(
    warrant: Warrant,
    view: VerifierView,
    now: float,
    mutating: bool,
    max_clock_skew: float = 2.0,
) -> bool:
    if view.watermark is None:
        raise RevocationWatermarkUnknown(
            f"verifier has no revocation watermark; refusing {warrant.issuer} "
            "warrant (issuance_epoch=%d) until re-sync" % warrant.issuance_epoch
        )

    if not warrant.signature_valid:
        return False
    if warrant.expires_at <= now + max_clock_skew:
        return False

    # The load-bearing check: can we prove the issuer was un-revoked at mint?
    if warrant.issuance_epoch > view.watermark:
        gap = warrant.issuance_epoch - view.watermark
        if mutating or gap > view.max_epoch_lag:
            raise WarrantEpochAhead(
                f"issuer {warrant.issuer} warrant epoch {warrant.issuance_epoch} "
                f"ahead of watermark {view.watermark} (gap={gap}, mutating={mutating}); "
                "sync revocation log and re-evaluate"
            )
        # read-only within declared lag: allow, but flag
        return True

    return True
