# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegation-chain-as-invalid-the-moment-a-mid-chain-warrant-is-revoked-rather-than-at-the-next-handoff-check.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegation-chain-as-invalid-the-moment-a-mid-chain-warrant-is-revoked-rather-than-at-the-next-handoff-check.warrant.json
# Markdown SHA-256:   55f1d12c34af7a340412fcc9174fc9957a06d0f491968e0afca0aa5e0eea7096
# Code AST SHA-256:   152401eb3a791a55af8ab8448d766866762639c0ebe2c5e16aa96fe2b8ae1512
# Verified Classes:   DeadAuthorityError, Warrant, RevocationRegistry, Lease
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class DeadAuthorityError(RuntimeError):
    """Raised when an action is attempted under a warrant whose ancestor closure
    contains a revoked identifier, or whose validity lease has expired."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    scope: FrozenSet[str]
    ancestors: FrozenSet[str]          # full transitive closure, not just direct parent
    expiry: float
    signature_ok: bool = True


@dataclass
class RevocationRegistry:
    _revoked: dict = field(default_factory=dict)   # warrant_id -> revocation_time
    _max_staleness: float = 5.0                    # bounded-staleness guarantee

    def revoke(self, warrant_id: str) -> None:
        self._revoked[warrant_id] = time.monotonic()

    def is_revoked(self, warrant_id: str, as_of: float) -> bool:
        # A read is only trustworthy if the registry's staleness bound holds.
        if time.monotonic() - as_of > self._max_staleness:
            raise DeadAuthorityError(
                f"registry read too stale for {warrant_id}; cannot certify non-revocation"
            )
        return warrant_id in self._revoked


@dataclass
class Lease:
    warrant_id: str
    acquired_at: float
    ttl: float

    def fresh(self, now: float) -> bool:
        return (now - self.acquired_at) < self.ttl


IRREVERSIBLE = frozenset({"spend", "write", "tool:search"})


def authorize_action(
    warrant: Warrant,
    action: str,
    registry: RevocationRegistry,
    lease: Lease,
    now: float,
) -> None:
    if not warrant.signature_ok:
        raise DeadAuthorityError(f"bad signature on {warrant.warrant_id}")
    if now >= warrant.expiry:
        raise DeadAuthorityError(f"{warrant.warrant_id} expired")
    if action not in warrant.scope:
        raise DeadAuthorityError(f"action {action} outside scope of {warrant.warrant_id}")

    # Ancestor-closure revocation check — the invariant that local validation skips.
    read_as_of = now
    for ancestor_id in warrant.ancestors:
        if registry.is_revoked(ancestor_id, read_as_of):
            raise DeadAuthorityError(
                f"{warrant.warrant_id} is dead: ancestor {ancestor_id} revoked"
            )

    # Lease freshness gates irreversible actions; reversible ones may proceed.
    if action in IRREVERSIBLE and not lease.fresh(now):
        raise DeadAuthorityError(
            f"stale lease ({now - lease.acquired_at:.1f}s > {lease.ttl}s) "
            f"for irreversible action {action} under {warrant.warrant_id}"
        )
