# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-federated-capability-grant-after-a-policy-renegotiation-invalidates-the-trust-broker-s-cached-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-federated-capability-grant-after-a-policy-renegotiation-invalidates-the-trust-broker-s-cached-warrant.warrant.json
# Markdown SHA-256:   daccfe7a7f19601de05886baa31dd1bd2a62e72a33c980a57df5150ef860a966
# Code AST SHA-256:   5d0fbc6c3e07a3967ca92018deb084653f7f7679fbf4c9170c68043c2bb88375
# Verified Classes:   StaleWarrantPolicyEpochError, BrokerUnreachableError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class StaleWarrantPolicyEpochError(RuntimeError):
    """Raised when a cached warrant's policy_epoch does not match the broker's
    current epoch for (issuer, capability). Signature and TTL may still be valid;
    the policy predicate set bound into the warrant is stale."""
    pass


class BrokerUnreachableError(RuntimeError):
    """Raised when the epoch check cannot be completed. Executor must fail closed."""
    pass


def exercise_capability(warrant, broker, request):
    # 1. Authenticity + TTL (necessary, not sufficient).
    if not warrant.signature_valid():
        raise StaleWarrantPolicyEpochError("warrant signature invalid")
    if warrant.is_expired():
        raise StaleWarrantPolicyEpochError("warrant TTL expired")

    # 2. Currency: the invariant that this article exists to enforce.
    try:
        current_epoch = broker.current_policy_epoch(
            issuer=warrant.issuer, capability=warrant.capability
        )
    except BrokerUnreachableError:
        # Fail closed. Do NOT fall back to TTL-only.
        raise StaleWarrantPolicyEpochError(
            "cannot verify policy epoch; broker unreachable; refusing use"
        )

    if warrant.policy_epoch > current_epoch:
        # Broker failover served a regressed epoch. Fatal inconsistency.
        raise StaleWarrantPolicyEpochError(
            f"epoch regression: warrant={warrant.policy_epoch} "
            f"broker={current_epoch}; refusing use"
        )

    if warrant.policy_epoch < current_epoch:
        # Policy was renegotiated (likely narrowed) after issuance.
        raise StaleWarrantPolicyEpochError(
            f"stale warrant: issued under epoch {warrant.policy_epoch}, "
            f"broker now at {current_epoch}; re-fetch required"
        )

    # 3. Only now evaluate the (current) predicate set against the request.
    if not warrant.predicates_satisfied(request):
        raise StaleWarrantPolicyEpochError("request violates current predicates")

    return broker.execute(warrant, request)
