# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-trust-broker-s-capability-grant-as-invalid-mid-session-after-a-policy-authority-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-trust-broker-s-capability-grant-as-invalid-mid-session-after-a-policy-authority-rotation.warrant.json
# Markdown SHA-256:   2966ecfb94f90c32eb8e1925ebdef889cd28d172fc9a5b9eb3ffc5551d1f55ff
# Code AST SHA-256:   bf9f466bed9f87c35c182a86c7d93d66c56507a254ee0e4c3274cc68039a0064
# Verified Classes:   StaleCapabilityError, CapabilityGrant, ProviderResponse, FederatedInstance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleCapabilityError(RuntimeError):
    """Raised when a cached capability grant is no longer authoritative
    because the federation's policy-root epoch has advanced past the
    epoch recorded at grant acquisition."""


@dataclass(frozen=True)
class CapabilityGrant:
    issuer: str
    subject: str
    action: str
    resource: str
    policy_epoch: int
    expires_at: float


@dataclass(frozen=True)
class ProviderResponse:
    policy_epoch: Optional[int]
    status: int


class FederatedInstance:
    def __init__(self, grant: CapabilityGrant):
        self._grant = grant
        self._observed_epoch = grant.policy_epoch

    def observe(self, response: ProviderResponse) -> None:
        if response.policy_epoch is None:
            return
        if response.policy_epoch > self._observed_epoch:
            self._observed_epoch = response.policy_epoch

    def invoke(self, response: ProviderResponse) -> str:
        self.observe(response)
        if self._observed_epoch > self._grant.policy_epoch:
            raise StaleCapabilityError(
                f"grant epoch {self._grant.policy_epoch} is stale; "
                f"federation epoch is {self._observed_epoch}; "
                f"renegotiate before invoking {self._grant.action}"
            )
        return f"invoked {self._grant.action} on {self._grant.resource}"


def guarded_invoke(instance: FederatedInstance, response: ProviderResponse) -> str:
    try:
        return instance.invoke(response)
    except StaleCapabilityError:
        # fail closed: do not retry with the same grant
        raise
