# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-capability-token-was-revoked-two-hops-upstream-before-the-next-tool-call-fires.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-capability-token-was-revoked-two-hops-upstream-before-the-next-tool-call-fires.warrant.json
# Markdown SHA-256:   d7be45c5bae920c1ffab3909691c8100707f75463dc998aa02d9501c0376761d
# Code AST SHA-256:   34bafcf7eb53a0321e3fb7fc00c72135e2cf4bdc350f37b2523a10c47447a563
# Verified Classes:   RevocationFreshnessError, AncestorRevokedError, CapabilityToken, RevocationView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class RevocationFreshnessError(RuntimeError):
    """Raised when a delegated token's ancestor revocation state cannot be
    observed within the required freshness bound. Fail closed."""
    pass


class AncestorRevokedError(PermissionError):
    """Terminal, non-retryable: an ancestor grant was revoked.
    Must NOT be caught by retry-on-expiry logic."""
    pass


@dataclass
class CapabilityToken:
    grant_id: str
    parent_id: Optional[str]
    scope: str
    exp: float                      # absolute epoch seconds
    revocation_endpoint: str


@dataclass
class RevocationView:
    """Per-verifier cache of revocation observations."""
    revoked: set = field(default_factory=set)
    last_check: dict = field(default_factory=dict)   # grant_id -> epoch

    def observe(self, grant_id: str, revoked_now: bool, at: float):
        if revoked_now:
            self.revoked.add(grant_id)
        self.last_check[grant_id] = at


def ancestors(token: CapabilityToken, registry: dict) -> list:
    chain, cur = [], token
    while cur is not None:
        chain.append(cur)
        cur = registry.get(cur.parent_id) if cur.parent_id else None
    return chain


def verify_at_tool_call(
    token: CapabilityToken,
    registry: dict,
    view: RevocationView,
    now: float,
    freshness_bound: float,
    poll_fn,                       # poll_fn(grant_id) -> bool (revoked?)
) -> None:
    """Enforce: unexpired AND every ancestor observed fresh AND none revoked."""
    if now >= token.exp:
        raise TimeoutError(f"token {token.grant_id} expired")  # retryable: re-mint

    for anc in ancestors(token, registry):
        if anc.grant_id in view.revoked:
            # strip scope so retry layer cannot re-mint from dead authority
            view.revoked.add(token.grant_id)
            raise AncestorRevokedError(
                f"ancestor {anc.grant_id} revoked; refusing {token.grant_id}"
            )
        last = view.last_check.get(anc.grant_id)
        if last is None or now - last > freshness_bound:
            try:
                is_revoked = poll_fn(anc.grant_id)
            except Exception as e:
                raise RevocationFreshnessError(
                    f"cannot confirm liveness of {anc.grant_id}: {e}"
                ) from e
            view.observe(anc.grant_id, is_revoked, now)
            if is_revoked:
                view.revoked.add(token.grant_id)
                raise AncestorRevokedError(
                    f"ancestor {anc.grant_id} revoked on fresh poll"
                )


def guarded_tool_call(token, registry, view, now, freshness_bound, poll_fn, invoke):
    verify_at_tool_call(token, registry, view, now, freshness_bound, poll_fn)
    return invoke()


# --- failure trace reproduction ---
def _demo():
    reg = {
        "g0": CapabilityToken("g0", None, "write:/proj/**", 1e12, "root/rev"),
        "g1": CapabilityToken("g1", "g0", "write:/proj/build/**", 1e12, "root/rev"),
        "g2": CapabilityToken("g2", "g1", "write:/proj/build/**", 1e12, "root/rev"),
    }
    view = RevocationView()
    # hop 3 cached validity at t=120 and never re-checked; root revoked g0 at t=400
    view.observe("g1", False, 120.0)
    revoked_set = {"g0"}

    def poll(gid):
        return gid in revoked_set

    try:
        guarded_tool_call(reg["g2"], reg, view, now=400.0,
                          freshness_bound=60.0, poll_fn=poll,
                          invoke=lambda: "wrote /proj/build/out.bin")
    except AncestorRevokedError as e:
        print(f"[BLOCKED] {e}")   # ancestor walk catches g0 despite stale g1 cache
    except RevocationFreshnessError as e:
        print(f"[FAIL-CLOSED] {e}")


if __name__ == "__main__":
    _demo()
