# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-stale-capability-attenuation-across-multi-hop-a2a-delegation-when-revocation-propagates-faster-than-the-bearer-s-re-attest.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-stale-capability-attenuation-across-multi-hop-a2a-delegation-when-revocation-propagates-faster-than-the-bearer-s-re-attest.warrant.json
# Markdown SHA-256:   8383cc41a01a5dd581876f54d9370b54318f56e7e1c7904157b03c622bc4d997
# Code AST SHA-256:   82505b81b308b8a35dabb094ad9a4d1d50e5b2a70662960c36cde12b9835b5ec
# Verified Classes:   StaleDelegationError, AuthorityUnreachableError, DelegatedToken, EpochAuthority
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleDelegationError(RuntimeError):
    """Raised when an in-flight child token descends from a revoked root grant."""
    pass


class AuthorityUnreachableError(RuntimeError):
    """Raised when epoch lookup fails; treated as revoked (fail closed)."""
    pass


@dataclass(frozen=True)
class DelegatedToken:
    token_id: str
    root_grant_id: str
    root_grant_epoch: int
    capabilities: frozenset
    expires_at: float


class EpochAuthority:
    def __init__(self):
        self._epochs = {}
        self._reachable = True

    def set_epoch(self, grant_id: str, epoch: int):
        self._epochs[grant_id] = epoch

    def current_epoch(self, grant_id: str) -> int:
        if not self._reachable:
            raise AuthorityUnreachableError(grant_id)
        return self._epochs.get(grant_id, -1)


def verify_lineage(token: DelegatedToken, authority: EpochAuthority,
                   lookup_timeout: float = 0.5) -> None:
    """Called by an intermediate hop on every forwarded result."""
    if time.time() >= token.expires_at:
        raise StaleDelegationError(f"token {token.token_id} expired")
    try:
        current = authority.current_epoch(token.root_grant_id)
    except AuthorityUnreachableError as exc:
        raise StaleDelegationError(
            f"authority unreachable for {token.root_grant_id}; failing closed"
        ) from exc
    if current != token.root_grant_epoch:
        raise StaleDelegationError(
            f"token {token.token_id} lineage stale: "
            f"token epoch {token.root_grant_epoch} != authority {current}"
        )


def forward_result(token: DelegatedToken, authority: EpochAuthority, payload):
    verify_lineage(token, authority)
    return {"accepted": True, "payload": payload}


# --- demonstration of the boundary ---
auth = EpochAuthority()
auth.set_epoch("grant-A", 7)
tok = DelegatedToken("child-1", "grant-A", 7, frozenset({"write:store"}),
                     time.time() + 300)

forward_result(tok, auth, "op-1")          # passes
auth.set_epoch("grant-A", 8)               # root revokes; epoch bumps
try:
    forward_result(tok, auth, "op-2")      # stale lineage detected
except StaleDelegationError as e:
    print("blocked:", e)
