# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-capability-token-as-still-live-because-an-in-flight-tool-call-was-admitted-before-revocation-propag.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-capability-token-as-still-live-because-an-in-flight-tool-call-was-admitted-before-revocation-propag.warrant.json
# Markdown SHA-256:   051da078e4bed3a791c11cb9035dc4ced92ca70bc1db9439bb3e739e6bc90475
# Code AST SHA-256:   873dc0aba27785f304762c5fb75b45f69b1e43127b8d6eeca8b4c319bcf2d09f
# Verified Classes:   CapabilityRevokedAtExecution, CapabilityToken, RevocationStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class CapabilityRevokedAtExecution(RuntimeError):
    """Raised when a tool call's side effect would execute under a capability
    that was revoked (or expired) between admission and execution."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    tool: str
    scope: str
    exp: float              # absolute wall-clock expiry
    revocation_epoch: int   # epoch under which this token was minted


class RevocationStore:
    """Strongly-consistent view of the issuer's current epoch.
    In production this is the issuer or a linearizable cache; a TTL cache
    here is exactly the bug this article describes."""
    def __init__(self, epoch: int):
        self._epoch = epoch

    def current_epoch(self) -> int:
        return self._epoch

    def revoke(self) -> None:
        self._epoch += 1


def execute_tool_call(
    token: CapabilityToken,
    store: RevocationStore,
    side_effect,
    *,
    admission_epoch: int,
    now: float | None = None,
) -> None:
    """Execute a side effect only if the token is live *at execution time*.

    admission_epoch is the epoch the gate observed when it admitted the call.
    If the store has advanced past it, the capability was revoked mid-flight
    and the side effect must not run.
    """
    now = time.time() if now is None else now

    current = store.current_epoch()
    if current > admission_epoch:
        raise CapabilityRevokedAtExecution(
            f"capability for tool={token.tool!r} scope={token.scope!r} "
            f"was revoked between admission (epoch={admission_epoch}) "
            f"and execution (epoch={current}); side effect suppressed"
        )
    if now >= token.exp:
        raise CapabilityRevokedAtExecution(
            f"capability for tool={token.tool!r} expired at exec: "
            f"exp={token.exp} now={now}"
        )
    if token.revocation_epoch != admission_epoch:
        raise CapabilityRevokedAtExecution(
            f"epoch mismatch: token minted under {token.revocation_epoch}, "
            f"admitted under {admission_epoch}"
        )

    side_effect()


def retry_tool_call(
    token: CapabilityToken,
    store: RevocationStore,
    side_effect,
    *,
    re_admit,
    attempts: int = 3,
) -> None:
    """Retries must re-run admission; replaying a cached admission decision
    is a revocation bypass."""
    last_err: Exception | None = None
    for _ in range(attempts):
        try:
            admission_epoch = re_admit(token)  # fresh epoch, never cached
            execute_tool_call(
                token, store, side_effect, admission_epoch=admission_epoch
            )
            return
        except CapabilityRevokedAtExecution:
            raise
        except Exception as exc:  # transient tool failure -> retry
            last_err = exc
    raise CapabilityRevokedAtExecution(
        f"retries exhausted under possibly-revoked capability: {last_err!r}"
    )
