# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-capability-revocation-that-arrives-after-delegation-but-before-the-delegated-call-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-capability-revocation-that-arrives-after-delegation-but-before-the-delegated-call-executes.warrant.json
# Markdown SHA-256:   e11658ea077e8fb16d5cbdb9a875eb1dfebde4e3fff464fb38b20a5f24811ab6
# Code AST SHA-256:   79da96a86431eb4b804c8d5cbdeda0f72d5e6982e855b795eb0f64c1f1812043
# Verified Classes:   RevocationContinuityError, DelegationToken, EpochStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class RevocationContinuityError(RuntimeError):
    """Raised when a delegated token's ancestor authority cannot be confirmed
    at execution time, or has been revoked since the token was minted."""


@dataclass
class DelegationToken:
    token_id: str
    chain: list[str]                 # ancestor principals, root-first
    epochs: dict[str, int]           # ancestor -> epoch at mint time
    issued_at: float
    expires_at: float
    scope: str
    target: str


@dataclass
class EpochStore:
    """Authoritative current epoch per principal. Advancing an epoch is the
    revocation primitive: it invalidates every descendant minted before."""
    _epochs: dict[str, int] = field(default_factory=dict)
    _cache: dict[str, tuple[int, float]] = field(default_factory=dict)
    cache_ttl: float = 0.2

    def current(self, principal: str, now: float) -> int:
        cached = self._cache.get(principal)
        if cached and (now - cached[1]) < self.cache_ttl:
            return cached[0]
        epoch = self._epochs.get(principal, 0)
        self._cache[principal] = (epoch, now)
        return epoch

    def revoke(self, principal: str) -> None:
        self._epochs[principal] = self._epochs.get(principal, 0) + 1
        self._cache.pop(principal, None)


def admit_delegated_call(
    token: DelegationToken,
    store: EpochStore,
    *,
    idempotent: bool,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    if now >= token.expires_at:
        raise RevocationContinuityError(
            f"token {token.token_id} expired at {token.expires_at:.3f}; "
            f"now={now:.3f}. Do not enter refresh path if ancestor revoked."
        )

    # Deferral deadline must be strictly shorter than remaining token life,
    # otherwise a blocked epoch check silently degrades into an expiry.
    deferral_deadline = token.expires_at - now
    if deferral_deadline <= 0:
        raise RevocationContinuityError(
            f"no deferral budget left for {token.token_id}"
        )

    for ancestor in token.chain:
        try:
            current = store.current(ancestor, now)
        except Exception as exc:
            if idempotent:
                continue
            raise RevocationContinuityError(
                f"cannot confirm epoch for ancestor {ancestor} of "
                f"{token.token_id}; non-idempotent call must not fire"
            ) from exc

        minted = token.epochs.get(ancestor)
        if minted is None:
            raise RevocationContinuityError(
                f"token {token.token_id} omits epoch for ancestor {ancestor}; "
                f"chain of custody unverifiable"
            )
        if current != minted:
            raise RevocationContinuityError(
                f"REVOKED_ANCESTOR: {ancestor} epoch advanced "
                f"{minted}->{current} after {token.token_id} was minted; "
                f"discard token, do not retry"
            )


def execute(token: DelegationToken, store: EpochStore) -> None:
    admit_delegated_call(token, store, idempotent=False)
    # ... perform deploy.apply against token.target ...
