# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-delegated-capability-survive-revocation-across-a-federated-trust-boundary-until-the-next-capability-resolution-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-delegated-capability-survive-revocation-across-a-federated-trust-boundary-until-the-next-capability-resolution-epoch.warrant.json
# Markdown SHA-256:   dc26066c18f93a50a009f41b1e7f6e21f5a2ca29e6fa1b0e5467fabeb8303da6
# Code AST SHA-256:   e9e2815599655b2d57028e9c41861cdcedbeea7fa6e20561896adec244596af5
# Verified Classes:   CapabilityResolutionError, ResolutionState, MaterializedEpoch, Capability
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class CapabilityResolutionError(RuntimeError):
    """Raised when a capability cannot be safely resolved to VALID or REVOKED."""


class ResolutionState(Enum):
    VALID = "valid"
    REVOKED = "revoked"
    INDETERMINATE = "indeterminate"


@dataclass(frozen=True)
class MaterializedEpoch:
    revocation_watermark: int  # highest revocation seq incorporated into this snapshot


@dataclass(frozen=True)
class Capability:
    cap_id: str
    revoked_seq: int | None  # seq of the revocation record, if any, from authoritative store


def resolve_capability(cap: Capability, epoch: MaterializedEpoch) -> ResolutionState:
    if cap.revoked_seq is None:
        return ResolutionState.VALID
    if cap.revoked_seq <= epoch.revocation_watermark:
        # Revocation is already reflected in this epoch: trust the snapshot.
        return ResolutionState.REVOKED
    # A revocation exists that postdates the snapshot watermark. The materialized
    # view is stale with respect to this capability. We must not serve VALID.
    return ResolutionState.INDETERMINATE


def authorize_invocation(cap: Capability, epoch: MaterializedEpoch) -> None:
    state = resolve_capability(cap, epoch)
    if state is ResolutionState.REVOKED:
        raise CapabilityResolutionError(
            f"capability {cap.cap_id!r} is revoked (seq={cap.revoked_seq})"
        )
    if state is ResolutionState.INDETERMINATE:
        # Fail closed. The caller must perform a synchronous authoritative check
        # against the issuer's revocation store before proceeding.
        raise CapabilityResolutionError(
            f"capability {cap.cap_id!r} has revocation seq={cap.revoked_seq} "
            f"newer than epoch watermark={epoch.revocation_watermark}; "
            "authoritative re-resolution required"
        )
    # state is VALID
    return None
