# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-warrant-as-revoked-before-the-revocation-event-itself-has-been-observed-the-attenuated-author.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-warrant-as-revoked-before-the-revocation-event-itself-has-been-observed-the-attenuated-author.warrant.json
# Markdown SHA-256:   2d7f9a6614fd28bc8bba0565c6a054986cdde6155afa84ff40cde9eeb83811ac
# Code AST SHA-256:   b680a8f0fa958ef108f05d8fc6ea26dd75b8b6c8792464485c23a07ac6fa9848
# Verified Classes:   StaleWarrantError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class StaleWarrantError(RuntimeError):
    """Raised when a warrant is used past its bounded-staleness horizon or
    when a child is minted from a parent that may already be revoked."""


@dataclass
class Warrant:
    warrant_id: str
    parent_id: Optional[str]
    scopes: frozenset
    issued_at: float
    expires_at: float
    last_validated_at: float
    revoked: bool = False


# B: maximum tolerated gap between issuer revocation and local observation.
BOUNDED_STALENESS_SECONDS = 2.0


def check_warrant(w: Warrant, now: Optional[float] = None) -> None:
    now = time.monotonic() if now is None else now

    # 1. Explicit revocation always wins.
    if w.revoked:
        raise StaleWarrantError(f"warrant {w.warrant_id} is revoked")

    # 2. Expiry.
    if now >= w.expires_at:
        raise StaleWarrantError(f"warrant {w.warrant_id} expired at {w.expires_at}")

    # 3. Bounded-staleness: if we have not re-validated against the
    #    issuer-authoritative structure within B, we must fail closed.
    #    "Unknown" is treated as revoked, never as valid.
    age_since_validation = now - w.last_validated_at
    if age_since_validation > BOUNDED_STALENESS_SECONDS:
        raise StaleWarrantError(
            f"warrant {w.warrant_id} unvalidated for {age_since_validation:.3f}s "
            f"> B={BOUNDED_STALENESS_SECONDS}s; treating as revoked (fail-closed)"
        )


def mint_child(parent: Warrant, child_scopes: frozenset,
               child_ttl: float, now: Optional[float] = None) -> Warrant:
    now = time.monotonic() if now is None else now

    # Parent must itself be currently valid (this is the retry-cache
    # revival guard: you may not mint from an unvalidated parent).
    check_warrant(parent, now=now)

    # Scope attenuation: child must be a strict subset of parent.
    if not child_scopes.issubset(parent.scopes):
        raise StaleWarrantError(
            f"scope escalation: {child_scopes - parent.scopes} not in parent"
        )

    child_expiry = now + child_ttl

    # Temporal attenuation: child may not outlive parent.
    if child_expiry > parent.expires_at:
        raise StaleWarrantError(
            f"temporal escalation: child expiry {child_expiry} exceeds "
            f"parent expiry {parent.expires_at}"
        )

    # Revocation-horizon attenuation: child's stale window must be
    # contained within parent's.
    child_horizon = now + BOUNDED_STALENESS_SECONDS
    parent_horizon = parent.last_validated_at + BOUNDED_STALENESS_SECONDS
    if child_horizon > parent_horizon:
        raise StaleWarrantError(
            "revocation-horizon escalation: child may outlive parent's "
            "bounded-staleness guarantee"
        )

    return Warrant(
        warrant_id=f"{parent.warrant_id}/child",
        parent_id=parent.warrant_id,
        scopes=child_scopes,
        issued_at=now,
        expires_at=child_expiry,
        last_validated_at=now,
    )
