# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-an-attenuated-delegatee-from-executing-on-a-revoked-parent-warrant-during-a-mid-flight-delegation-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-an-attenuated-delegatee-from-executing-on-a-revoked-parent-warrant-during-a-mid-flight-delegation-handoff.warrant.json
# Markdown SHA-256:   e17eb469f28f4ea53a7e739568da9d5a00237471161490bd04cb50619f916d4f
# Code AST SHA-256:   00fe3247f50becaf4b1d42a1d3fd4e57603a90122f1ad2c4e3ffb4253e6ed29b
# Verified Classes:   StaleAuthorityError, RevocationList, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class StaleAuthorityError(RuntimeError):
    """Raised when a delegatee attempts execution under a chain containing a revoked ancestor."""


class RevocationList:
    """Pull-based revocation set. Eventually consistent; callers must tolerate staleness."""
    def __init__(self) -> None:
        self._revoked: dict[str, float] = {}

    def revoke(self, token_id: str, at: Optional[float] = None) -> None:
        self._revoked[token_id] = at if at is not None else time.time()

    def is_revoked(self, token_id: str, at: float) -> bool:
        ts = self._revoked.get(token_id)
        return ts is not None and ts <= at


@dataclass
class Warrant:
    token_id: str
    scope: str
    expiry: float
    chain: list[str] = field(default_factory=list)  # ancestor token_ids, root-last

    def full_chain(self) -> list[str]:
        return [self.token_id, *self.chain]


def execute_under_warrant(
    warrant: Warrant,
    revocation_list: RevocationList,
    now: Optional[float] = None,
) -> str:
    """
    Enforce the freshness predicate: valid(W, t) iff chain verifies AND no ancestor revoked at t.
    Any implementation that checks only the leaf, or checks at mint time, is unsound.
    """
    t = now if now is not None else time.time()

    if t >= warrant.expiry:
        raise StaleAuthorityError(
            f"warrant {warrant.token_id} expired at {warrant.expiry}, now={t}"
        )

    # The load-bearing clause: check EVERY ancestor at execution time, not just the leaf.
    for ancestor_id in warrant.full_chain():
        if revocation_list.is_revoked(ancestor_id, at=t):
            raise StaleAuthorityError(
                f"execution blocked: ancestor {ancestor_id} revoked before t={t}; "
                f"chain={warrant.full_chain()}; re-delegate from a live root"
            )

    return f"executed {warrant.scope} under {warrant.token_id} at t={t}"


# Reproduction of the failure trace:
rl = RevocationList()
root = Warrant("W_O", "write:repo/foo", expiry=time.time() + 3600)
leaf = Warrant("W_E", "write:repo/foo/bar/file.txt", expiry=time.time() + 900,
               chain=["W_P", "W_O"])

# T=400: root revoked out-of-band.
rl.revoke("W_O", at=time.time())

# T=900-ish: leaf still cryptographically valid, but freshness predicate must fail.
try:
    execute_under_warrant(leaf, rl)
except StaleAuthorityError as e:
    print(f"correctly blocked: {e}")
    # Do NOT retry; re-delegate from a live root.
