# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-check-revocation-before-acting-on-a-delegated-warrant-and-why-the-crl-ocsp-analogue-fails-at-the-agent-layer.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-check-revocation-before-acting-on-a-delegated-warrant-and-why-the-crl-ocsp-analogue-fails-at-the-agent-layer.warrant.json
# Markdown SHA-256:   222ba4af10c4e1c872f4b57b30eca7c928bd5a92c6edd378491037e402040da8
# Code AST SHA-256:   c0a9727c20659a589c7669d23e354af42d2e38536dc766d3d7c2ef97cfae0e71
# Verified Classes:   RevocationShadowViolation, RevocationStatus, WarrantEnforcementProxy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationShadowViolation(RuntimeError):
    """Raised when an effectful action would execute under a warrant whose
    revocation status is older than the action's latency bound, or when a
    revoked/unknown status was soft-failed instead of hard-denied."""
    pass


@dataclass
class RevocationStatus:
    state: str          # "good" | "revoked" | "unknown"
    queried_at: float   # monotonic seconds


class WarrantEnforcementProxy:
    def __init__(self, issuer_query, skew_max: float = 2.0):
        self._query = issuer_query          # callable(warrant_id) -> RevocationStatus
        self._skew_max = skew_max
        self._cache: dict[str, RevocationStatus] = {}

    def authorize_effect(self, warrant_id: str, latency_bound: float) -> None:
        status = self._cache.get(warrant_id)
        now = time.monotonic()

        # Re-query if the cached status is older than the effect's own window.
        # This is the invariant: freshness <= latency_bound + skew.
        if status is None or (now - status.queried_at) > (latency_bound + self._skew_max):
            status = self._query(warrant_id)
            self._cache[warrant_id] = status

        if status.state == "revoked":
            # Hard deny. Never soft-fail a revoked warrant into "proceed with caution".
            raise RevocationShadowViolation(
                f"warrant {warrant_id} revoked at {status.queried_at:.3f}; "
                f"effect latency_bound={latency_bound}s refused"
            )
        if status.state == "unknown":
            # Unknown is a deny, not a caution flag. An LLM told to "be careful"
            # will proceed; the proxy must not give it that option.
            raise RevocationShadowViolation(
                f"warrant {warrant_id} status unknown (issuer unsynced); "
                f"refusing effect rather than soft-failing"
            )
        # state == "good": admitted, but only for this single effect.
