# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-peer-s-cached-revocation-state-the-stale-warrant-window-in-federated-agent-identity-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-peer-s-cached-revocation-state-the-stale-warrant-window-in-federated-agent-identity-propagation.warrant.json
# Markdown SHA-256:   facd9a3669fa09896a66e1e4caf215bc55124421905f6ea7231ab5841cafdd52
# Code AST SHA-256:   bc8c5dda2efec20c9b835a68b83f02ecb0c78716154e29743680294cf265ed8d
# Verified Classes:   StaleWarrantWindowError, CachedVerdict
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWarrantWindowError(RuntimeError):
    """Raised when a cached revocation verdict is being used past the issuer's
    declared freshness horizon (min(expiry, nextUpdate)). The cached 'good'
    is not a weaker signal here; it is an invalid one and must not authorize
    a consequential action."""
    pass


@dataclass(frozen=True)
class CachedVerdict:
    warrant_id: str
    verdict: str          # "good" | "revoked" | "unknown"
    cached_at: float      # monotonic seconds
    ttl: float            # consumer-chosen cache lifetime
    issuer_next_update: float  # absolute monotonic deadline from issuer
    warrant_expiry: float      # absolute monotonic deadline


def authorize_consequential_action(
    verdict: CachedVerdict,
    now: float,
    revalidate,           # callable(warrant_id) -> "good" | "revoked" | "unknown"
) -> str:
    """Return the verdict to act on. Reuses cache only within the issuer's
    freshness horizon; otherwise forces revalidation before side effects."""

    if verdict.verdict == "revoked":
        return "revoked"

    sound_until = min(
        verdict.cached_at + verdict.ttl,
        verdict.issuer_next_update,
        verdict.warrant_expiry,
    )

    if now <= sound_until:
        return verdict.verdict  # cheap path: cache is still issuer-backed

    # Above the boundary: the cached verdict cannot authorize a side effect.
    # Do NOT treat as 'good' (the failure) and do NOT treat as 'revoked'
    # (availability failure). Force an evidence-layer revalidation.
    fresh = revalidate(verdict.warrant_id)

    if fresh == "unknown":
        # Issuer unreachable or ambiguous response: block, do not guess.
        raise StaleWarrantWindowError(
            f"warrant {verdict.warrant_id}: cached verdict expired at "
            f"{sound_until:.3f} (now={now:.3f}); revalidation returned "
            f"'unknown' — consequential action blocked"
        )

    if fresh != verdict.verdict and fresh == "revoked":
        # Observation-driven invalidation: trust the issuer over the cache.
        return "revoked"

    return fresh


def invalidate_on_observation(verdict: CachedVerdict, observed: str) -> CachedVerdict:
    """A revocation observed on the wire must evict the cache entry at once;
    expiry-only invalidation lets the cache outlive the issuer's truth."""
    if observed == "revoked":
        return CachedVerdict(
            warrant_id=verdict.warrant_id,
            verdict="revoked",
            cached_at=verdict.cached_at,
            ttl=0.0,
            issuer_next_update=verdict.issuer_next_update,
            warrant_expiry=verdict.warrant_expiry,
        )
    return verdict
