# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-peer-s-warrant-when-the-federated-registry-gossip-window-outlives-its-own-cache-ttl.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-peer-s-warrant-when-the-federated-registry-gossip-window-outlives-its-own-cache-ttl.warrant.json
# Markdown SHA-256:   ce28240dee27ddb557120f1289cee8e00a19c250f64c023be1132721b3c9703a
# Code AST SHA-256:   8f67f86316e3032469c0d5d06453f93d4dbd0365b4d314022e004a21c6d5c892
# Verified Classes:   RevocationWatermarkRegression, WarrantResolution, WarrantCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict


class RevocationWatermarkRegression(RuntimeError):
    """Raised when a registry read returns a revocation-epoch behind the consumer's stored watermark.

    This is the detectable signature of the federated gossip-window failure: the
    local registry has not yet reconciled the issuer's revocation, so its view is
    behind. Re-caching from this read would extend pre-revocation acceptance.
    """


@dataclass
class WarrantResolution:
    warrant_id: str
    issuer: str
    claims: Dict[str, str]
    issuer_revocation_epoch: int
    resolved_at: float = field(default_factory=time.time)


class WarrantCache:
    def __init__(self, ttl_seconds: float, gossip_p99_by_issuer: Dict[str, float]):
        self.ttl = ttl_seconds
        self.gossip_p99 = gossip_p99_by_issuer
        self._entries: Dict[str, WarrantResolution] = {}
        self._watermark: Dict[str, int] = {}

    def _is_safe_to_positive_cache(self, issuer: str) -> bool:
        # T_cache must exceed cross-region gossip tail, else positive caching is unsound.
        return self.ttl >= self.gossip_p99.get(issuer, float("inf")) + 30.0

    def accept(self, res: WarrantResolution) -> bool:
        issuer = res.issuer
        prior = self._watermark.get(issuer, 0)

        # Monotonic watermark: a registry view behind our stored epoch is stale.
        if res.issuer_revocation_epoch < prior:
            raise RevocationWatermarkRegression(
                f"issuer={issuer} returned epoch={res.issuer_revocation_epoch} "
                f"behind stored watermark={prior}; registry view is pre-revocation. "
                f"Refusing to re-cache warrant={res.warrant_id}."
            )

        self._watermark[issuer] = res.issuer_revocation_epoch

        if not self._is_safe_to_positive_cache(issuer):
            # T_cache < D_gossip: fail-closed on expiry-driven re-cache.
            # Only accept if we can prove freshness via a synchronous issuer pull,
            # which the caller must have done (epoch == live issuer epoch).
            if res.issuer_revocation_epoch != self._watermark.get(issuer):
                raise RevocationWatermarkRegression(
                    f"issuer={issuer} cache TTL {self.ttl}s < gossip p99 "
                    f"{self.gossip_p99.get(issuer)}s; positive caching unsound and "
                    f"no live issuer pull performed for warrant={res.warrant_id}."
                )

        self._entries[res.warrant_id] = res
        return True

    def lookup(self, warrant_id: str) -> WarrantResolution:
        entry = self._entries.get(warrant_id)
        if entry is None:
            raise RevocationWatermarkRegression(
                f"warrant={warrant_id} absent from cache; fail-closed."
            )
        if time.time() - entry.resolved_at > self.ttl:
            # Expiry is a fail-closed boundary, not a re-cache trigger.
            raise RevocationWatermarkRegression(
                f"warrant={warrant_id} expired; re-resolve against issuer, "
                f"not local registry, before accepting."
            )
        return entry
