# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-revocation-epoch-has-advanced-past-its-own-cached-view.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-revocation-epoch-has-advanced-past-its-own-cached-view.warrant.json
# Markdown SHA-256:   145b0fa48f3eec4aa4042ea5c8ef908874e9cf531dc401b6c79499d0115bb69f
# Code AST SHA-256:   c1f793eaded8011bac8f8dc974fada93c915550dc4e660a14aa4bdaa50cc13b0
# Verified Classes:   RevocationEpochStale
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class RevocationEpochStale(RuntimeError):
    """Raised when a delegated warrant's chain cannot be validated against the
    verifier's cached revocation root because chain depth exceeds what the
    cached root can express, or because the presenter's observed epoch has
    fallen behind the issuer's current epoch by more than the allowed delta."""


def verify_delegated_warrant(
    warrant,
    chain,
    cached_epoch: int,
    cached_root,
    presenter_observed_epoch: int,
    current_epoch: int,
    max_epoch_delta: int = 2,
    cached_root_max_depth: int = 1,
):
    # Signature validity is necessary but not sufficient.
    for link in chain:
        if not link.signature_valid():
            raise RevocationEpochStale(
                f"signature invalid at link {link.warrant_id}; refusing before "
                f"revocation reasoning"
            )

    # Structural check: can the cached root even express this chain's revocation?
    depth = len(chain)
    if depth > cached_root_max_depth:
        raise RevocationEpochStale(
            f"chain depth {depth} exceeds cached_root_max_depth "
            f"{cached_root_max_depth}; cached root at epoch {cached_epoch} "
            f"cannot express revocation of ancestors. Synchronous root fetch "
            f"required before authorization."
        )

    # Fence check: presenter's view of its own authorization must be current.
    if current_epoch - presenter_observed_epoch > max_epoch_delta:
        raise RevocationEpochStale(
            f"presenter observed epoch {presenter_observed_epoch}, issuer is at "
            f"{current_epoch}, delta exceeds {max_epoch_delta}. Re-attestation "
            f"challenge required."
        )

    # Only now is a cached-root membership check meaningful.
    for link in chain:
        if link.warrant_id in cached_root.leaves:
            raise RevocationEpochStale(
                f"warrant {link.warrant_id} present in revocation root at epoch "
                f"{cached_epoch}"
            )

    return {"authorized": True, "epoch_used": cached_epoch, "depth": depth}
