# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-delegated-aaif-credential-as-dead-the-moment-its-parent-is-revoked-even-if-the-child-s-exp-is-still-in-the-future.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-delegated-aaif-credential-as-dead-the-moment-its-parent-is-revoked-even-if-the-child-s-exp-is-still-in-the-future.warrant.json
# Markdown SHA-256:   9b3ce74232ee5dd45669bedbafc1e599964258e6887460928be5421a1463283e
# Code AST SHA-256:   36f90d19ebb36b84fa9c82f87f3147600c8ab62c83f16af62f6296c1d5b5f153
# Verified Classes:   DeadAncestryError, Credential, RevocationLog
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class DeadAncestryError(RuntimeError):
    """Raised when a delegated credential's ancestry is not live at reliance time."""


@dataclass
class Credential:
    cred_id: str
    parent_id: Optional[str]
    scope: frozenset
    nbf: float
    exp: float
    non_delegable: bool = False
    revoked_at: Optional[float] = None


@dataclass
class RevocationLog:
    # revoke time keyed by cred_id; presence means revoked
    revoked: dict = field(default_factory=dict)

    def is_revoked_at(self, cred_id: str, t: float) -> bool:
        r = self.revoked.get(cred_id)
        return r is not None and r <= t


# Propagation bound: max seconds from revoke to universal observation.
DELTA = 30.0


def resolve_ancestry(cred: Credential, store: dict) -> list:
    chain = [cred]
    cur = cred
    while cur.parent_id is not None:
        parent = store.get(cur.parent_id)
        if parent is None:
            raise DeadAncestryError(
                f"credential {cur.cred_id} references unknown parent {cur.parent_id}"
            )
        chain.append(parent)
        cur = parent
    return chain


def authorize_use(cred: Credential, store: dict, log: RevocationLog,
                  now: float, requested: frozenset) -> None:
    # Structural checks first (cheap).
    if not (cred.nbf <= now <= cred.exp):
        raise DeadAncestryError(f"{cred.cred_id} outside own validity window")
    if not requested.issubset(cred.scope):
        raise DeadAncestryError(f"{cred.cred_id} scope does not cover request")

    # Local-only fast path is legal ONLY for non-delegable leaves
    # whose remaining life is within the propagation bound.
    if cred.non_delegable and (cred.exp - now) <= DELTA:
        if log.is_revoked_at(cred.cred_id, now):
            raise DeadAncestryError(f"{cred.cred_id} revoked")
        return

    # Otherwise: walk the chain and confirm every ancestor is live at `now`.
    for node in resolve_ancestry(cred, store):
        if log.is_revoked_at(node.cred_id, now):
            raise DeadAncestryError(
                f"{cred.cred_id} relies on revoked ancestor {node.cred_id}"
            )


def mint_child(parent: Credential, store: dict, log: RevocationLog,
               now: float, child_scope: frozenset, ttl: float) -> Credential:
    # Re-delegation is the boundary: ancestry MUST be live at mint time.
    for node in resolve_ancestry(parent, store):
        if log.is_revoked_at(node.cred_id, now):
            raise DeadAncestryError(
                f"refusing to delegate from {parent.cred_id}: "
                f"ancestor {node.cred_id} revoked at {log.revoked[node.cred_id]}"
            )
    if not child_scope.issubset(parent.scope):
        raise DeadAncestryError("child scope exceeds parent scope")
    child = Credential(
        cred_id=f"{parent.cred_id}.{int(now)}",
        parent_id=parent.cred_id,
        scope=child_scope,
        nbf=now,
        exp=min(now + ttl, parent.exp),
    )
    store[child.cred_id] = child
    return child


# --- Reproduce the observed failure and its prevention ---
if __name__ == "__main__":
    store, log = {}, RevocationLog()
    R = Credential("R", None, frozenset({"fs:read", "fs:write"}), 0, 10_000)
    store[R.cred_id] = R
    C1 = mint_child(R, store, log, now=100.0, child_scope=frozenset({"fs:read", "fs:write"}), ttl=3600)
    C2 = mint_child(C1, store, log, now=110.0, child_scope=frozenset({"fs:read"}), ttl=1800)

    # Operator revokes C1 at T=200.
    log.revoked[C1.cred_id] = 200.0

    # C2 is structurally fine at T=202; the naive path would pass it.
    authorize_use(C2, store, log, now=202.0, requested=frozenset({"fs:read"}))  # raises

    # And the re-delegation that produced C3 in the incident is now blocked:
    try:
        C3 = mint_child(C2, store, log, now=209.0, child_scope=frozenset({"fs:read"}), ttl=1200)
    except DeadAncestryError as e:
        print(f"blocked re-derivation of dead authority: {e}")
