# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-halt-on-a-revoked-peer-warrant-it-cannot-verify-locally.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-halt-on-a-revoked-peer-warrant-it-cannot-verify-locally.warrant.json
# Markdown SHA-256:   5be09d2b48a752a4132a8c55d27c94c6c24574b5f637a2e6ab2b5c6393f332f8
# Code AST SHA-256:   7e3b028436323d46ee6a64b1692cf6dd402766f399bd321c8ed38aea9ea92006
# Verified Classes:   RevocationIndeterminate, ChainRevoked, Warrant, StatusReceipt
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class RevocationIndeterminate(RuntimeError):
    """Raised when a warrant's revocation status cannot be confirmed within the staleness budget."""
    pass


class ChainRevoked(RuntimeError):
    """Raised when any link in a delegated warrant chain is revoked or its issuer is revoked."""
    pass


@dataclass
class Warrant:
    subject: str
    issuer: str
    scope: str
    expires_at: float
    parent: Optional["Warrant"] = None


@dataclass
class StatusReceipt:
    subject: str
    checked_at: float
    revoked: bool


def verify_chain(
    leaf: Warrant,
    receipts: dict[str, StatusReceipt],
    max_staleness: float,
    now: Optional[float] = None,
) -> None:
    now = now if now is not None else time.time()

    # Walk the full chain: every issuer and the leaf subject must be status-checked.
    node: Optional[Warrant] = leaf
    while node is not None:
        if node.expires_at <= now:
            raise ChainRevoked(f"warrant for {node.subject} expired at {node.expires_at}")

        receipt = receipts.get(node.subject)
        if receipt is None:
            # No status material at all: indeterminate, must halt.
            raise RevocationIndeterminate(
                f"no revocation receipt for {node.subject}; cannot confirm status"
            )
        age = now - receipt.checked_at
        if age > max_staleness:
            # Cached status is too old to be trusted; treat as indeterminate, not valid.
            raise RevocationIndeterminate(
                f"receipt for {node.subject} is {age:.1f}s old "
                f"(max_staleness={max_staleness}s); refusing to proceed"
            )
        if receipt.revoked:
            raise ChainRevoked(
                f"{node.subject} revoked as of {receipt.checked_at}; "
                f"invalidates all descendant warrants"
            )
        node = node.parent


def execute_delegated_action(
    leaf: Warrant,
    receipts: dict[str, StatusReceipt],
    max_staleness: float,
    action,
    now: Optional[float] = None,
):
    now = now if now is not None else time.time()
    try:
        verify_chain(leaf, receipts, max_staleness, now=now)
    except (RevocationIndeterminate, ChainRevoked) as exc:
        # Fail closed: do not execute on indeterminate or revoked state.
        raise RevocationIndeterminate(
            f"halting delegated action for {leaf.subject}: {exc}"
        ) from exc
    return action()
