# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-capability-through-policy-negotiation-but-the-data-residency-warrant-expires-between-discovery-and-first-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-capability-through-policy-negotiation-but-the-data-residency-warrant-expires-between-discovery-and-first-tool.warrant.json
# Markdown SHA-256:   3fc49524bd79917b21de7262ceb496c98ebd5870e6ad2ee10c1b68319505dd06
# Code AST SHA-256:   a74358004a5f2d30d674693c201f8e49ad9775203e29ce8794f337be6e394072
# Verified Classes:   WarrantStaleError, WarrantExpiredError, Warrant, ProviderPolicyState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantStaleError(RuntimeError):
    """Raised when a presented capability warrant's epoch does not match the
    provider's current policy epoch. Indicates the warrant was issued before a
    narrowing policy advance and must be re-negotiated."""
    pass


class WarrantExpiredError(RuntimeError):
    """Raised when a warrant's TTL has elapsed regardless of epoch state."""
    pass


@dataclass(frozen=True)
class Warrant:
    cap_id: str
    residency: str
    retention_days: int
    epoch: int
    ttl_seconds: int
    issued_at: float


@dataclass(frozen=True)
class ProviderPolicyState:
    current_epoch: int
    # Narrowing advances bump current_epoch; consumers must revalidate.


def validate_warrant_at_invocation(
    warrant: Warrant,
    policy: ProviderPolicyState,
    now: float,
) -> None:
    """Revalidate a cached warrant against the provider's *current* policy epoch.

    This is the lease model, not the bearer-credential model. The epoch check
    is equality, not inequality: a warrant issued at epoch E is only valid if
    the provider is *still* at epoch E. Any advance -- widening or narrowing --
    invalidates the warrant, because the consumer cannot distinguish the two
    from the warrant alone and must not assume widening.
    """
    if now - warrant.issued_at > warrant.ttl_seconds:
        raise WarrantExpiredError(
            f"warrant for {warrant.cap_id} expired: "
            f"age={now - warrant.issued_at:.1f}s ttl={warrant.ttl_seconds}s"
        )

    if warrant.epoch != policy.current_epoch:
        # This is the boundary the observed deployment missed. The provider
        # advanced from epoch 4471 to 4473 between discovery and invocation.
        # A `warrant.epoch <= policy.current_epoch` check would have passed
        # the stale warrant through; equality refuses it.
        raise WarrantStaleError(
            f"warrant for {warrant.cap_id} issued at epoch {warrant.epoch}, "
            f"provider now at epoch {policy.current_epoch}; "
            f"re-negotiate before invoking"
        )


def invoke_capability(
    warrant: Warrant,
    policy: ProviderPolicyState,
    now: float,
    payload: dict,
) -> dict:
    validate_warrant_at_invocation(warrant, policy, now)
    # Only reached if warrant epoch == current epoch. Safe to execute.
    return {"status": "ok", "cap_id": warrant.cap_id, "epoch": policy.current_epoch}
