# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-delegated-credential-verification-after-a-scope-narrowing-hop-when-the-parent-token-expires-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-delegated-credential-verification-after-a-scope-narrowing-hop-when-the-parent-token-expires-mid-chain.warrant.json
# Markdown SHA-256:   261c9d7d6e7f1dafe741065cf5de92508964052ceeb5378dffbe3f7d9494ce09
# Code AST SHA-256:   b96ce7994cab54e2aa387b23a8f55192aac27ccfff28dd2332185de44918d8d5
# Verified Classes:   ChainTemporalContainmentError, DelegatedToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field

class ChainTemporalContainmentError(RuntimeError):
    """Raised when a delegated leaf is presented outside its chain deadline,
    or when its scope is not contained in the parent's effective scope."""
    pass

@dataclass
class DelegatedToken:
    subject: str
    scope: frozenset
    not_before: float
    not_after: float
    parent: "DelegatedToken | None" = None
    # chain_deadline is the min of all ancestor not_after, signed at mint.
    chain_deadline: float = field(default=0.0)

    def __post_init__(self):
        if self.parent is None:
            self.chain_deadline = self.not_after
        else:
            # Narrowing invariant: leaf cannot outlive any ancestor.
            self.chain_deadline = min(self.not_after, self.parent.chain_deadline)
            self.not_after = self.chain_deadline

def mint_child(parent: DelegatedToken, subject: str, scope: frozenset,
               ttl: float, now: float) -> DelegatedToken:
    if not scope <= parent.scope:
        raise ChainTemporalContainmentError(
            f"scope {scope} not contained in parent {parent.scope}")
    child = DelegatedToken(
        subject=subject, scope=scope,
        not_before=now, not_after=now + ttl, parent=parent)
    if child.not_after > parent.chain_deadline:
        raise ChainTemporalContainmentError(
            f"child not_after {child.not_after} exceeds chain deadline "
            f"{parent.chain_deadline}")
    return child

def verify_at(token: DelegatedToken, now: float) -> None:
    # Single scalar check replaces recursive traversal.
    if now < token.not_before:
        raise ChainTemporalContainmentError(
            f"token for {token.subject} not yet valid at {now}")
    if now > token.chain_deadline:
        raise ChainTemporalContainmentError(
            f"token for {token.subject} presented at {now} past chain "
            f"deadline {token.chain_deadline}: parent expired mid-chain")
    # If revocation is modeled, it must bump chain_deadline to now.
    if token.parent is not None and token.scope - token.parent.scope:
        raise ChainTemporalContainmentError(
            f"scope drift: {token.scope - token.parent.scope} not in parent")
