# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-capability-token-whose-attenuation-chain-outlives-the-delegating-parent-s-revocation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-capability-token-whose-attenuation-chain-outlives-the-delegating-parent-s-revocation-epoch.warrant.json
# Markdown SHA-256:   bdf1aab13964d7576d0717a80586fb562c8d884b40131a414975f6876fc95828
# Code AST SHA-256:   629f12be6d9fe3c7ab7bfbb070f8ae27526961af57634f5bc9fb4e9def362fec
# Verified Classes:   StaleAuthorityError, EpochRollbackError, DelegatedToken, VerifierFloor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleAuthorityError(RuntimeError):
    """Raised when a delegated token's root epoch is below the verifier's floor."""


class EpochRollbackError(RuntimeError):
    """Raised when an epoch increment would move the root's counter backwards."""


@dataclass
class DelegatedToken:
    token_id: str
    root_principal: str
    root_epoch: int          # signed, non-attenuatable, propagated through chain
    caveats: list = field(default_factory=list)
    expires_at: float = 0.0


@dataclass
class VerifierFloor:
    """A verifier's cached view of each root principal's minimum live epoch."""
    floors: dict = field(default_factory=dict)
    refreshed_at: dict = field(default_factory=dict)
    max_staleness_s: float = 60.0

    def refresh(self, root_principal: str, epoch: int, now: float) -> None:
        current = self.floors.get(root_principal, 0)
        if epoch < current:
            raise EpochRollbackError(
                f"epoch for {root_principal} would roll back {current} -> {epoch}; "
                "refusing to re-validate previously revoked tokens"
            )
        self.floors[root_principal] = epoch
        self.refreshed_at[root_principal] = now

    def is_fresh(self, root_principal: str, now: float) -> bool:
        ts = self.refreshed_at.get(root_principal)
        return ts is not None and (now - ts) <= self.max_staleness_s


def verify_delegated_token(
    token: DelegatedToken,
    floor: VerifierFloor,
    now: float,
) -> bool:
    # 1. Cryptographic + caveat checks (assumed done by caller; both pass here).
    if now >= token.expires_at:
        raise StaleAuthorityError(f"token {token.token_id} expired at {token.expires_at}")

    # 2. Root liveness check — the predicate the un-epoch-bound system omits.
    if not floor.is_fresh(token.root_principal, now):
        # A stale floor is equivalent to no floor: we cannot bound revocation lag.
        raise StaleAuthorityError(
            f"verifier floor for {token.root_principal} is stale; "
            f"cannot establish liveness of root epoch {token.root_epoch}"
        )

    live_floor = floor.floors.get(token.root_principal, 0)
    if token.root_epoch < live_floor:
        raise StaleAuthorityError(
            f"token {token.token_id} minted under root epoch {token.root_epoch} "
            f"but live floor is {live_floor}; delegating root has been revoked"
        )

    return True


# --- Failure trace: the observed incident ---
floor = VerifierFloor(max_staleness_s=60.0)
floor.refresh("O", epoch=41, now=1000.0)          # O mints cap(O->A) in epoch 41

leaf_c = DelegatedToken(
    token_id="cap(B->C)",
    root_principal="O",
    root_epoch=41,                                 # propagated unchanged through A, B
    expires_at=1000.0 + 4 * 3600,
)

# At t=2000 O revokes cap(O->A); epoch -> 42; floor pushed to verifiers.
floor.refresh("O", epoch=42, now=2000.0)

try:
    verify_delegated_token(leaf_c, floor, now=2001.0)
except StaleAuthorityError as e:
    print(f"BLOCKED: {e}")   # leaf_c rejected despite valid signature + caveats
