# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-credential-has-outlived-its-warrant-scope-after-an-upstream-revocation-race.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-credential-has-outlived-its-warrant-scope-after-an-upstream-revocation-race.warrant.json
# Markdown SHA-256:   66360011fcdb9e15eff28f3e9e7e68b6331410227a55a04fe6f939cf82c92c31
# Code AST SHA-256:   1bcfa5ea70b1d4d04f274ba2b2ebe759c2f96acf3e584cf6f5912281cda461f6
# Verified Classes:   WarrantScopeViolation, GrantStoreUnavailable, Warrant, GrantState
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantScopeViolation(RuntimeError):
    """Raised when a delegated warrant's parent epoch diverges from the live grant epoch."""
    pass


class GrantStoreUnavailable(RuntimeError):
    """Raised when the parent grant epoch cannot be read; verifier must fail closed."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    parent_grant_id: str
    parent_epoch: int          # captured at mint time
    scope: str
    expires_at: float
    ttl_seconds: float


@dataclass(frozen=True)
class GrantState:
    grant_id: str
    revocation_epoch: int


MAX_ORPHAN_WINDOW_SECONDS = 30.0


def mint_warrant(parent: GrantState, scope: str, ttl_seconds: float,
                 verifier_is_epoch_checking: bool) -> Warrant:
    if ttl_seconds > MAX_ORPHAN_WINDOW_SECONDS and not verifier_is_epoch_checking:
        raise WarrantScopeViolation(
            f"refusing to mint warrant ttl={ttl_seconds}s > "
            f"max_orphan_window={MAX_ORPHAN_WINDOW_SECONDS}s without an "
            f"epoch-checking verifier; orphan window would be unbounded by revocation"
        )
    return Warrant(
        warrant_id=f"w-{parent.grant_id}-{parent.revocation_epoch}",
        parent_grant_id=parent.grant_id,
        parent_epoch=parent.revocation_epoch,
        scope=scope,
        expires_at=0.0,  # set by caller clock
        ttl_seconds=ttl_seconds,
    )


def verify_delegated(warrant: Warrant, requested_scope: str, now: float,
                     grant_lookup) -> bool:
    # Signature/expiry checks are assumed to have passed upstream.
    if now > warrant.expires_at:
        raise WarrantScopeViolation(f"{warrant.warrant_id} expired")
    if not requested_scope.startswith(warrant.scope):
        raise WarrantScopeViolation(
            f"{warrant.warrant_id} scope {warrant.scope!r} does not cover {requested_scope!r}"
        )

    # The conjunctive invariant: parent epoch must still match at decision time.
    try:
        live: Optional[GrantState] = grant_lookup(warrant.parent_grant_id)
    except Exception as exc:
        # Fail closed: cannot confirm epoch, so cannot honor the warrant.
        raise GrantStoreUnavailable(
            f"cannot read epoch for {warrant.parent_grant_id}; denying {warrant.warrant_id}"
        ) from exc

    if live is None:
        raise WarrantScopeViolation(
            f"parent grant {warrant.parent_grant_id} no longer exists; "
            f"{warrant.warrant_id} is orphaned"
        )

    if live.revocation_epoch != warrant.parent_epoch:
        raise WarrantScopeViolation(
            f"orphaned warrant {warrant.warrant_id}: parent_epoch="
            f"{warrant.parent_epoch} but live revocation_epoch="
            f"{live.revocation_epoch} for grant {warrant.parent_grant_id}"
        )

    return True
