# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-cross-org-delegation-token-it-has-already-cached-for-its-own-outbound-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-cross-org-delegation-token-it-has-already-cached-for-its-own-outbound-calls.warrant.json
# Markdown SHA-256:   8935c3f1d6232f5c17333923a091c845e01b10c72c74d8736243afc8f0aaf223
# Code AST SHA-256:   04ff95035ce5c0e123473e180327461cc8c196b90e91e870da2a9de751dd1768
# Verified Classes:   RevocationPropagationError, CachedDelegation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class RevocationPropagationError(RuntimeError):
    """Raised when a cached delegated token cannot be proven fresh against the issuer's status channel."""
    pass


@dataclass
class CachedDelegation:
    token: str
    scope: str
    issued_at: float
    expires_at: float
    status_list_version: int
    last_status_check: float
    revocation_latency_bound: float | None  # None => issuer did not disclose; unsafe to cache
    act_chain: tuple[str, ...] = field(default_factory=tuple)


def assert_token_reusable(
    cached: CachedDelegation,
    now: float,
    current_status_version: int,
    safety_margin: float = 5.0,
) -> None:
    """
    Enforce the caching invariant before reusing a delegated token for an outbound call.
    Raises RevocationPropagationError if the token's authority cannot be proven current.
    """
    if cached.revocation_latency_bound is None:
        raise RevocationPropagationError(
            "issuer disclosed no revocation_latency_bound; token is not cacheable, re-exchange required"
        )

    if now >= cached.expires_at - safety_margin:
        raise RevocationPropagationError(
            f"token within {safety_margin}s of expiry; re-exchange required"
        )

    staleness = now - cached.last_status_check
    if staleness > cached.revocation_latency_bound:
        raise RevocationPropagationError(
            f"status check stale by {staleness:.1f}s > bound {cached.revocation_latency_bound:.1f}s; "
            "re-introspect before reuse"
        )

    if current_status_version > cached.status_list_version:
        raise RevocationPropagationError(
            f"status list advanced {cached.status_list_version}->{current_status_version}; "
            "cached authority may be revoked or downgraded; re-introspect"
        )


def use_token_for_call(cached: CachedDelegation, current_status_version: int) -> None:
    now = time.time()
    assert_token_reusable(cached, now, current_status_version)
    # ... perform outbound tool call under cached.token ...
