# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-warrants-from-silently-outliving-the-principal-s-revocation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-warrants-from-silently-outliving-the-principal-s-revocation-epoch.warrant.json
# Markdown SHA-256:   704ae249be0176d0f6ddfa0d66eb90455f2734393fe9d73394367850df5dccd8
# Code AST SHA-256:   e385aa8a4c7f00c4b2a14e8518c163cea2bc5468cd7024aa344c2b286869aa34
# Verified Classes:   EpochSkewError, Warrant, EpochAssertion
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class EpochSkewError(RuntimeError):
    """Raised when a warrant's stamped epoch is not provably fresh at exercise time."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    delegator: str
    epoch: int          # must be inside the signed payload
    not_after: float
    depth: int


@dataclass(frozen=True)
class EpochAssertion:
    epoch: int
    issued_at: float


MAX_ORACLE_AGE_S = 30.0
IRREVERSIBLE = {"billing:charge", "data:delete", "deploy:prod"}


def assert_epoch_fresh(
    warrant: Warrant,
    assertion: EpochAssertion | None,
    action: str,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    # Expiry is necessary but never sufficient.
    if now >= warrant.not_after:
        raise EpochSkewError(
            f"warrant {warrant.warrant_id} expired at {warrant.not_after}"
        )

    if action in IRREVERSIBLE:
        if assertion is None:
            # Fail closed: no proof of freshness means no authority.
            raise EpochSkewError(
                f"irreversible action {action!r} requires a live epoch assertion; "
                f"none available for warrant {warrant.warrant_id}"
            )
        age = now - assertion.issued_at
        if age > MAX_ORACLE_AGE_S:
            raise EpochSkewError(
                f"epoch assertion age {age:.1f}s exceeds {MAX_ORACLE_AGE_S}s "
                f"for irreversible action {action!r}"
            )
        if assertion.epoch != warrant.epoch:
            # The principal has moved on; the warrant is signed but dead.
            raise EpochSkewError(
                f"epoch skew: warrant {warrant.warrant_id} stamped "
                f"{warrant.epoch}, principal at {assertion.epoch} — revoked"
            )


def exercise(
    warrant: Warrant,
    assertion: EpochAssertion | None,
    action: str,
    cache: dict[tuple[str, int], bool],
) -> bool:
    # Cache keyed on (warrant_id, epoch) so a bump cannot serve a stale allow.
    key = (warrant.warrant_id, warrant.epoch)
    if cache.get(key):
        # Even a cached allow must pass the freshness gate for irreversible work.
        assert_epoch_fresh(warrant, assertion, action)
        return True
    assert_epoch_fresh(warrant, assertion, action)
    cache[key] = True
    return True
