# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-capability-tokens-from-surviving-their-own-attestation-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-capability-tokens-from-surviving-their-own-attestation-refresh.warrant.json
# Markdown SHA-256:   d2d7c730910291a9b262bd3777dc8cc059f708a2b158a03b557697eb41aac3e5
# Code AST SHA-256:   c666eeba720732382c41143395886df6d9dfd0d0b99844add381da36f70322a5
# Verified Classes:   StaleAttestationAcceptance, DelegatedToken, VerifierView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAttestationAcceptance(RuntimeError):
    """Raised when a verifier would admit a token against an unprovably-fresh epoch view."""
    pass


@dataclass(frozen=True)
class DelegatedToken:
    subject: str
    scope: tuple
    exp: float
    attestation_hash: str
    revocation_epoch: int


@dataclass
class VerifierView:
    confirmed_epoch: int
    last_poll: float
    cached_attestation_hash: str


def admit(token: DelegatedToken, view: VerifierView, now: float,
          delta_accept: float, issuer_fetch) -> bool:
    if now >= token.exp:
        return False

    # Invariant 1: epoch equality is necessary, not sufficient.
    if token.revocation_epoch != view.confirmed_epoch:
        return False

    # Invariant 2: freshness bound must be strictly tighter than propagation guarantee.
    age = now - view.last_poll
    if age > delta_accept:
        # Re-confirm synchronously at the boundary rather than trusting the cache.
        fresh = issuer_fetch(token.subject)
        if fresh is None:
            raise StaleAttestationAcceptance(
                f"cannot confirm epoch for {token.subject}: issuer unreachable "
                f"at age={age:.2f}s > delta_accept={delta_accept:.2f}s"
            )
        if fresh.revocation_epoch != token.revocation_epoch:
            raise StaleAttestationAcceptance(
                f"epoch skew: token={token.revocation_epoch} "
                f"issuer={fresh.revocation_epoch} for {token.subject}"
            )
        if fresh.attestation_hash != token.attestation_hash:
            raise StaleAttestationAcceptance(
                f"attestation hash mismatch for {token.subject}: "
                f"token={token.attestation_hash[:8]} issuer={fresh.attestation_hash[:8]}"
            )
        view.confirmed_epoch = fresh.revocation_epoch
        view.cached_attestation_hash = fresh.attestation_hash
        view.last_poll = now

    # Invariant 3: attestation binding re-evaluated at accept time.
    if token.attestation_hash != view.cached_attestation_hash:
        raise StaleAttestationAcceptance(
            f"stale attestation binding for {token.subject}"
        )
    return True
