# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-delegated-scope-when-capability-attenuation-is-non-monotonic-across-a-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-delegated-scope-when-capability-attenuation-is-non-monotonic-across-a-handoff.warrant.json
# Markdown SHA-256:   5f972f802dfe1a0a2be1f0693255251c72a972746cbc9798c8ea4b80586d5213
# Code AST SHA-256:   760c415c21dd068a26a9e2c74c4dc271e8827faf318ee617eff394519cccbc01
# Verified Classes:   NonMonotonicDelegationError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class NonMonotonicDelegationError(RuntimeError):
    """Raised when a child warrant would exceed parent lifetime or carry a stale mutable predicate."""
    pass


@dataclass
class Warrant:
    subject: str
    rights: frozenset[str]
    predicate: Optional[Callable[[dict], bool]]
    predicate_is_mutable: bool
    issued_at: float
    not_after: float
    chain_exp: float = field(init=False)

    def __post_init__(self) -> None:
        # chain_exp is the minimum expiry across the entire delegation chain.
        self.chain_exp = self.not_after


def delegate(
    parent: Warrant,
    child_subject: str,
    requested_rights: frozenset[str],
    requested_predicate: Optional[Callable[[dict], bool]],
    predicate_is_mutable: bool,
    requested_lifetime_s: float,
    now: Optional[float] = None,
) -> Warrant:
    now = time.time() if now is None else now

    # 1. Structural attenuation: rights must be a subset.
    if not requested_rights.issubset(parent.rights):
        raise NonMonotonicDelegationError(
            f"rights {requested_rights - parent.rights} not held by parent {parent.subject}"
        )

    # 2. Lifetime monotonicity: child must not outlive parent, and parent must be live.
    parent_remaining = parent.chain_exp - now
    if parent_remaining <= 0:
        raise NonMonotonicDelegationError(
            f"parent warrant for {parent.subject} already expired at {parent.chain_exp}"
        )
    if requested_lifetime_s > parent_remaining:
        raise NonMonotonicDelegationError(
            f"requested lifetime {requested_lifetime_s}s exceeds parent remaining {parent_remaining:.1f}s; "
            "refusing to mint a dangling grant"
        )

    # 3. Semantic attenuation: mutable predicates require re-evaluation at use, and
    #    the child must be told its true chain expiry so the resource server can
    #    reject at the edge rather than at the predicate layer.
    if predicate_is_mutable and requested_predicate is None:
        raise NonMonotonicDelegationError(
            "mutable predicate flagged but no predicate supplied; cannot revalidate"
        )

    child = Warrant(
        subject=child_subject,
        rights=requested_rights,
        predicate=requested_predicate,
        predicate_is_mutable=predicate_is_mutable,
        issued_at=now,
        not_after=now + requested_lifetime_s,
    )
    # Inherit the chain minimum so downstream servers see the real ceiling.
    child.chain_exp = min(child.not_after, parent.chain_exp)
    return child


def use(warrant: Warrant, state: dict, now: Optional[float] = None) -> bool:
    now = time.time() if now is None else now
    if now >= warrant.chain_exp:
        # Distinguishable from scope violation so callers do not retry.
        raise NonMonotonicDelegationError(
            f"warrant for {warrant.subject} expired at chain_exp={warrant.chain_exp}"
        )
    if warrant.predicate is not None and not warrant.predicate(state):
        raise NonMonotonicDelegationError(
            f"scope predicate failed for {warrant.subject} against current state"
        )
    return True
