# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-mid-handoff-when-a2a-v1-0-card-signatures-were-valid-at-discovery-time.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-mid-handoff-when-a2a-v1-0-card-signatures-were-valid-at-discovery-time.warrant.json
# Markdown SHA-256:   340b9e91646b7669958a535045b894b5a3d1ab2dcd3ece54c3071bace0959506
# Code AST SHA-256:   5bebfe20ed0ab48d54fd5540e200cb87c9531035c0bff4d29ded75f8a9113032
# Verified Classes:   RevocationPropagationError, CachedCard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationPropagationError(RuntimeError):
    """Raised when a cached card's liveness cannot be bounded within the
    federation's revocation propagation window."""
    pass


@dataclass
class CachedCard:
    issuer: str
    key_id: str
    serial: str
    signature_valid: bool          # point-in-time; never changes on revocation
    last_revocation_check: float   # monotonic seconds
    card_hash: str


def assert_handoff_safe(
    card: CachedCard,
    revocation_list: set[tuple[str, str, str]] | None,
    now: float,
    delta_propagation: float,
) -> None:
    """Gate a handoff on BOTH signature validity and revocation liveness.

    Signature validity alone is insufficient: revoked cards hash identically
    to live cards, so a hash-keyed verification cache is revocation-blind.
    """
    if not card.signature_valid:
        raise RevocationPropagationError(
            f"card {card.issuer}/{card.serial}: signature invalid"
        )

    age = now - card.last_revocation_check
    if age > delta_propagation:
        # Stale-by-construction: cannot bound liveness. Fail closed.
        raise RevocationPropagationError(
            f"card {card.issuer}/{card.serial}: revocation state {age:.1f}s old "
            f"exceeds propagation bound {delta_propagation:.1f}s; "
            f"re-fetch required before handoff"
        )

    if revocation_list is None:
        # Unreachable list endpoint is NOT a pass.
        raise RevocationPropagationError(
            f"card {card.issuer}/{card.serial}: revocation list unavailable; "
            f"fail-closed"
        )

    triple = (card.issuer, card.key_id, card.serial)
    if triple in revocation_list:
        raise RevocationPropagationError(
            f"card {card.issuer}/{card.serial}: REVOKED; abort handoff and re-plan, "
            f"do not retry"
        )


def handoff(card: CachedCard, revocation_list, delta_propagation: float) -> None:
    assert_handoff_safe(card, revocation_list, time.monotonic(), delta_propagation)
    # ... proceed with state transfer ...
