# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-capability-token-is-still-honored-by-a-peer-s-cached-trust-anchor-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-capability-token-is-still-honored-by-a-peer-s-cached-trust-anchor-mid-handoff.warrant.json
# Markdown SHA-256:   a7c526fcb2cec7be5c6dc80b16cb7d1200831331d2e15290426823fdade46580
# Code AST SHA-256:   f324a2545360c2515805486993c339f9a15fc427df5379e41510b4cc84f4ad01
# Verified Classes:   StaleAuthorityError, Capability, TrustAnchor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAuthorityError(RuntimeError):
    """Raised when a capability's cached authority cannot be freshly established
    within the token's remaining lifetime. The verifier must halt, not proceed."""


@dataclass(frozen=True)
class Capability:
    subject: str
    scope: str
    exp: float            # absolute epoch seconds
    issuer: str


@dataclass(frozen=True)
class TrustAnchor:
    issuer: str
    fetched_at: float     # epoch seconds when this anchor was retrieved
    delegation_active: bool


def verify_capability(
    cap: Capability,
    anchor: TrustAnchor,
    delta_rev: float,
    now: float | None = None,
) -> None:
    """Verify a federated capability token against a cached trust anchor.

    Enforces the authority-freshness invariant:
        anchor_age <= min(remaining_ttl, delta_rev)

    Raises StaleAuthorityError if the anchor is too old to substantiate
    authority before the token expires. Does NOT raise on mere signature
    or clock failure -- those are separate, upstream checks.
    """
    now = time.time() if now is None else now

    remaining_ttl = cap.exp - now
    if remaining_ttl <= 0:
        raise StaleAuthorityError(
            f"token for {cap.subject} already expired at verification time"
        )

    if anchor.issuer != cap.issuer:
        raise StaleAuthorityError(
            f"anchor issuer {anchor.issuer!r} does not match token issuer "
            f"{cap.issuer!r}; cannot substantiate authority"
        )

    if not anchor.delegation_active:
        raise StaleAuthorityError(
            f"delegation for {cap.issuer!r} is marked inactive at anchor fetch"
        )

    anchor_age = now - anchor.fetched_at
    freshness_budget = min(remaining_ttl, delta_rev)

    if anchor_age > freshness_budget:
        raise StaleAuthorityError(
            f"stale authority: anchor_age={anchor_age:.3f}s exceeds "
            f"freshness_budget={freshness_budget:.3f}s "
            f"(remaining_ttl={remaining_ttl:.3f}s, delta_rev={delta_rev:.3f}s); "
            f"halting rather than proceeding on cached authority"
        )


def execute_with_retry(
    cap: Capability,
    anchor: TrustAnchor,
    delta_rev: float,
    attempt: int,
    refresh_anchor,
) -> None:
    """Retry path that MUST refresh authority before re-verifying.

    A retry that re-verifies against the same anchor is a stale-authority
    amplifier and is rejected here.
    """
    now = time.time()
    remaining_ttl = cap.exp - now
    if remaining_ttl <= 0:
        raise StaleAuthorityError(
            f"retry attempt {attempt} at T+{now:.1f}: token expired; "
            f"cannot re-establish authority"
        )

    anchor_age = now - anchor.fetched_at
    if anchor_age > min(remaining_ttl, delta_rev):
        # Force a refresh; do not re-verify against the pinned anchor.
        refreshed = refresh_anchor(cap.issuer)
        if refreshed is None:
            raise StaleAuthorityError(
                f"retry attempt {attempt}: authority refresh failed and "
                f"cached anchor is stale (age={anchor_age:.3f}s); halting"
            )
        anchor = refreshed

    verify_capability(cap, anchor, delta_rev, now=now)
