# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-keeps-a-revoked-capability-because-its-peer-caches-the-attestation-at-handshake-time.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-keeps-a-revoked-capability-because-its-peer-caches-the-attestation-at-handshake-time.warrant.json
# Markdown SHA-256:   164ee1d6aec0deec5ee3eb460da91f2f057713b6cce02b1cb78dab383d81de6a
# Code AST SHA-256:   07eff4bf942ae3a7f493fa4c5bfc13b86db44c27330cc5de15e9c4368b104874
# Verified Classes:   RevokedCapabilityError, Attestation, AttestationCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevokedCapabilityError(RuntimeError):
    """Raised when a cached attestation is used past its soundness bound."""


@dataclass(frozen=True)
class Attestation:
    instance_id: str
    scope: str
    issued_epoch: int      # authority's revocation epoch at issuance
    exp: float             # absolute expiry, peer-local time


class AttestationCache:
    def __init__(self, propagation_bound_s: float):
        self._cache: dict[tuple[str, str], Attestation] = {}
        self._confirmed_epoch: int = 0
        self._propagation_bound_s = propagation_bound_s

    def on_revocation_epoch(self, epoch: int) -> None:
        # Authority pushed a new revocation epoch; invalidate all older entries.
        if epoch > self._confirmed_epoch:
            self._confirmed_epoch = epoch
            self._cache = {
                k: v for k, v in self._cache.items()
                if v.issued_epoch >= epoch
            }

    def admit(self, att: Attestation, now: float | None = None) -> None:
        now = time.monotonic() if now is None else now
        if att.issued_epoch < self._confirmed_epoch:
            raise RevokedCapabilityError(
                f"attestation for {att.instance_id} issued at epoch "
                f"{att.issued_epoch} predates confirmed epoch "
                f"{self._confirmed_epoch}"
            )
        self._cache[(att.instance_id, att.scope)] = att

    def verify_call(
        self, instance_id: str, scope: str, now: float | None = None
    ) -> Attestation:
        now = time.monotonic() if now is None else now
        att = self._cache.get((instance_id, scope))
        if att is None:
            raise RevokedCapabilityError(
                f"no attestation for {instance_id}@{scope}"
            )
        if att.issued_epoch < self._confirmed_epoch:
            raise RevokedCapabilityError(
                f"{instance_id}@{scope} revoked: epoch {att.issued_epoch} "
                f"< confirmed {self._confirmed_epoch}"
            )
        if now >= att.exp:
            raise RevokedCapabilityError(
                f"{instance_id}@{scope} attestation expired"
            )
        age = now - (att.exp - self._propagation_bound_s)
        if age > 0:
            # Within propagation bound of expiry: unsound to trust without
            # a fresh authority check.
            raise RevokedCapabilityError(
                f"{instance_id}@{scope} within propagation bound; "
                f"re-query authority before use"
            )
        return att
