# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-trust-broker-revocation-mid-federation-when-capability-warrants-outlive-their-issuing-authority.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-trust-broker-revocation-mid-federation-when-capability-warrants-outlive-their-issuing-authority.warrant.json
# Markdown SHA-256:   f51fb626249cfc1d37b3bf60cfa7c00cb336b0049e9a5aedc0a6c2a20051026d
# Code AST SHA-256:   442b839a245a49cf53c0aa6562ea978aa8fd1eacd931207095686fa056e13e8a
# Verified Classes:   StaleTrustWindowError, Warrant, RevocationView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleTrustWindowError(RuntimeError):
    """Raised when a warrant's remaining life exceeds the freshness of the
    revocation view, opening a possible-revocation blind spot."""
    pass


@dataclass
class Warrant:
    principal: str
    scope: str
    issued_epoch: int
    not_after: float  # absolute unix time


@dataclass
class RevocationView:
    epoch: int
    refreshed_at: float


def admit_call(
    warrant: Warrant,
    view: RevocationView,
    broker_current_epoch: int,
    now: float | None = None,
    max_staleness: float = 300.0,
) -> bool:
    now = time.time() if now is None else now

    if warrant.not_after <= now:
        raise StaleTrustWindowError(
            f"warrant for {warrant.principal} already expired at {warrant.not_after}"
        )

    # Epoch-pinned check: reject if the broker has moved past the warrant's epoch.
    if warrant.issued_epoch < broker_current_epoch:
        raise StaleTrustWindowError(
            f"warrant epoch {warrant.issued_epoch} is behind broker epoch "
            f"{broker_current_epoch}; trust may have been withdrawn"
        )

    remaining_ttl = warrant.not_after - now
    view_age = now - view.refreshed_at

    if view_age > max_staleness:
        raise StaleTrustWindowError(
            f"revocation view is {view_age:.1f}s stale (max {max_staleness:.1f}s)"
        )

    # The core invariant: revocation view must be at least as fresh as the
    # warrant's remaining life, else a revocation could hide in the gap.
    blind_spot = remaining_ttl - view_age
    if blind_spot > 0:
        raise StaleTrustWindowError(
            f"possible-revocation blind spot of {blind_spot:.1f}s: warrant has "
            f"{remaining_ttl:.1f}s left but revocation view is only {view_age:.1f}s old"
        )

    return True


def exercise_capability(warrant: Warrant, view: RevocationView, broker_epoch: int) -> str:
    admit_call(warrant, view, broker_epoch)
    return f"executed {warrant.scope} as {warrant.principal}"
