# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-revoked-aaif-delegation-credential-as-still-authoritative-during-in-flight-tool-execution-and-how-does.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-revoked-aaif-delegation-credential-as-still-authoritative-during-in-flight-tool-execution-and-how-does.warrant.json
# Markdown SHA-256:   8ae42020dac885160c153dc90c1a2e0af7a270fe81f401f9fc9adaab2ba87bea
# Code AST SHA-256:   c595bc7104c07b8883fafedc6fb1cf9fa62d6884afa5c6ec15db69f2844ffd24
# Verified Classes:   StaleDelegationError, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleDelegationError(RuntimeError):
    """Raised when a delegation credential's authorization freshness cannot be
    proven within the task's remaining duration."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    not_after: float            # absolute epoch seconds
    last_revocation_check: float  # epoch seconds of last issuer confirmation
    verifier_cache_ttl: float   # seconds this verifier tolerates staleness
    parent: "Warrant | None" = None


def assert_authorization_fresh(w: Warrant, estimated_call_duration: float,
                               safety_margin: float = 2.0) -> None:
    now = time.time()

    # Forward validity must never exceed the next revalidation deadline.
    next_revalidation_due = w.last_revocation_check + w.verifier_cache_ttl
    if w.not_after > next_revalidation_due + 1e-6:
        raise StaleDelegationError(
            f"warrant {w.warrant_id} not_after exceeds next revalidation due; "
            f"forward window extends past provable authorization freshness"
        )

    # Remaining budget before this verifier's snapshot goes stale.
    remaining_budget = next_revalidation_due - now
    required = estimated_call_duration + safety_margin
    if remaining_budget < required:
        raise StaleDelegationError(
            f"warrant {w.warrant_id}: remaining freshness budget "
            f"{remaining_budget:.1f}s < required {required:.1f}s; "
            f"must synchronously re-validate against issuer before effect"
        )

    # Multi-hop: the leaf's freshness is bounded by the whole chain.
    if w.parent is not None:
        assert_authorization_fresh(w.parent, estimated_call_duration, safety_margin)
