# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-cross-org-capability-token-as-a-one-shot-warrant-rather-than-a-renewable-session-handle.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-cross-org-capability-token-as-a-one-shot-warrant-rather-than-a-renewable-session-handle.warrant.json
# Markdown SHA-256:   1569d0932499f8ff49341e744e8bbb5ad28bb37958f8e8e63a09f944e8a44aae
# Code AST SHA-256:   b8a58f06fca587ab30cb52398ecf64e621d236cf20787240300f736487b3bd72
# Verified Classes:   TransmissionState, OneShotWarrantReuseError, Warrant, OutboundCall
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum


class TransmissionState(Enum):
    UNSENT = "unsent"
    SENT_UNKNOWN = "sent_unknown"
    SENT_ACKED = "sent_acked"


class OneShotWarrantReuseError(RuntimeError):
    """Raised when a retry would re-present a possibly-consumed one-shot warrant."""


@dataclass
class Warrant:
    jti: str
    audience: str
    scope_set: frozenset
    expires_at: float
    foreign_issuer: bool
    has_nonce: bool
    refresh_bound_to_act_chain: bool

    def is_one_shot(self) -> bool:
        return self.foreign_issuer and (self.has_nonce or self.refresh_bound_to_act_chain)


@dataclass
class OutboundCall:
    warrant: Warrant
    idempotency_key: str
    state: TransmissionState = TransmissionState.UNSENT
    attempts: int = 0


def retry_after_failure(call: OutboundCall, error_class: str, p99_rtt: float) -> str:
    call.attempts += 1
    short_lived = (call.warrant.expires_at - time.time()) < 10 * p99_rtt

    if call.warrant.is_one_shot() and short_lived:
        if call.state is TransmissionState.SENT_UNKNOWN:
            raise OneShotWarrantReuseError(
                f"warrant jti={call.warrant.jti} aud={call.warrant.audience} "
                f"may already be redeemed on far side; re-presentation would burn the "
                f"act chain. error_class={error_class!r} is retryable at transport layer "
                f"but not at credential layer. Escalate or resolve via idempotency_key="
                f"{call.idempotency_key!r}."
            )
        if call.state is TransmissionState.UNSENT:
            return "retry_transport_same_warrant"

    if error_class in ("504", "502", "connection_reset"):
        return "retry_transport_same_warrant"
    return "fail_permanently"
