# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-delegated-warrant-after-the-delegating-agent-s-revocation-and-how-does-the-attenuation-chain-leak.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-delegated-warrant-after-the-delegating-agent-s-revocation-and-how-does-the-attenuation-chain-leak.warrant.json
# Markdown SHA-256:   422983262654bd7896bb15e58fca1c1114824e8f7eb2e2f5ff132cc44e125801
# Code AST SHA-256:   04ac3ac9fee2bcc1bb0c696c6fc2ba96eb2215cc5bf8fec09993de71244c1b9e
# Verified Classes:   WarrantRefused, Warrant, RevocationRegistry
# Defensive Guards:   8 fail-closed invariants (zero external deps)

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


class WarrantRefused(RuntimeError):
    """Raised when a delegated warrant cannot be honored safely."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    issuer: str
    parent_id: Optional[str]
    scope: frozenset
    issued_at: float
    ttl: float
    root_epoch: int
    signature_valid: bool = True


@dataclass
class RevocationRegistry:
    root_epoch: int = 0
    revoked: set = field(default_factory=set)

    def current_epoch(self) -> int:
        return self.root_epoch

    def revoke(self, warrant_id: str) -> None:
        self.revoked.add(warrant_id)
        self.root_epoch += 1  # monotonic; invalidates all older-epoch warrants


def verify_delegated_warrant(
    warrant: Warrant,
    registry: RevocationRegistry,
    last_ancestor_check: Optional[float],
    risk_class_epsilon: float,
    now: Optional[float] = None,
) -> None:
    """
    Enforce the revocation-reach invariant for a single warrant in a chain.

    Raises WarrantRefused if ANY of:
      - signature is invalid
      - warrant is expired
      - warrant's root_epoch is behind the registry's current epoch
        (an ancestor was revoked after issuance)
      - the warrant's own id is in the revoked set
      - the last verified ancestor check is older than risk_class_epsilon
        (stale liveness; the deputy cannot prove the principal is still live)
    """
    now = time.time() if now is None else now

    if not warrant.signature_valid:
        raise WarrantRefused(f"{warrant.warrant_id}: invalid signature")

    if now > warrant.issued_at + warrant.ttl:
        raise WarrantRefused(f"{warrant.warrant_id}: expired")

    if warrant.warrant_id in registry.revoked:
        raise WarrantRefused(f"{warrant.warrant_id}: explicitly revoked")

    # The critical check: epoch monotonicity makes ancestor revocation transitive.
    if warrant.root_epoch < registry.current_epoch():
        raise WarrantRefused(
            f"{warrant.warrant_id}: stale epoch {warrant.root_epoch} "
            f"< root {registry.current_epoch()} — ancestor revoked"
        )

    # Liveness of the principal: cannot act on cached authority past epsilon.
    if last_ancestor_check is None:
        raise WarrantRefused(
            f"{warrant.warrant_id}: no ancestor liveness proof; "
            f"refusing to act as confused deputy"
        )
    if now - last_ancestor_check > risk_class_epsilon:
        raise WarrantRefused(
            f"{warrant.warrant_id}: ancestor check stale by "
            f"{now - last_ancestor_check:.1f}s > epsilon {risk_class_epsilon}s"
        )


def attenuate(parent: Warrant, child_scope: frozenset, child_ttl: float) -> Warrant:
    """Narrow a warrant; refuse if scope would broaden."""
    if not child_scope.issubset(parent.scope):
        raise WarrantRefused(
            f"attenuation broadens scope: {child_scope - parent.scope} not in parent"
        )
    if child_ttl > parent.ttl:
        raise WarrantRefused("attenuation extends TTL beyond parent")
    return Warrant(
        warrant_id=f"{parent.warrant_id}.child",
        issuer=parent.warrant_id,
        parent_id=parent.warrant_id,
        scope=child_scope,
        issued_at=time.time(),
        ttl=child_ttl,
        root_epoch=parent.root_epoch,
    )
