# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-warrant-when-the-revocation-arrives-after-the-task-handoff-has-already-been-accepted.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-warrant-when-the-revocation-arrives-after-the-task-handoff-has-already-been-accepted.warrant.json
# Markdown SHA-256:   d8ef1327e7d1dfec6a8c923996c8925bebd826efc793f204e78d049269f1aa5f
# Code AST SHA-256:   eb433e7548676c267c24441df602d671199cb43de48d1d3a3281c508ea8d65ce
# Verified Classes:   RevocationStaleError, WarrantRevokedError, Warrant, RevocationState, RevocationAwareExecutor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class RevocationStaleError(RuntimeError):
    """Raised when a warrant's revocation freshness cannot be established
    within its declared max_staleness budget at the moment of use."""
    pass


class WarrantRevokedError(RuntimeError):
    """Raised when the issuer's revocation surface positively confirms
    the warrant (or an ancestor in its chain) has been revoked."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    issuer: str
    parent_id: Optional[str]
    max_staleness: Optional[float]  # seconds; None means "no bound declared"
    expires_at: float               # absolute epoch seconds


@dataclass
class RevocationState:
    last_check_at: Optional[float] = None
    last_result_revoked: bool = False


class RevocationAwareExecutor:
    def __init__(self, crl_client, clock=time.time):
        self.crl = crl_client
        self.clock = clock
        self._state: dict[str, RevocationState] = {}

    def _effective_staleness(self, warrant: Warrant) -> float:
        # No declared bound => zero tolerance => synchronous check every use.
        if warrant.max_staleness is None:
            return 0.0
        return warrant.max_staleness

    def _check_chain(self, warrant: Warrant, chain: list[Warrant]) -> None:
        """Re-anchor to the ROOT issuer's revocation surface. A revoked
        ancestor invalidates every descendant, regardless of what the
        intermediate peer claims."""
        for w in chain:
            state = self._state.setdefault(w.warrant_id, RevocationState())
            budget = self._effective_staleness(w)
            now = self.clock()
            fresh = (
                state.last_check_at is not None
                and (now - state.last_check_at) <= budget
            )
            if not fresh:
                try:
                    revoked = self.crl.is_revoked(w.issuer, w.warrant_id)
                except Exception as exc:
                    # Cannot establish freshness -> fail closed.
                    raise RevocationStaleError(
                        f"revocation check failed for {w.warrant_id} "
                        f"at issuer {w.issuer}: {exc!r}"
                    ) from exc
                state.last_check_at = now
                state.last_result_revoked = revoked
            if state.last_result_revoked:
                raise WarrantRevokedError(
                    f"warrant {w.warrant_id} (issuer {w.issuer}) is revoked; "
                    f"descendant use refused"
                )

    def before_tool_call(self, warrant: Warrant, chain: list[Warrant]) -> None:
        """Must be invoked before EVERY tool call, not once per task.
        Warrant validity is a function of wall-clock time; a task's
        execution spans wall-clock time."""
        if self.clock() >= warrant.expires_at:
            raise WarrantRevokedError(
                f"warrant {warrant.warrant_id} expired at {warrant.expires_at}"
            )
        self._check_chain(warrant, chain)
