diff --git a/sdk/rust/README.md b/sdk/rust/README.md index 61c5b1d4a4..3b0bc6c3e0 100644 --- a/sdk/rust/README.md +++ b/sdk/rust/README.md @@ -266,23 +266,52 @@ when recall credit was not disclosed. An omitted risk label is empty in `SearchHit.governed` and `SearchResponse.term_leg`; `retrieval_risk` describes the other hits. +The typed error methods and the retry behavior below apply to the SDK installed +from this checkout. The published `0.1.1` crate exposes the raw `ApiError` +fields, including `category` and `retryable`. + ```rust use clickhouse_loom::Error; match bot.get("deploy_window").await { Err(Error::Api(error)) => { - eprintln!("{} {} {:?} {:?}", error.status, error.code, error.category, error.retryable); + eprintln!("{} {} {:?} {}", error.status, error.code, error.kind(), error.category()); } Err(error) => eprintln!("{error}"), Ok(memory) => println!("found={}", memory.found), } ``` -API errors preserve the server's code, message, optional category and retryable -flag, retry hints, request ID and raw detail. Unknown error codes and categories -remain strings. An error response without a JSON body still carries the HTTP -status. `Error::Transport` reports HTTP transport failures; `Error::Protocol` -reports an invalid successful response. +API errors preserve the server's code, message, optional category and +retryable flag, retry hints, request ID and raw detail. Unknown error codes and +categories remain strings in those fields. An error response without a JSON +body still carries the HTTP status. `Error::Transport` reports HTTP transport +failures; `Error::Protocol` reports an invalid successful response. + +`ApiError::kind` is the typed class of an API error. A known code picks it; +otherwise the HTTP status does: 400 and 422 are `Validation`, 401 and 403 +`Auth`, 404 `NotFound`, and 409 and 412 `PreconditionFailed`. HTTP 429 is +always `RateLimited`. HTTP 5xx is `BackendUnavailable` unless the code is +`IDEMPOTENT_IN_PROGRESS`. If neither the code nor the status supplies a kind, +`kind()` returns `Other`; inspect `code` for more detail. + +`Error::category` and `Error::retryable` give the class in effect: the category +and flag the server declared, else the SDK's own class. By status alone, 401 +and 403 are `Auth`; 408 and 429 are `Capacity` and retryable; 502, 503 and 504 +are `Dependency` and retryable; any other 5xx is `Internal` and any other +status `Input`, neither retryable. A code the SDK never retries, such as +`ANALYSIS_UNAVAILABLE` or `PUBLICATION_PENDING`, keeps its own category and is +never retryable. A 5xx on an operation that is not declared idempotent is not +retryable when its body names no flag, since the call may have written; +`AUTH_UNAVAILABLE` shows that nothing ran. A transport failure is +`Dependency`: retryable when the server was never reached, otherwise not, since +the call may have run. An invalid response is `Internal`. + +A `PreconditionFailed` can carry the live row's hash in `current_sha256()`. +Use it to check which revision the server rejected the request against. For a definition's approval, +show the current text again and never resend the hash unseen. A `WrongCell` +answer names the `org` and the `cell` to call instead; `cell` is empty when the +server does not know it. ## Per-call options and metadata @@ -338,13 +367,18 @@ metadata. ## Retries and logging -Operation policies come from the full server registry. Retries after dispatch -require declared idempotence, including HTTP status retries, incomplete responses -and 429 pacing. `RetryTimeouts::Always` does not enable nonidempotent operations. +Operation policies come from the full server registry. A 429 is paced on +every operation: the server answers it before running anything. Other retries +after dispatch require declared idempotence, for HTTP status retries and +incomplete responses, unless the answer shows nothing ran. HTTP 408 and +`AUTH_UNAVAILABLE` are retried on any operation. `RetryTimeouts::Always` does +not enable nonidempotent operations. Calls do not follow redirects. Retry and pacing defaults are: - Up to 3 attempts on connection failures, HTTP 408 and HTTP 500–599. + For a nonidempotent operation, only HTTP 408 and `AUTH_UNAVAILABLE` + qualify for status retries under this budget. Configuration errors and the SDK's excluded error codes stop retries; `retryable=false` alone does not stop a status retry. - Exponential backoff starts at 100 ms, doubles to a 5 second ceiling, and uses @@ -354,9 +388,10 @@ Calls do not follow redirects. Retry and pacing defaults are: - Declared idempotent writes generate one UUID idempotency key per call and reuse it across retries and pacing. Timeouts and incomplete responses retry these writes by default. `get` and `search` do not retry those failures by default. -- Pacing is enabled separately from retries. A 429 waits at most 5 seconds per - round, with a 15 second total sleep budget per call. Missing, invalid or - over-cap hints use 1 second; a zero hint returns the error immediately. +- Pacing is enabled separately from retries. On a 429, the client waits for the + server's hint if it fits the remaining sleep budget (15 seconds per call by + default). Missing or invalid hints use 1 second. A zero hint or a wait + beyond the remaining budget returns the 429 without resending. Each pacing round starts a fresh retry budget. Recorded `X-RateLimit-*` headers can also delay a subsequent call to the same operation. @@ -438,8 +473,9 @@ omitted target fields to the client identity. `memory.recall` and `memory.brief` default only their required agent; optional filters use server defaults. `code.grep` omits `include_body` unless supplied, so the server chooses its default from `mode`. Unknown operations receive -bound org and namespace only and retry connection failures before dispatch. -They do not retry HTTP errors, timeouts, incomplete responses or 429 responses. +bound org and namespace only. They retry connection failures before dispatch +and an answer that shows nothing ran (HTTP 408, `AUTH_UNAVAILABLE`); a 429 is +paced. They do not retry other HTTP errors, timeouts or incomplete responses. The server validates fields and authorizes every operation. ## Routes outside the op registry diff --git a/sdk/rust/src/client.rs b/sdk/rust/src/client.rs index a3691ee18b..8f6bd51781 100644 --- a/sdk/rust/src/client.rs +++ b/sdk/rust/src/client.rs @@ -211,7 +211,10 @@ impl Client { /// Call any dotted wire operation, decoding its response as `T`. /// /// Known operations use generated identity and retry policies. Unknown operations - /// receive bound org/namespace and retry only failures before connection. + /// receive the client's org and namespace and are treated as non-idempotent. + /// They can retry connection failures and responses that show the handler did + /// not run (HTTP 408 or `AUTH_UNAVAILABLE`), subject to the retry policy. + /// HTTP 429 uses the client's separate pacing budget. pub async fn call( &self, op: &str, @@ -346,7 +349,8 @@ impl Client { } let mut error = ApiError::from_response(status.as_u16(), &headers, &bytes); error.request_id.get_or_insert_with(|| request_id.clone()); - if status.as_u16() == 429 && self.pacing && idempotent { + // The server answers a 429 before running any operation. + if status.as_u16() == 429 && self.pacing { let delay = pacing_delay( error.retry_after_s, self.ratelimit_max_wait.saturating_sub(paced), @@ -360,7 +364,9 @@ impl Client { continue; } } - let allowed = idempotent + // A status retry runs the operation again. Only a declared + // idempotent one is safe, unless the answer proves nothing ran. + let allowed = (idempotent || error.handler_never_ran()) && status.as_u16() != 429 && retry.statuses.contains(&status.as_u16()) && !error.forbids_retry(); @@ -380,6 +386,10 @@ impl Client { .is_some_and(|budget| delay > budget.saturating_sub(slept)) { log::error!(target: "clickhouse_loom", "{op} failed status={status} elapsed_ms={} attempts={sent} rid={request_id}", started.elapsed().as_millis()); + let mut error = error; + if let Error::Api(api) = &mut error { + api.mark_maybe_applied(idempotent); + } return Err(CallFailure { error, metadata: Some(Box::new(metadata)), @@ -576,13 +586,12 @@ fn valid_operation(op: &str) -> bool { } pub(crate) fn pacing_delay(hint: Option, budget: Duration) -> Duration { - let hint = hint - .filter(|s| s.is_finite() && *s <= 60.0) - .unwrap_or(1.0) - .max(0.0); - Duration::from_secs_f64(hint) - .min(Duration::from_secs(5)) - .min(budget) + let seconds = hint.filter(|s| s.is_finite()).unwrap_or(1.0).max(0.0); + // A shorter wait would resend before the server asked us to. + Duration::try_from_secs_f64(seconds) + .ok() + .filter(|delay| *delay <= budget) + .unwrap_or_default() } fn env_value(name: &str) -> Option { @@ -655,16 +664,19 @@ mod tests { } #[test] - fn pacing_caps_hints_and_budget_and_does_not_spin_on_zero() { + fn pacing_waits_for_the_hint_only_when_it_fits() { for (hint, budget, expected) in [ (None, 15, 1), - (Some(61.0), 15, 1), - (Some(60.0), 15, 5), - (Some(30.0), 2, 2), + (None, 0, 0), + (Some(61.0), 15, 0), + (Some(60.0), 60, 60), + (Some(8.0), 15, 8), + (Some(30.0), 2, 0), (Some(0.0), 15, 0), (Some(1.0), 0, 0), (Some(-1.0), 15, 0), (Some(f64::NAN), 15, 1), + (Some(f64::MAX), 15, 0), ] { assert_eq!( pacing_delay(hint, Duration::from_secs(budget)), diff --git a/sdk/rust/src/error.rs b/sdk/rust/src/error.rs index 12b5f29e25..4ee78425a0 100644 --- a/sdk/rust/src/error.rs +++ b/sdk/rust/src/error.rs @@ -1,10 +1,137 @@ -use std::time::SystemTime; +use std::{fmt, time::SystemTime}; use reqwest::header::{HeaderMap, RETRY_AFTER}; use serde_json::Value; +/// Whose move an error is: the server's `detail.category`, else the SDK's own class. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum ErrorCategory { + /// The request does not fit the data or the operation as they are now. + Input, + /// The token, its role or its namespace access does not cover the call. + Auth, + /// The server or a limit is busy or not ready; the request itself is fine. + Capacity, + /// A store or a model provider failed, was too slow or is still catching up. + Dependency, + /// The deployment is not in a state to serve the call; an operator must act. + Configuration, + /// The server failed. + Internal, +} + +impl ErrorCategory { + pub fn as_str(self) -> &'static str { + match self { + Self::Input => "input", + Self::Auth => "auth", + Self::Capacity => "capacity", + Self::Dependency => "dependency", + Self::Configuration => "configuration", + Self::Internal => "internal", + } + } + + fn from_name(name: &str) -> Option { + Some(match name { + "input" => Self::Input, + "auth" => Self::Auth, + "capacity" => Self::Capacity, + "dependency" => Self::Dependency, + "configuration" => Self::Configuration, + "internal" => Self::Internal, + _ => return None, + }) + } +} + +impl fmt::Display for ErrorCategory { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// The class of an API error, as the other SDKs pick an exception class: a +/// known `detail.code` picks it, else the HTTP status does. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum ErrorKind { + /// `VALIDATION_FAILED`, or HTTP 400 or 422 without a known code. + Validation, + /// `AUTH_INVALID`, `AUTH_INSUFFICIENT`, or HTTP 401 or 403 without a known code. + Auth, + /// `RESOURCE_NOT_FOUND`, or HTTP 404 without a known code. + NotFound, + /// `PRECONDITION_FAILED`, or HTTP 409 or 412 without a known code. Read + /// [`ApiError::current_sha256`] and the code before resending. + PreconditionFailed, + /// `IDEMPOTENT_CONFLICT`: an Idempotency-Key was reused with a different body. + IdempotentConflict, + /// `WRONG_CELL`: the org lives in another cell of the deployment. Nothing + /// was written; [`ApiError::org`] and [`ApiError::cell`] name where to call. + WrongCell, + /// HTTP 429. + RateLimited, + /// `IDEMPOTENT_IN_PROGRESS`: the first request with this key still runs. + IdempotentInProgress, + /// HTTP 5xx. + BackendUnavailable, + /// Any other code on any other status, such as `OVERRIDE_NOT_STORED` or 423 `LOCKED`. + Other, +} + +impl ErrorKind { + fn of(status: u16, code: &str) -> Self { + let class = match code { + "VALIDATION_FAILED" => Self::Validation, + "AUTH_INVALID" | "AUTH_INSUFFICIENT" => Self::Auth, + "RESOURCE_NOT_FOUND" => Self::NotFound, + "RATE_LIMITED" => Self::RateLimited, + "IDEMPOTENT_CONFLICT" => Self::IdempotentConflict, + "WRONG_CELL" => Self::WrongCell, + "IDEMPOTENT_IN_PROGRESS" => Self::IdempotentInProgress, + "PRECONDITION_FAILED" => Self::PreconditionFailed, + // ClickHouse refused to store an override: no precondition. + "OVERRIDE_NOT_STORED" => Self::Other, + "BACKEND_UNAVAILABLE" + | "OVERLOADED" + | "BACKEND_TIMEOUT" + | "SCHEMA_PENDING" + | "CODED_WIDTH_MISMATCH" => Self::BackendUnavailable, + _ => match status { + 400 | 422 => Self::Validation, + 401 | 403 => Self::Auth, + 404 => Self::NotFound, + 409 | 412 => Self::PreconditionFailed, + _ => Self::Other, + }, + }; + if status == 429 { + Self::RateLimited + } else if status >= 500 + && !matches!(class, Self::BackendUnavailable | Self::IdempotentInProgress) + { + Self::BackendUnavailable + } else { + class + } + } +} + +/// 5xx codes the SDK never resends, with their class. +const NEVER_RETRIED: [(&str, ErrorCategory); 7] = [ + ("ANALYSIS_UNAVAILABLE", ErrorCategory::Configuration), + ("ASSISTANT_UNAVAILABLE", ErrorCategory::Configuration), + ("CODED_WIDTH_MISMATCH", ErrorCategory::Configuration), + ("GATEWAY_REQUIRED", ErrorCategory::Configuration), + ("MODEL_CALL_UNATTRIBUTED", ErrorCategory::Internal), + ("PUBLICATION_PENDING", ErrorCategory::Dependency), + ("TENANCY_REFUSED", ErrorCategory::Configuration), +]; + /// An HTTP error carrying the server's code, message and error classification. -#[derive(Debug, derive_more::Display)] +#[derive(derive_more::Display)] #[display("HTTP {status} [{code}] {message}")] #[non_exhaustive] pub struct ApiError { @@ -19,6 +146,25 @@ pub struct ApiError { pub retry_after: Option, pub request_id: Option, pub detail: Value, + /// The SDK's own class, for what the transport knows and the body does not say. + pub(crate) sdk_class: Option<(ErrorCategory, bool)>, +} + +impl fmt::Debug for ApiError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // The methods resolve the class in effect; the fields show what the server sent. + f.debug_struct("ApiError") + .field("status", &self.status) + .field("code", &self.code) + .field("message", &self.message) + .field("category", &self.category) + .field("retryable", &self.retryable) + .field("retry_after_s", &self.retry_after_s) + .field("retry_after", &self.retry_after) + .field("request_id", &self.request_id) + .field("detail", &self.detail) + .finish() + } } impl ApiError { @@ -57,6 +203,7 @@ impl ApiError { .and_then(|v| v.to_str().ok()) .map(str::to_owned), detail, + sdk_class: None, } } } @@ -72,19 +219,101 @@ pub(crate) fn parse_retry_after(raw: &str, now: SystemTime) -> Option { } impl ApiError { + /// The typed class derived from the code and HTTP status. HTTP 429 is + /// always [`ErrorKind::RateLimited`]. HTTP 5xx is + /// [`ErrorKind::BackendUnavailable`] unless the code is `IDEMPOTENT_IN_PROGRESS`. + pub fn kind(&self) -> ErrorKind { + ErrorKind::of(self.status, &self.code) + } + + /// Whose move the error is: the category the server declared, else the + /// SDK's own class, the way [`Error::category`] resolves it. + pub fn category(&self) -> ErrorCategory { + match self.sdk_class { + Some((category, _)) => category, + None => self + .category + .as_deref() + .and_then(ErrorCategory::from_name) + .unwrap_or_else(|| self.fallback_class().0), + } + } + + /// Whether resending the same request unchanged can succeed later: the + /// flag the server declared, else the SDK's own class, the way + /// [`Error::retryable`] resolves it. + pub fn retryable(&self) -> bool { + match self.sdk_class { + Some((_, retryable)) => retryable, + None => self.retryable.unwrap_or_else(|| self.fallback_class().1), + } + } + + /// The live row's hash in a [`ErrorKind::PreconditionFailed`] response. + /// `None` for every other class and when the server named none. For a definition's + /// approval, show the current text again; never resend this hash unseen. + pub fn current_sha256(&self) -> Option<&str> { + self.detail_of(ErrorKind::PreconditionFailed, "current_sha256") + } + + /// The org of a [`ErrorKind::WrongCell`] answer; `None` for every other class. + pub fn org(&self) -> Option<&str> { + self.detail_of(ErrorKind::WrongCell, "org") + } + + /// The cell that holds the org of a [`ErrorKind::WrongCell`] answer; `None` + /// for every other class and when the server named none. + pub fn cell(&self) -> Option<&str> { + self.detail_of(ErrorKind::WrongCell, "cell") + } + + /// The SDK's class for a body that names none: a code it never retries + /// keeps that code's class, else the HTTP status alone decides. + fn fallback_class(&self) -> (ErrorCategory, bool) { + if let Some(category) = never_retried(&self.code) { + return (category, false); + } + match self.status { + 401 | 403 => (ErrorCategory::Auth, false), + 408 | 429 => (ErrorCategory::Capacity, true), + 502..=504 => (ErrorCategory::Dependency, true), + status if status >= 500 => (ErrorCategory::Internal, false), + _ => (ErrorCategory::Input, false), + } + } + + /// A 5xx on an operation that is not idempotent may follow a write the + /// call made, so it is not retryable whatever its status alone says, + /// unless its code proves the handler never ran. + pub(crate) fn mark_maybe_applied(&mut self, idempotent: bool) { + if idempotent || self.retryable.is_some() || self.status < 500 || self.handler_never_ran() { + return; + } + self.sdk_class = Some((self.category(), false)); + } + + pub(crate) fn handler_never_ran(&self) -> bool { + self.status == 408 || self.code == "AUTH_UNAVAILABLE" + } + pub(crate) fn forbids_retry(&self) -> bool { - self.category.as_deref() == Some("configuration") - || matches!( - self.code.as_str(), - "ANALYSIS_UNAVAILABLE" - | "ASSISTANT_UNAVAILABLE" - | "CODED_WIDTH_MISMATCH" - | "GATEWAY_REQUIRED" - | "MODEL_CALL_UNATTRIBUTED" - | "PUBLICATION_PENDING" - | "TENANCY_REFUSED" - ) + self.category.as_deref() == Some("configuration") || never_retried(&self.code).is_some() } + + /// A detail field of one class only, so a value of another class is not read as its own. + fn detail_of(&self, kind: ErrorKind, key: &str) -> Option<&str> { + (self.kind() == kind) + .then(|| self.detail.get(key)) + .flatten() + .and_then(Value::as_str) + } +} + +fn never_retried(code: &str) -> Option { + NEVER_RETRIED + .iter() + .find(|(known, _)| *known == code) + .map(|(_, category)| *category) } impl std::error::Error for ApiError {} @@ -108,6 +337,33 @@ pub enum Error { Api(Box), } +impl Error { + /// Whose move the error is, for every variant. An API error resolves as + /// [`ApiError::category`]. A transport failure is `Dependency`, an invalid + /// response `Internal`, and an invalid request or client configuration `Input`. + pub fn category(&self) -> ErrorCategory { + match self { + Self::Api(error) => error.category(), + Self::Transport(_) => ErrorCategory::Dependency, + Self::Protocol { .. } => ErrorCategory::Internal, + _ => ErrorCategory::Input, + } + } + + /// Whether resending the same request unchanged can succeed later, for + /// every variant. An API error resolves as [`ApiError::retryable`]. A + /// transport failure is retryable here only if it happened during + /// connection setup. This error does not know the operation's retry + /// policy. No other SDK-raised error is retryable. + pub fn retryable(&self) -> bool { + match self { + Self::Api(error) => error.retryable(), + Self::Transport(source) => source.is_connect(), + _ => false, + } + } +} + impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { @@ -122,6 +378,7 @@ impl std::error::Error for Error { #[cfg(test)] mod tests { use super::*; + use serde_json::json; use std::time::Duration; #[test] @@ -282,4 +539,264 @@ mod tests { original, )); } + + fn api(status: u16, detail: Value) -> ApiError { + let body = json!({"detail": detail}).to_string(); + ApiError::from_response(status, &HeaderMap::new(), body.as_bytes()) + } + + #[test] + fn the_class_follows_the_code_then_the_status() { + for (status, detail, expected) in [ + ( + 400, + json!({"code": "VALIDATION_FAILED"}), + ErrorKind::Validation, + ), + (422, json!({}), ErrorKind::Validation), + (401, json!({}), ErrorKind::Auth), + (403, json!({"code": "MODEL_CALL_REFUSED"}), ErrorKind::Auth), + (404, json!({"code": "AUTH_INSUFFICIENT"}), ErrorKind::Auth), + (404, json!({}), ErrorKind::NotFound), + ( + 409, + json!({"code": "PINNED_CONFLICT"}), + ErrorKind::PreconditionFailed, + ), + (412, json!({}), ErrorKind::PreconditionFailed), + ( + 409, + json!({"code": "IDEMPOTENT_CONFLICT"}), + ErrorKind::IdempotentConflict, + ), + (409, json!({"code": "WRONG_CELL"}), ErrorKind::WrongCell), + ( + 503, + json!({"code": "IDEMPOTENT_IN_PROGRESS"}), + ErrorKind::IdempotentInProgress, + ), + ( + 503, + json!({"code": "AUTH_UNAVAILABLE"}), + ErrorKind::BackendUnavailable, + ), + (500, json!({}), ErrorKind::BackendUnavailable), + ( + 503, + json!({"code": "RATE_LIMITED"}), + ErrorKind::BackendUnavailable, + ), + (429, json!({}), ErrorKind::RateLimited), + ( + 409, + json!({"code": "OVERRIDE_NOT_STORED"}), + ErrorKind::Other, + ), + (423, json!({"code": "LOCKED"}), ErrorKind::Other), + ] { + assert_eq!(api(status, detail).kind(), expected); + } + } + + #[test] + fn the_class_in_effect_is_the_declared_one_else_the_sdk_s() { + for (status, category, retryable) in [ + (400, ErrorCategory::Input, false), + (401, ErrorCategory::Auth, false), + (403, ErrorCategory::Auth, false), + (404, ErrorCategory::Input, false), + (408, ErrorCategory::Capacity, true), + (409, ErrorCategory::Input, false), + (429, ErrorCategory::Capacity, true), + (500, ErrorCategory::Internal, false), + (502, ErrorCategory::Dependency, true), + (503, ErrorCategory::Dependency, true), + (504, ErrorCategory::Dependency, true), + ] { + let error = api(status, json!({})); + assert_eq!( + (error.category(), error.retryable()), + (category, retryable), + "{status}" + ); + } + for (code, category) in [ + ("ANALYSIS_UNAVAILABLE", ErrorCategory::Configuration), + ("ASSISTANT_UNAVAILABLE", ErrorCategory::Configuration), + ("CODED_WIDTH_MISMATCH", ErrorCategory::Configuration), + ("GATEWAY_REQUIRED", ErrorCategory::Configuration), + ("MODEL_CALL_UNATTRIBUTED", ErrorCategory::Internal), + ("PUBLICATION_PENDING", ErrorCategory::Dependency), + ("TENANCY_REFUSED", ErrorCategory::Configuration), + ] { + let error = api(503, json!({"code": code})); + assert_eq!( + (error.category(), error.retryable()), + (category, false), + "{code}" + ); + assert!(error.forbids_retry()); + } + let error = api( + 503, + json!({"code": "INTERNAL_ERROR", "category": "capacity", "retryable": true}), + ); + assert_eq!( + (error.category(), error.retryable()), + (ErrorCategory::Capacity, true) + ); + // A name the SDK does not know falls back; the raw fields keep it. + let error = api(500, json!({"category": "future", "retryable": "yes"})); + assert_eq!( + (error.category(), error.retryable()), + (ErrorCategory::Internal, false) + ); + assert_eq!(error.category.as_deref(), Some("future")); + assert_eq!(error.retryable, None); + let error = api(423, json!({"category": "configuration"})); + assert_eq!(error.category(), ErrorCategory::Configuration); + assert!(error.forbids_retry()); + assert_eq!(ErrorCategory::Dependency.to_string(), "dependency"); + } + + #[test] + fn a_5xx_that_may_follow_a_write_is_not_retryable() { + for (status, code, idempotent, declared, expected) in [ + (503, "OVERLOADED", false, None, false), + (503, "OVERLOADED", true, None, true), + (503, "OVERLOADED", false, Some(true), true), + (503, "OVERLOADED", false, Some(false), false), + (500, "INTERNAL_ERROR", false, None, false), + (503, "AUTH_UNAVAILABLE", false, None, true), + (429, "RATE_LIMITED", false, None, true), + ] { + let mut detail = json!({"code": code}); + if let Some(declared) = declared { + detail["retryable"] = json!(declared); + } + let mut error = api(status, detail); + let category = error.category(); + error.mark_maybe_applied(idempotent); + assert_eq!( + error.retryable(), + expected, + "{code} {idempotent} {declared:?}" + ); + assert_eq!(error.category(), category); + assert_eq!(error.retryable, declared); + } + } + + #[test] + fn typed_details_belong_to_their_class() { + for (status, detail) in [ + ( + 409, + json!({"code": "PRECONDITION_FAILED", "current_sha256": "live"}), + ), + (412, json!({"current_sha256": "live"})), + ] { + assert_eq!(api(status, detail).current_sha256(), Some("live")); + } + assert_eq!( + api(409, json!({"code": "PRECONDITION_FAILED"})).current_sha256(), + None + ); + assert_eq!( + api( + 409, + json!({"code": "PRECONDITION_FAILED", "current_sha256": 7}) + ) + .current_sha256(), + None + ); + for code in ["IDEMPOTENT_CONFLICT", "WRONG_CELL", "OVERRIDE_NOT_STORED"] { + assert_eq!( + api(409, json!({"code": code, "current_sha256": "live"})).current_sha256(), + None + ); + } + + let elsewhere = api( + 409, + json!({"code": "WRONG_CELL", "org": "acme", "cell": "eu"}), + ); + assert_eq!( + (elsewhere.org(), elsewhere.cell()), + (Some("acme"), Some("eu")) + ); + let unplaced = api( + 409, + json!({"code": "WRONG_CELL", "org": "acme", "cell": ""}), + ); + assert_eq!(unplaced.cell(), Some("")); + let home = api( + 409, + json!({"code": "PRECONDITION_FAILED", "org": "acme", "cell": "eu"}), + ); + assert_eq!((home.org(), home.cell()), (None, None)); + + let mut error = api(503, json!({"code": "OVERLOADED"})); + error.mark_maybe_applied(false); + assert!(!format!("{error:?}").contains("sdk_class")); + } + + #[tokio::test] + async fn errors_the_sdk_raises_have_a_class() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + drop(listener); + let unreachable = Error::Transport( + reqwest::Client::new() + .get(format!("http://{addr}")) + .send() + .await + .unwrap_err(), + ); + assert_eq!( + (unreachable.category(), unreachable.retryable()), + (ErrorCategory::Dependency, true) + ); + + let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let client = reqwest::Client::builder() + .timeout(Duration::from_millis(50)) + .build() + .unwrap(); + let lost = Error::Transport( + client + .get(format!("http://{}", held.local_addr().unwrap())) + .send() + .await + .unwrap_err(), + ); + assert_eq!( + (lost.category(), lost.retryable()), + (ErrorCategory::Dependency, false) + ); + + let source = serde_json::from_str::("{").unwrap_err(); + let invalid = Error::Protocol { + status: 200, + source, + }; + assert_eq!( + (invalid.category(), invalid.retryable()), + (ErrorCategory::Internal, false) + ); + for error in [ + Error::Input("invalid".into()), + Error::Configuration("invalid".into()), + ] { + assert_eq!( + (error.category(), error.retryable()), + (ErrorCategory::Input, false) + ); + } + let error = Error::Api(Box::new(api(404, json!({})))); + assert_eq!( + (error.category(), error.retryable()), + (ErrorCategory::Input, false) + ); + } } diff --git a/sdk/rust/src/lib.rs b/sdk/rust/src/lib.rs index 5eb2435466..6dd9783179 100644 --- a/sdk/rust/src/lib.rs +++ b/sdk/rust/src/lib.rs @@ -7,7 +7,10 @@ //! including `serde_json::Value`. //! //! Identity is bound once on [`Client`]. Calls return typed responses, and -//! [`Error::Api`] preserves the server's error classification. +//! [`Error::Api`] preserves the server's error classification. Every error +//! answers [`Error::category`] and [`Error::retryable`] with the server's +//! declaration or the SDK's own class; an API error also has a typed +//! [`ApiError::kind`]. //! Search defaults to all agents with no user or session filter. Set filters on //! [`SearchRequest`] explicitly. Builder identity values apply to declared identity //! fields; optional reader filters keep the values in the request. @@ -23,9 +26,10 @@ //! [`Client::with_retry`] creates a policy override sharing connections and rate state. //! Dropping a call future cancels its retries and waits, but cannot undo a write. //! Logs use the `log` facade without installing a logger or recording payloads. -//! Retries after dispatch require a known, declared idempotent operation. -//! Unknown operations receive bound org and namespace and retry only connection -//! failures. Operation names must be dotted identifiers. +//! A 429 is paced on every operation. Other retries after dispatch require a +//! known, declared idempotent operation, unless the answer shows nothing ran: +//! HTTP 408 or `AUTH_UNAVAILABLE`. Unknown operations receive bound org and +//! namespace. Operation names must be dotted identifiers. //! //! Enable the `blocking` feature for a synchronous client in the `blocking` module. //! It runs the async transport on a dedicated thread and rejects calls on Tokio @@ -208,7 +212,7 @@ mod blocking_operations; pub use call::{CallFailure, CallMetadata, CallOptions, CallResult, RateLimit}; pub use capabilities::{ProbeReport, ProbeRequest}; pub use client::{Client, ClientBuilder}; -pub use error::{ApiError, Error}; +pub use error::{ApiError, Error, ErrorCategory, ErrorKind}; pub use models::*; pub use retry::{RetryPolicy, RetryTimeouts}; pub use routes::{Method, RouteRequest, RouteResponse}; diff --git a/sdk/rust/src/routes.rs b/sdk/rust/src/routes.rs index 9cd6a75ebc..a7e5d28772 100644 --- a/sdk/rust/src/routes.rs +++ b/sdk/rust/src/routes.rs @@ -126,7 +126,9 @@ impl Client { /// Only `CallOptions::timeout` and `CallOptions::request_id` apply. The /// SDK resends only on a 429, after the server's hint and within the /// client's pacing budget. A refused HTTP/2 stream returns a transport - /// error without a retry. + /// error without a retry. For a method that can write, a 5xx without + /// an explicit retry flag or a code proving the handler did not run + /// is reported as nonretryable: the server may already have applied it. pub async fn request(&self, request: RouteRequest) -> Result { self.request_with_options(request, CallOptions::default()) .await @@ -235,6 +237,7 @@ impl Client { continue; } } + error.mark_maybe_applied(method.is_safe()); log::error!(target: "clickhouse_loom", "{route} failed status={} elapsed_ms={} attempts={attempts} rid={request_id}", status.as_u16(), started.elapsed().as_millis()); return Err(CallFailure { error: Error::Api(Box::new(error)), diff --git a/sdk/rust/tests/blocking_cases/mod.rs b/sdk/rust/tests/blocking_cases/mod.rs index c0df20d47f..6177562f70 100644 --- a/sdk/rust/tests/blocking_cases/mod.rs +++ b/sdk/rust/tests/blocking_cases/mod.rs @@ -264,6 +264,48 @@ fn clones_run_concurrently_and_survive_original_drop() { request(&server); } +#[test] +fn synchronous_calls_pace_and_retry_by_the_async_rules() { + for (status, code, retried) in [ + (429, "RATE_LIMITED", true), + (408, "REQUEST_TIMEOUT", true), + (503, "OVERLOADED", false), + ] { + let server = Server::new(vec![ + response( + status, + json!({"detail": {"code": code, "message": "again", "retry_after_s": 0.01}}), + "", + ), + response(200, json!({"answer": "ok"}), ""), + retry_scope::unused_response(), + ]); + let client = blocking::Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("") + .retry(retry_scope::immediate()) + .build() + .unwrap(); + let result = client.call::( + "assistant.ask", + &json!({"question": "which"}), + CallOptions::default(), + ); + assert_eq!(result.is_ok(), retried, "{code}"); + assert!(!request(&server).headers.contains_key("idempotency-key")); + let second = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async { + tokio::time::timeout(Duration::from_millis(300), server.request()) + .await + .is_ok() + }); + assert_eq!(second, retried, "{code}"); + } +} + #[tokio::test] async fn runtime_construction_drop_and_calls_have_explicit_boundaries() { let client = blocking::Client::builder("org", "ns", "bot") diff --git a/sdk/rust/tests/client.rs b/sdk/rust/tests/client.rs index aa0fe53f04..4665c4f118 100644 --- a/sdk/rust/tests/client.rs +++ b/sdk/rust/tests/client.rs @@ -10,7 +10,9 @@ use std::{ time::{Duration, Instant}, }; -use clickhouse_loom::{Client, Error, RetryPolicy, RetryTimeouts, SearchRequest, SetRequest}; +use clickhouse_loom::{ + Client, Error, ErrorCategory, ErrorKind, RetryPolicy, RetryTimeouts, SearchRequest, SetRequest, +}; use serde_json::{json, Value}; use tokio::{ process::Command, @@ -43,6 +45,9 @@ mod review_regressions; #[path = "routes/mod.rs"] mod routes; +#[path = "retry_scope/mod.rs"] +mod retry_scope; + #[cfg(feature = "blocking")] #[path = "blocking_cases/mod.rs"] mod blocking_cases; @@ -463,6 +468,15 @@ async fn api_errors_preserve_categories_and_retry_hints() { assert_eq!(error.retry_after.as_deref(), Some("8")); assert_eq!(error.request_id.as_deref(), Some("request-1")); assert_eq!(error.detail["custom"], 42); + // A name the SDK does not know falls back to the status rule. + let expected = if category == "future" { + "capacity" + } else { + category + }; + assert_eq!(error.category().as_str(), expected); + assert!(!error.retryable()); + assert_eq!(error.kind(), ErrorKind::RateLimited); } } @@ -490,6 +504,11 @@ async fn nonstandard_http_errors_keep_the_status() { assert_eq!(error.category, None); assert_eq!(error.retryable, None); assert_eq!(error.retry_after_s, Some(3.0)); + assert_eq!(error.kind(), ErrorKind::BackendUnavailable); + assert_eq!( + (error.category(), error.retryable()), + (ErrorCategory::Dependency, true) + ); } } @@ -505,9 +524,96 @@ async fn unknown_error_codes_and_date_retry_headers_survive() { }; assert_eq!(error.code, "FUTURE_CONFLICT"); assert_eq!(error.retry_after_s, Some(0.0)); + assert_eq!(error.kind(), ErrorKind::PreconditionFailed); + assert_eq!( + (error.category(), error.retryable()), + (ErrorCategory::Input, false) + ); assert!(error.retry_after.unwrap().contains("GMT")); } +#[tokio::test] +async fn a_final_5xx_is_retryable_only_where_nothing_could_have_written() { + for (op, idempotent) in [ + ("assistant.ask", false), + ("future.op", false), + ("memory.get", true), + ] { + for (detail, retryable) in [ + (json!({"code": "OVERLOADED"}), idempotent), + (json!({"code": "OVERLOADED", "retryable": true}), true), + (json!({"code": "OVERLOADED", "retryable": false}), false), + (json!({"code": "AUTH_UNAVAILABLE"}), true), + ] { + let server = Server::new(vec![ + response(503, json!({"detail": detail}), ""), + response(200, "{}", ""), + ]); + let client = Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("") + .retry(RetryPolicy::disabled()) + .build() + .unwrap(); + let failure = client + .call::(op, &json!({}), clickhouse_loom::CallOptions::default()) + .await + .unwrap_err(); + let error = &failure.error; + assert_eq!(error.category(), ErrorCategory::Dependency, "{op} {detail}"); + assert_eq!(error.retryable(), retryable, "{op} {detail}"); + server.request().await; + assert!( + tokio::time::timeout(Duration::from_millis(300), server.request()) + .await + .is_err() + ); + } + } +} + +#[tokio::test] +async fn precondition_and_wrong_cell_answers_expose_their_details() { + let server = Server::new(vec![ + response( + 409, + json!({"detail": {"code": "PRECONDITION_FAILED", "message": "stale", + "current_sha256": "live"}}), + "", + ), + response( + 409, + json!({"detail": {"code": "WRONG_CELL", "message": "elsewhere", + "org": "acme", "cell": "eu"}}), + "", + ), + ]); + let client = server.client(); + let Error::Api(error) = client + .set(SetRequest::new("key", json!({})).if_match_sha256("stale")) + .await + .unwrap_err() + else { + panic!("expected API error"); + }; + assert_eq!(error.kind(), ErrorKind::PreconditionFailed); + assert_eq!(error.current_sha256(), Some("live")); + assert_eq!( + (error.category(), error.retryable()), + (ErrorCategory::Input, false) + ); + assert_eq!((error.org(), error.cell()), (None, None)); + server.request().await; + + let Error::Api(error) = client.get("key").await.unwrap_err() else { + panic!("expected API error"); + }; + assert_eq!(error.kind(), ErrorKind::WrongCell); + assert_eq!((error.org(), error.cell()), (Some("acme"), Some("eu"))); + assert_eq!(error.current_sha256(), None); + server.request().await; +} + #[tokio::test] async fn successful_but_invalid_payloads_are_protocol_errors() { for body in ["not json", "[]", "{}"] { diff --git a/sdk/rust/tests/first_phase/mod.rs b/sdk/rust/tests/first_phase/mod.rs index 7d6ea0c777..163dbb109d 100644 --- a/sdk/rust/tests/first_phase/mod.rs +++ b/sdk/rust/tests/first_phase/mod.rs @@ -231,11 +231,10 @@ async fn generic_calls_cover_operations_without_facades_and_future_operations() } #[tokio::test] -async fn unknown_and_nonidempotent_operations_never_retry_after_dispatch() { +async fn nonidempotent_operations_are_paced_on_a_429_and_retry_nothing_else() { for op in ["future.operation", "memory.touch"] { for reply in [ response(503, "{}", ""), - response(429, "{}", "Retry-After: 0.001\r\n"), "HTTP/1.1 200 OK\r\nContent-Length: 100\r\nConnection: close\r\n\r\n{}".into(), ] { let server = Server::new(vec![reply, response(200, "{}", "")]); @@ -253,6 +252,23 @@ async fn unknown_and_nonidempotent_operations_never_retry_after_dispatch() { .headers .contains_key("idempotency-key")); } + let server = Server::new(vec![ + response(429, "{}", "Retry-After: 0.001\r\n"), + response(200, "{}", ""), + ]); + let result = server + .client() + .call::(op, &json!({}), CallOptions::default()) + .await + .unwrap(); + assert_eq!(result.metadata.attempts, 2, "{op}"); + for _ in 0..2 { + assert!(!server + .request() + .await + .headers + .contains_key("idempotency-key")); + } } } diff --git a/sdk/rust/tests/network_cases/mod.rs b/sdk/rust/tests/network_cases/mod.rs index 654d0a898a..5f5cd39346 100644 --- a/sdk/rust/tests/network_cases/mod.rs +++ b/sdk/rust/tests/network_cases/mod.rs @@ -212,7 +212,7 @@ async fn pacing_has_its_own_budget_and_resets_retry_attempts() { } #[tokio::test] -async fn pacing_zero_and_exhausted_budget_return_429() { +async fn pacing_zero_and_over_budget_hints_return_429_without_resending() { for hint in ["0", "0.01"] { let server = Server::new(vec![ response(429, "", &format!("Retry-After: {hint}\r\n")); @@ -224,11 +224,18 @@ async fn pacing_zero_and_exhausted_budget_return_429() { .ratelimit_max_wait(Duration::from_millis(1)) .build() .unwrap(); - assert!(matches!(client.get("key").await, Err(Error::Api(e)) if e.status == 429)); + let failure = client + .get_with_options("key", clickhouse_loom::CallOptions::default()) + .await + .unwrap_err(); + assert!(matches!(failure.error, Error::Api(e) if e.status == 429)); + assert_eq!(failure.metadata.unwrap().attempts, 1); server.request().await; - if hint != "0" { - assert_eq!(server.request().await.headers["x-loom-retry-count"], "1"); - } + assert!( + tokio::time::timeout(Duration::from_millis(300), server.request()) + .await + .is_err() + ); } } diff --git a/sdk/rust/tests/retry_scope/mod.rs b/sdk/rust/tests/retry_scope/mod.rs new file mode 100644 index 0000000000..93caebf430 --- /dev/null +++ b/sdk/rust/tests/retry_scope/mod.rs @@ -0,0 +1,201 @@ +use super::*; +use clickhouse_loom::{CallFailure, CallOptions, CallResult}; + +/// Operations the registry does not mark idempotent. +const NOT_REPLAYED: [&str; 2] = ["assistant.ask", "future.op"]; + +pub(super) fn unused_response() -> String { + // A queued response keeps the fixture listening, so an extra request would arrive. + response(200, "{}", "") +} + +fn refused(status: u16, code: &str) -> String { + response( + status, + json!({"detail": {"code": code, "message": "again", "retry_after_s": 0.01}}), + "", + ) +} + +fn accepted() -> String { + response(200, json!({"answer": "ok"}), "") +} + +pub(super) fn immediate() -> RetryPolicy { + let mut policy = RetryPolicy::default(); + policy.backoff = Duration::ZERO; + policy.backoff_jitter = 0.0; + policy +} + +async fn ask( + client: &Client, + op: &str, + request_id: &str, +) -> Result, CallFailure> { + client + .call::( + op, + &json!({"question": "which"}), + CallOptions::default().request_id(request_id), + ) + .await +} + +#[tokio::test] +async fn a_429_is_paced_on_operations_that_declare_no_idempotence() { + for op in NOT_REPLAYED { + let server = Server::new(vec![ + refused(429, "RATE_LIMITED"), + accepted(), + unused_response(), + ]); + let client = Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("") + .build() + .unwrap(); + let result = ask(&client, op, "paced-1").await.unwrap(); + assert_eq!(result.data["answer"], "ok"); + assert_eq!(result.metadata.attempts, 2); + for retry_count in ["0", "1"] { + let request = server.request().await; + assert_eq!(request.line, format!("POST /v1/{op} HTTP/1.1")); + assert_eq!(request.headers["x-request-id"], "paced-1"); + assert_eq!(request.headers["x-loom-retry-count"], retry_count); + assert!(!request.headers.contains_key("idempotency-key")); + } + + let server = Server::new(vec![refused(429, "RATE_LIMITED"), accepted()]); + let client = Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("") + .ratelimit_max_wait(Duration::ZERO) + .build() + .unwrap(); + let failure = ask(&client, op, "refused-1").await.unwrap_err(); + let Error::Api(error) = failure.error else { + panic!("expected API error"); + }; + assert_eq!(error.status, 429); + assert_eq!(failure.metadata.unwrap().attempts, 1); + assert_eq!(server.request().await.headers["x-request-id"], "refused-1"); + assert!( + tokio::time::timeout(Duration::from_millis(300), server.request()) + .await + .is_err() + ); + } +} + +#[tokio::test] +async fn a_429_with_a_hint_past_the_budget_is_not_resent() { + let server = Server::new(vec![ + response( + 429, + json!({"detail": {"code": "RATE_LIMITED"}}), + "Retry-After: 3600\r\n", + ), + accepted(), + ]); + let failure = ask(&server.client(), "assistant.ask", "daily-limit") + .await + .unwrap_err(); + let Error::Api(error) = failure.error else { + panic!("expected API error"); + }; + assert_eq!(error.status, 429); + assert_eq!(error.retry_after_s, Some(3600.0)); + assert_eq!(failure.metadata.unwrap().attempts, 1); + assert_eq!( + server.request().await.line, + "POST /v1/assistant.ask HTTP/1.1" + ); + assert!( + tokio::time::timeout(Duration::from_millis(300), server.request()) + .await + .is_err() + ); +} + +#[tokio::test] +async fn an_answer_that_shows_nothing_ran_is_retried_on_any_operation() { + for op in NOT_REPLAYED { + for (status, code) in [(408, "REQUEST_TIMEOUT"), (503, "AUTH_UNAVAILABLE")] { + let server = Server::new(vec![refused(status, code), accepted()]); + let client = Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("") + .retry(immediate()) + .build() + .unwrap(); + let result = ask(&client, op, "ran-later").await.unwrap(); + assert_eq!(result.data["answer"], "ok", "{op} {code}"); + assert_eq!(result.metadata.attempts, 2); + for retry_count in ["0", "1"] { + let request = server.request().await; + assert_eq!(request.headers["x-request-id"], "ran-later"); + assert_eq!(request.headers["x-loom-retry-count"], retry_count); + assert!(!request.headers.contains_key("idempotency-key")); + } + } + } +} + +#[tokio::test] +async fn every_other_answer_still_needs_declared_idempotence() { + for op in NOT_REPLAYED { + for (status, code) in [ + (500, "INTERNAL_ERROR"), + (503, "OVERLOADED"), + (408, "GATEWAY_REQUIRED"), + ] { + let server = Server::new(vec![refused(status, code), response(200, "{}", "")]); + let failure = ask(&server.client(), op, "once").await.unwrap_err(); + let Error::Api(error) = failure.error else { + panic!("expected API error"); + }; + assert_eq!(error.status, status, "{op} {code}"); + assert_eq!(failure.metadata.unwrap().attempts, 1); + assert_eq!(server.request().await.headers["x-loom-retry-count"], "0"); + assert!( + tokio::time::timeout(Duration::from_millis(300), server.request()) + .await + .is_err(), + "{op} {code}" + ); + } + } +} + +#[tokio::test] +async fn a_never_ran_answer_follows_the_policy() { + for (policy, retried) in [ + (RetryPolicy::disabled(), false), + (without(&503), false), + (without(&408), true), + ] { + let server = Server::new(vec![refused(503, "AUTH_UNAVAILABLE"), accepted()]); + let client = Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("") + .retry(policy) + .build() + .unwrap(); + let result = ask(&client, "assistant.ask", "policy").await; + assert_eq!(result.is_ok(), retried); + server.request().await; + assert_eq!( + tokio::time::timeout(Duration::from_millis(300), server.request()) + .await + .is_ok(), + retried + ); + } +} + +fn without(status: &u16) -> RetryPolicy { + let mut policy = immediate(); + policy.statuses.remove(status); + policy +} diff --git a/sdk/rust/tests/routes/mod.rs b/sdk/rust/tests/routes/mod.rs index bd51c7dd06..236d6268e8 100644 --- a/sdk/rust/tests/routes/mod.rs +++ b/sdk/rust/tests/routes/mod.rs @@ -1,5 +1,5 @@ use super::*; -use clickhouse_loom::{CallFailure, CallOptions, RouteRequest, RouteResponse}; +use clickhouse_loom::{CallFailure, CallOptions, Method, RouteRequest, RouteResponse}; pub(super) fn unused_response() -> String { // A queued response keeps the fixture listening, so an extra request would arrive. @@ -189,9 +189,8 @@ async fn a_429_with_no_wait_to_take_is_returned() { .is_err() ); - // The last wait is cut to what is left of the budget, then the 429 stands. + // After one wait, the next hint no longer fits the remaining budget. let server = Server::new(vec![ - refused(json!(0.05)), refused(json!(0.05)), refused(json!(0.05)), unused_response(), @@ -206,8 +205,8 @@ async fn a_429_with_no_wait_to_take_is_returned() { .request_json_with_options::(route(), CallOptions::default()) .await .unwrap_err(); - assert_eq!(attempts_of(failure), 3); - for _ in 0..3 { + assert_eq!(attempts_of(failure), 2); + for _ in 0..2 { server.request().await; } assert!( @@ -235,6 +234,38 @@ async fn a_route_is_not_resent_when_the_connection_closes_without_an_answer() { ); } +#[tokio::test] +async fn a_raw_503_is_not_retryable_after_a_route_write() { + for (method, path, retryable) in [ + (Method::POST, "/v1/knowledge.upload", false), + (Method::GET, "/v1/whoami", true), + ] { + let server = Server::new(vec![ + response(503, "Service unavailable", ""), + unused_response(), + ]); + let failure = server + .client() + .request_json_with_options::( + RouteRequest::new(method.clone(), path), + CallOptions::default(), + ) + .await + .unwrap_err(); + let Error::Api(error) = failure.error else { + panic!("expected API error"); + }; + assert_eq!(error.status, 503); + assert_eq!(error.retryable, None); + assert_eq!(error.retryable(), retryable, "{method}"); + assert_eq!(failure.metadata.unwrap().attempts, 1); + assert_eq!( + server.request().await.line, + format!("{method} {path} HTTP/1.1") + ); + } +} + #[tokio::test] async fn route_errors_are_returned_without_a_retry() { for (status, body, code, message) in [