# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-revoked-federated-agent-credential-has-already-been-trusted-downstream-the-warrant-epoch-skew-window-in-cross-org-a.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-revoked-federated-agent-credential-has-already-been-trusted-downstream-the-warrant-epoch-skew-window-in-cross-org-a.warrant.json
# Markdown SHA-256:   6c289f23d01f3f8c6ba3d1172b90765b920060f4341cf5f48293e0f0997288f9
# Code AST SHA-256:   59488789089c8826e7be4e9cc54f3729c8694ca227da75cb58587782f2a2ad0a
# Verified Classes:   StaleWarrantEpochError, Warrant, EpochFloorVerifier
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWarrantEpochError(RuntimeError):
    """Raised when a cached authorization decision is served under a warrant
    epoch that the issuer has already superseded. This is the boundary failure:
    the decision is signature-valid but epoch-stale, and the downstream planner
    has already distilled it into its plan."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    scope: str
    epoch: int
    not_after: float


class EpochFloorVerifier:
    def __init__(self, epoch_oracle, skew_budget_s: float = 30.0):
        # epoch_oracle: callable returning the issuer's current signed epoch.
        self._epoch_oracle = epoch_oracle
        self._skew_budget_s = skew_budget_s
        self._cache: dict[tuple[str, str], tuple[Warrant, float]] = {}

    def authorize(self, warrant: Warrant, now: float | None = None) -> bool:
        now = time.time() if now is None else now
        if now > warrant.not_after:
            raise StaleWarrantEpochError(
                f"warrant for {warrant.subject}/{warrant.scope} expired at "
                f"{warrant.not_after}, now={now}"
            )

        key = (warrant.subject, warrant.scope)
        cached = self._cache.get(key)

        if cached is not None:
            cached_warrant, cached_at = cached
            current_epoch = self._epoch_oracle()
            # The invariant: a cache hit is only valid if the cached warrant's
            # epoch equals the issuer's current epoch AND the cache is younger
            # than the skew budget. Either violation means the decision may
            # outlive the credential.
            if cached_warrant.epoch < current_epoch:
                self._cache.pop(key, None)
                raise StaleWarrantEpochError(
                    f"cached decision for {warrant.subject}/{warrant.scope} "
                    f"was issued under epoch {cached_warrant.epoch}, issuer is "
                    f"now at epoch {current_epoch}; refusing to serve stale "
                    f"authority to a planner with context continuity"
                )
            if now - cached_at > self._skew_budget_s:
                self._cache.pop(key, None)
                raise StaleWarrantEpochError(
                    f"cached decision for {warrant.subject}/{warrant.scope} is "
                    f"{now - cached_at:.1f}s old, exceeds skew budget "
                    f"{self._skew_budget_s}s"
                )
            return True

        current_epoch = self._epoch_oracle()
        if warrant.epoch < current_epoch:
            raise StaleWarrantEpochError(
                f"presented warrant epoch {warrant.epoch} < issuer epoch "
                f"{current_epoch}; warrant was rotated and must not be trusted"
            )
        self._cache[key] = (warrant, now)
        return True
