# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-aaif-credential-whose-revocation-epoch-has-advanced-past-its-issuance-epoch-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-aaif-credential-whose-revocation-epoch-has-advanced-past-its-issuance-epoch-mid-task.warrant.json
# Markdown SHA-256:   bef512f262f94b14c9450894be8236ef18c9b70922e717bd145e7ca66bb85042
# Code AST SHA-256:   df647c2522fcbd9a8e66833352af16ca5e7450a5095e6d81b079cb4746027758
# Verified Classes:   StaleDelegationError, RevocationOracleUnavailable, ChainLink, DelegatedCredential, RevocationOracle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleDelegationError(RuntimeError):
    """Raised when a delegated credential's asserted epoch is behind the issuer's current epoch."""
    pass


class RevocationOracleUnavailable(RuntimeError):
    """Raised when the revocation channel cannot be reached; must fail closed."""
    pass


@dataclass
class ChainLink:
    subject: str
    asserted_epoch: int


@dataclass
class DelegatedCredential:
    holder: str
    parent_chain: list[ChainLink]
    not_after: float


class RevocationOracle:
    def current_epoch(self, subject: str) -> int:
        # In production: signed query to issuer's revocation endpoint.
        raise NotImplementedError


def resolve_and_verify(
    cred: DelegatedCredential,
    oracle: RevocationOracle,
    propagation_sla_seconds: float,
    task_started_at: float,
) -> None:
    """
    Enforce the chain-freshness invariant at the moment of use.
    Fails closed on oracle unavailability. Fails hard on any advanced epoch.
    """
    now = time.time()

    if now > cred.not_after:
        raise StaleDelegationError(
            f"credential for {cred.holder} expired at {cred.not_after}"
        )

    # If the task is short enough that no revocation could have propagated
    # since issuance, check-at-issuance is acceptable. Otherwise, force a
    # live check for every link.
    task_age = now - task_started_at
    must_check_live = task_age >= propagation_sla_seconds

    for link in cred.parent_chain:
        if not must_check_live:
            continue
        try:
            live_epoch = oracle.current_epoch(link.subject)
        except Exception as exc:
            # Oracle down is not permission to proceed.
            raise RevocationOracleUnavailable(
                f"cannot verify epoch for {link.subject}: {exc}"
            ) from exc

        if live_epoch > link.asserted_epoch:
            raise StaleDelegationError(
                f"link {link.subject} asserted epoch {link.asserted_epoch} "
                f"but issuer is at {live_epoch}; entire chain invalid"
            )


def execute_side_effecting_step(
    cred: DelegatedCredential,
    oracle: RevocationOracle,
    propagation_sla_seconds: float,
    task_started_at: float,
    action,
) -> None:
    # Freshness gate runs BEFORE the side effect, not after.
    resolve_and_verify(cred, oracle, propagation_sla_seconds, task_started_at)
    action()
