# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-honors-a-capability-warrant-whose-jurisdiction-clause-was-satisfied-at-issuance-but-invalidated-by-a-mid-flight-policy-r.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-honors-a-capability-warrant-whose-jurisdiction-clause-was-satisfied-at-issuance-but-invalidated-by-a-mid-flight-policy-r.warrant.json
# Markdown SHA-256:   bb981d2186a6743968c7b5ca702a584e5833f51a81afeefb486e27f9c3b6d3aa
# Code AST SHA-256:   2e203d7a65fc149c46e1b349b33e0c19eac6e3c5482c9a5b2d4bd93716d953d4
# Verified Classes:   StalePredicateWarrantError, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass

class StalePredicateWarrantError(RuntimeError):
    """Raised when a warrant's embedded predicate was evaluated outside its
    freshness window and no live re-validation against the issuer's current
    policy store was performed."""
    pass

@dataclass
class Warrant:
    warrant_id: str
    scope: str
    ttl_s: int
    issued_at: float
    predicate_evaluated_at: float
    freshness_window_s: float
    predicate_is_mutable: bool

def execute_under_warrant(
    warrant: Warrant,
    issuer_predicate_endpoint,
    now: float | None = None,
) -> bool:
    now = time.time() if now is None else now

    # 1. liveness bound
    if now >= warrant.issued_at + warrant.ttl_s:
        raise StalePredicateWarrantError(
            f"warrant {warrant.warrant_id} expired at "
            f"{warrant.issued_at + warrant.ttl_s:.0f}"
        )

    # 2. currency bound — the invariant the incident violated
    age = now - warrant.predicate_evaluated_at
    if warrant.predicate_is_mutable and age >= warrant.freshness_window_s:
        # must re-validate live against the issuer's CURRENT policy store
        verdict = issuer_predicate_endpoint(warrant.warrant_id)
        if not verdict.get("allowed"):
            raise StalePredicateWarrantError(
                f"warrant {warrant.warrant_id} predicate stale "
                f"(age={age:.1f}s >= window={warrant.freshness_window_s}s) "
                f"and live re-evaluation denied at policy_version="
                f"{verdict.get('policy_version')}"
            )
        # refresh the evaluation timestamp to the signed server time
        warrant.predicate_evaluated_at = verdict["evaluated_at"]

    return True
