# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-revoked-aaif-credential-that-its-own-cached-verification-state-still-marks-valid.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-revoked-aaif-credential-that-its-own-cached-verification-state-still-marks-valid.warrant.json
# Markdown SHA-256:   05118b5caf61af60daae9fc22a8054bef0966c1bf4af17aaba9b1a667804f3e9
# Code AST SHA-256:   b53688e093303f00926b48d6ade4a52218ce9aec764bc2390aa9298b3af50766
# Verified Classes:   StaleCredentialEvidence, RevocationChannelUnavailable, StatusListSnapshot, CachedVerdict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StaleCredentialEvidence(RuntimeError):
    """Raised when a cached AAIF verdict cannot be honored because its
    underlying evidence is older than the risk class permits, or because
    the status-list snapshot it was computed from has diverged."""
    pass


class RevocationChannelUnavailable(StaleCredentialEvidence):
    """Raised when the status endpoint could not be polled within max_lag.
    A poll failure is NOT evidence of no revocation; we fail closed."""
    pass


@dataclass
class StatusListSnapshot:
    fetch_time: float
    revoked_indices: set[int]
    next_update: float


@dataclass
class CachedVerdict:
    credential_id: str
    subject: str
    scopes: list[str]
    risk_class: str            # "HIGH" | "LOW"
    verdict: str               # "VALID" | "REVOKED"
    verdict_minted_at: float
    evidence_snapshot: StatusListSnapshot


def max_lag_seconds(risk_class: str) -> float:
    # HIGH-risk scopes (key compromise, financial write, privilege escalation)
    # tolerate zero revocation-observation lag: online check every invocation.
    return 0.0 if risk_class == "HIGH" else 300.0


def effective_evidence_age(verdict: CachedVerdict, now: float) -> float:
    # Age is the MAXIMUM over all inputs, not the age of the verdict object.
    # A verdict minted now from a list fetched an hour ago has age 3600.
    return max(
        now - verdict.verdict_minted_at,
        now - verdict.evidence_snapshot.fetch_time,
    )


def admit(
    verdict: CachedVerdict,
    latest_snapshot: Optional[StatusListSnapshot],
    now: Optional[float] = None,
) -> bool:
    now = time.time() if now is None else now

    # Negative verdicts are monotonic: honoring a REVOKED verdict forever
    # is safe and costs nothing. Only positives carry freshness obligations.
    if verdict.verdict == "REVOKED":
        return False

    # Guard 1: snapshot divergence. If the instance holds a newer snapshot
    # than the one the verdict was computed from, the verdict is stale by
    # construction regardless of its mint time.
    if latest_snapshot is None:
        raise RevocationChannelUnavailable(
            f"no status snapshot available for {verdict.credential_id}; "
            f"cannot confirm non-revocation"
        )
    if latest_snapshot.fetch_time > verdict.evidence_snapshot.fetch_time:
        raise StaleCredentialEvidence(
            f"verdict for {verdict.credential_id} computed from snapshot "
            f"@{verdict.evidence_snapshot.fetch_time}, but newer snapshot "
            f"@{latest_snapshot.fetch_time} exists; re-verify required"
        )

    # Guard 2: lag-exceeds-risk-class, measured on effective evidence age.
    lag = max_lag_seconds(verdict.risk_class)
    age = effective_evidence_age(verdict, now)
    if age > lag:
        raise StaleCredentialEvidence(
            f"evidence for {verdict.credential_id} is {age:.1f}s old, "
            f"exceeds max_lag={lag:.1f}s for risk_class={verdict.risk_class}"
        )

    # Guard 3: confirm the credential is not in the snapshot we are relying on.
    idx = hash(verdict.credential_id) & 0xFFFF
    if idx in verdict.evidence_snapshot.revoked_indices:
        raise StaleCredentialEvidence(
            f"credential {verdict.credential_id} appears revoked in the "
            f"snapshot its VALID verdict was computed from"
        )

    return True
