# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-credential-in-a-multi-hop-delegation-chain-it-did-not-originate.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-credential-in-a-multi-hop-delegation-chain-it-did-not-originate.warrant.json
# Markdown SHA-256:   542445f43d3627d94f192104325c01e6be156fea9dc506665775838627bb3b1a
# Code AST SHA-256:   b709efe1c4b944f32285d7eda16bb6d65459058417ff9c67f424455ff655d4a5
# Verified Classes:   DelegationRevocationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DelegationRevocationError(RuntimeError):
    """Raised when a delegation chain cannot be shown live up to its TTL."""
    pass


def verify_chain(leaf, ancestors, cache, now, max_depth=4):
    """
    leaf: token with .issued_at, .expires_at, .parent_id, .epoch
    ancestors: dict parent_id -> token (the path from leaf to root)
    cache: dict token_id -> (revoked: bool, checked_at: float)
    """
    if len(ancestors) > max_depth:
        # Truncating the walk and returning "valid" is the observed failure.
        raise DelegationRevocationError(
            f"chain depth {len(ancestors)} exceeds max_depth {max_depth}; "
            "refusing to verify a truncated path"
        )

    remaining = leaf.expires_at - now
    staleness = cache.max_age  # configured per-verifier bound

    if remaining > staleness:
        # Token outlives our revocation-detection window: must walk ancestors.
        for token_id, token in ancestors.items():
            entry = cache.get(token_id)
            if entry is None:
                raise DelegationRevocationError(
                    f"no cached revocation state for ancestor {token_id}; "
                    "cannot bound staleness"
                )
            revoked, checked_at = entry
            if now - checked_at > staleness:
                raise DelegationRevocationError(
                    f"ancestor {token_id} revocation state is stale "
                    f"({now - checked_at:.1f}s > {staleness:.1f}s)"
                )
            if revoked:
                raise DelegationRevocationError(
                    f"ancestor {token_id} is revoked; leaf {leaf.parent_id} orphaned"
                )

    # Token expires within the staleness window: local proof is sound.
    return True
