# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-peer-identity-that-arrives-after-a-baton-handoff-has-already-crossed-a-trust-domain-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-peer-identity-that-arrives-after-a-baton-handoff-has-already-crossed-a-trust-domain-boundary.warrant.json
# Markdown SHA-256:   193d6f59d943d9bfe4214be8692a0ad73c11c2b2e674e80162174583382752ff
# Code AST SHA-256:   85f6ddfb3a0bb8a444bcabc2e03de1796cfbe0fdc539c41302ac71705120c715
# Verified Classes:   RevokedWarrantError, EpochProbeTimeout, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevokedWarrantError(RuntimeError):
    """Raised when a cross-domain warrant's epoch is stale relative to the issuer."""


class EpochProbeTimeout(RuntimeError):
    """Raised when the issuer's current revocation epoch cannot be confirmed."""


@dataclass
class Warrant:
    subject: str
    issuer_domain: str
    epoch: int
    issued_at: float
    expires_at: float

    @property
    def remaining_ttl(self) -> float:
        return self.expires_at - time.monotonic()


def admit_cross_domain_handoff(
    warrant: Warrant,
    issuer_current_epoch: int | None,
    max_revocation_staleness: float,
    probe_fn,
    probe_timeout: float = 0.5,
) -> str:
    """Decide execute / quarantine / reject for an inbound baton warrant.

    Returns 'execute' only when freshness is provable. Any unprovable-freshness
    path must quarantine or reject; never fall through to execute.
    """
    if warrant.remaining_ttl <= 0:
        raise RevokedWarrantError(
            f"warrant for {warrant.subject} already expired at use-time"
        )

    # Path 1: bounded staleness — TTL short enough that a stale cache is safe.
    if warrant.remaining_ttl <= max_revocation_staleness:
        return "execute"

    # Path 2: epoch-bound check — need issuer's current epoch at use-time.
    if issuer_current_epoch is None:
        try:
            issuer_current_epoch = probe_fn(warrant.issuer_domain, probe_timeout)
        except TimeoutError as exc:
            # Fail closed: unprovable freshness must never execute.
            raise EpochProbeTimeout(
                f"epoch probe to {warrant.issuer_domain} timed out; "
                f"refusing to execute warrant for {warrant.subject}"
            ) from exc

    if warrant.epoch < issuer_current_epoch:
        raise RevokedWarrantError(
            f"warrant epoch {warrant.epoch} < issuer epoch {issuer_current_epoch} "
            f"for subject {warrant.subject}; identity revoked in issuing domain"
        )

    return "execute"
