| 1 | //! LLM Client Trait and Retry Logic |
| 2 | //! |
| 3 | //! This module provides a unified interface for LLM providers with robust retry logic, |
| 4 | //! exponential backoff, and proper error classification. |
| 5 | //! |
| 6 | //! # Architecture |
| 7 | //! |
| 8 | //! - `LlmClient` trait: Async interface for LLM providers (DeepSeek, `OpenAI`, etc.) |
| 9 | //! - `RetryConfig`: Configurable retry behavior with exponential backoff and jitter |
| 10 | //! - `LlmError`: Classified errors with retryability information |
| 11 | |
| 12 | //! - `with_retry`: Generic retry wrapper for any async operation |
| 13 | //! |
| 14 | //! # Example |
| 15 | //! |
| 16 | //! ```ignore |
| 17 | //! use crate::llm_client::{LlmClient, RetryConfig, with_retry}; |
| 18 | //! |
| 19 | //! let config = RetryConfig::default(); |
| 20 | //! let result = with_retry(&config, || async { |
| 21 | //! client.create_message(request).await |
| 22 | //! }, None).await; |
| 23 | //! ``` |
| 24 | |
| 25 | pub mod rate_limit; |
| 26 | |
| 27 | pub use codewhale_error_taxonomy::RequestTransmission; |
| 28 | |
| 29 | use anyhow::Result; |
| 30 | use codewhale_command_contract::metrics::format_duration; |
| 31 | use codewhale_models::{MessageRequest, MessageResponse, StreamEvent}; |
| 32 | use codewhale_runtime::config::{RateLimitRetryPolicy, RetryPolicy}; |
| 33 | use serde_json::Value; |
| 34 | use std::future::Future; |
| 35 | use std::pin::Pin; |
| 36 | use std::time::{Duration, Instant}; |
| 37 | use uuid::Uuid; |
| 38 | |
| 39 | #[cfg(any(test, feature = "test-support"))] |
| 40 | pub mod mock; |
| 41 | |
| 42 | // === LlmClient Trait === |
| 43 | |
| 44 | /// Type alias for boxed stream of SSE events |
| 45 | pub type StreamEventBox = |
| 46 | Pin<Box<dyn futures_util::Stream<Item = Result<StreamEvent>> + Send + 'static>>; |
| 47 | |
| 48 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] |
| 49 | pub struct ToolWireMeasurement { |
| 50 | pub tool_schema_bytes: usize, |
| 51 | pub tool_schema_sha256: String, |
| 52 | pub tool_count: usize, |
| 53 | pub omitted_tool_names: Vec<String>, |
| 54 | pub omitted_tool_count: usize, |
| 55 | } |
| 56 | |
| 57 | impl ToolWireMeasurement { |
| 58 | #[must_use] |
| 59 | pub fn bounded_for_receipt(mut self) -> Self { |
| 60 | self.omitted_tool_names = |
| 61 | codewhale_models::tool_projection::bounded_tool_projection_warning_names( |
| 62 | &self.omitted_tool_names, |
| 63 | ); |
| 64 | self |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | /// Unified interface for LLM providers. |
| 69 | /// |
| 70 | /// This trait abstracts over different LLM APIs (DeepSeek, `OpenAI`, etc.) |
| 71 | /// allowing the agent to work with any provider that implements this interface. |
| 72 | /// |
| 73 | /// # Implementation Notes |
| 74 | /// |
| 75 | /// - All methods are async and require `Send + Sync` for thread safety |
| 76 | /// - The `create_message_stream` method returns a pinned boxed stream for SSE |
| 77 | /// - Implementations should handle their own authentication and base URL configuration |
| 78 | #[allow(async_fn_in_trait)] // Trait methods are part of the LLM provider interface |
| 79 | pub trait LlmClient: Send + Sync { |
| 80 | /// Returns the provider name (e.g., "openai", "deepseek") |
| 81 | fn provider_name(&self) -> &'static str; |
| 82 | |
| 83 | /// Returns the model identifier being used |
| 84 | fn model(&self) -> &str; |
| 85 | |
| 86 | fn measure_outbound_tools( |
| 87 | &self, |
| 88 | _request: MessageRequest, |
| 89 | ) -> Result<Option<ToolWireMeasurement>> { |
| 90 | Ok(None) |
| 91 | } |
| 92 | |
| 93 | /// Creates a non-streaming message completion |
| 94 | fn create_message( |
| 95 | &self, |
| 96 | request: MessageRequest, |
| 97 | ) -> impl Future<Output = Result<MessageResponse>> + Send; |
| 98 | |
| 99 | /// Dispatch a fresh request. Clients with a local response cache must |
| 100 | /// override this; authorization decisions cannot reuse earlier answers. |
| 101 | fn create_message_uncached( |
| 102 | &self, |
| 103 | request: MessageRequest, |
| 104 | ) -> impl Future<Output = Result<MessageResponse>> + Send { |
| 105 | self.create_message(request) |
| 106 | } |
| 107 | |
| 108 | /// Creates a streaming message completion |
| 109 | /// |
| 110 | /// Returns a stream of SSE events that should be consumed until completion. |
| 111 | fn create_message_stream( |
| 112 | &self, |
| 113 | request: MessageRequest, |
| 114 | ) -> impl Future<Output = Result<StreamEventBox>> + Send; |
| 115 | |
| 116 | /// Optional health check to verify API connectivity |
| 117 | fn health_check(&self) -> impl Future<Output = Result<bool>> + Send { |
| 118 | async { Ok(true) } |
| 119 | } |
| 120 | |
| 121 | /// The concrete base URL requests go to, when the implementation knows it. |
| 122 | /// |
| 123 | /// Background cost accrual uses this for billing provenance only: it is |
| 124 | /// reduced to a non-secret surface classification and a SHA-256 fingerprint |
| 125 | /// before being recorded, and the URL itself is never persisted or logged |
| 126 | /// (#4318). The default is `None` so an implementation that cannot report a |
| 127 | /// stable endpoint yields "unknown endpoint" — which fails closed — rather |
| 128 | /// than being assumed to be the provider's public API. |
| 129 | fn billing_base_url(&self) -> Option<&str> { |
| 130 | None |
| 131 | } |
| 132 | |
| 133 | /// Non-secret limits frozen with the resolved route, when available. |
| 134 | fn route_limits(&self) -> Option<codewhale_config::route::RouteLimits> { |
| 135 | None |
| 136 | } |
| 137 | |
| 138 | fn effective_context_window(&self, _model: &str) -> Option<u32> { |
| 139 | None |
| 140 | } |
| 141 | |
| 142 | /// Output cap for a request sent through this exact client route. |
| 143 | fn effective_max_output_tokens(&self, requested_model: &str) -> u32 { |
| 144 | let route = self.effective_route_envelope(requested_model, chrono::Utc::now()); |
| 145 | crate::route_budget::effective_max_output_tokens_for_turn_with_window( |
| 146 | route.provider, |
| 147 | &route.model, |
| 148 | self.route_limits(), |
| 149 | self.effective_context_window(requested_model), |
| 150 | None, |
| 151 | None, |
| 152 | ) |
| 153 | } |
| 154 | |
| 155 | /// Freeze the non-secret effective route immediately before a request is |
| 156 | /// dispatched. Implementations with richer configured identity/billing |
| 157 | /// facts should override this fail-closed default. |
| 158 | fn effective_route_envelope( |
| 159 | &self, |
| 160 | requested_model: &str, |
| 161 | dispatched_at: chrono::DateTime<chrono::Utc>, |
| 162 | ) -> crate::cost_status::EffectiveRouteEnvelope { |
| 163 | let provider = codewhale_config::ProviderKind::parse(self.provider_name()) |
| 164 | .unwrap_or(codewhale_config::ProviderKind::Custom); |
| 165 | crate::cost_status::EffectiveRouteEnvelope::capture_observed( |
| 166 | provider, |
| 167 | self.provider_name(), |
| 168 | requested_model, |
| 169 | self.billing_base_url(), |
| 170 | dispatched_at, |
| 171 | ) |
| 172 | } |
| 173 | |
| 174 | fn supports_catalog_reviewer_model(&self, _candidate: &str) -> bool { |
| 175 | let Some(provider) = codewhale_config::ProviderKind::parse(self.provider_name()) else { |
| 176 | return false; |
| 177 | }; |
| 178 | self.billing_base_url() |
| 179 | .is_some_and(|url| codewhale_config::provider_base_url_is_official(provider, url)) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | // === Authentication diagnostics === |
| 184 | |
| 185 | #[derive(Debug, Clone, PartialEq, Eq, Default)] |
| 186 | pub struct AuthenticationErrorContext { |
| 187 | pub provider: Option<String>, |
| 188 | pub base_url_authority: Option<String>, |
| 189 | pub model: Option<String>, |
| 190 | pub key_source: Option<String>, |
| 191 | pub key_fingerprint: Option<String>, |
| 192 | pub key_kind: Option<String>, |
| 193 | /// The one command or action that replaces the rejected credential. |
| 194 | pub fix: Option<String>, |
| 195 | } |
| 196 | |
| 197 | impl AuthenticationErrorContext { |
| 198 | #[must_use] |
| 199 | pub fn from_parts( |
| 200 | provider: Option<&str>, |
| 201 | base_url: Option<&str>, |
| 202 | model: Option<&str>, |
| 203 | key_source: Option<&str>, |
| 204 | api_key: Option<&str>, |
| 205 | ) -> Self { |
| 206 | let api_key = api_key.and_then(non_empty_trimmed); |
| 207 | Self { |
| 208 | provider: provider.and_then(non_empty_trimmed).map(str::to_string), |
| 209 | base_url_authority: base_url.and_then(base_url_authority), |
| 210 | model: model.and_then(non_empty_trimmed).map(str::to_string), |
| 211 | key_source: key_source.and_then(non_empty_trimmed).map(str::to_string), |
| 212 | key_fingerprint: api_key.map(redacted_key_fingerprint), |
| 213 | key_kind: api_key.map(classify_api_key_prefix).map(str::to_string), |
| 214 | fix: None, |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | #[must_use] |
| 219 | pub fn with_fix(mut self, fix: impl Into<String>) -> Self { |
| 220 | self.fix = Some(fix.into()).filter(|fix: &String| !fix.trim().is_empty()); |
| 221 | self |
| 222 | } |
| 223 | |
| 224 | fn is_empty(&self) -> bool { |
| 225 | self.provider.is_none() |
| 226 | && self.base_url_authority.is_none() |
| 227 | && self.model.is_none() |
| 228 | && self.key_source.is_none() |
| 229 | && self.key_fingerprint.is_none() |
| 230 | && self.key_kind.is_none() |
| 231 | && self.fix.is_none() |
| 232 | } |
| 233 | |
| 234 | fn detail_segments(&self) -> Vec<String> { |
| 235 | let mut segments = Vec::new(); |
| 236 | if let Some(provider) = self.provider.as_deref() { |
| 237 | segments.push(format!("provider: {provider}")); |
| 238 | } |
| 239 | if let Some(authority) = self.base_url_authority.as_deref() { |
| 240 | segments.push(format!("base URL authority: {authority}")); |
| 241 | } |
| 242 | if let Some(model) = self.model.as_deref() { |
| 243 | segments.push(format!("model: {model}")); |
| 244 | } |
| 245 | if let Some(source) = self.key_source.as_deref() { |
| 246 | segments.push(format!("key source: {source}")); |
| 247 | } |
| 248 | if let Some(fingerprint) = self.key_fingerprint.as_deref() { |
| 249 | segments.push(format!("key fingerprint: {fingerprint}")); |
| 250 | } |
| 251 | if let Some(kind) = self.key_kind.as_deref() { |
| 252 | segments.push(format!("key type: {kind}")); |
| 253 | } |
| 254 | if let Some(fix) = self.fix.as_deref() { |
| 255 | segments.push(format!("fix: {fix}")); |
| 256 | } |
| 257 | segments |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 262 | pub struct AuthenticationErrorDetail { |
| 263 | message: String, |
| 264 | context: Option<AuthenticationErrorContext>, |
| 265 | } |
| 266 | |
| 267 | impl AuthenticationErrorDetail { |
| 268 | #[must_use] |
| 269 | pub fn new(message: impl Into<String>) -> Self { |
| 270 | Self { |
| 271 | message: message.into(), |
| 272 | context: None, |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | #[must_use] |
| 277 | pub fn with_context( |
| 278 | message: impl Into<String>, |
| 279 | context: Option<AuthenticationErrorContext>, |
| 280 | ) -> Self { |
| 281 | let context = context.filter(|context| !context.is_empty()); |
| 282 | Self { |
| 283 | message: message.into(), |
| 284 | context, |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | #[must_use] |
| 289 | pub fn to_user_message(&self) -> String { |
| 290 | let Some(context) = self.context.as_ref() else { |
| 291 | return self.message.clone(); |
| 292 | }; |
| 293 | let segments = context.detail_segments(); |
| 294 | if segments.is_empty() { |
| 295 | self.message.clone() |
| 296 | } else { |
| 297 | format!("{} ({})", self.message, segments.join(", ")) |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | impl From<String> for AuthenticationErrorDetail { |
| 303 | fn from(message: String) -> Self { |
| 304 | Self::new(message) |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | impl From<&str> for AuthenticationErrorDetail { |
| 309 | fn from(message: &str) -> Self { |
| 310 | Self::new(message) |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | #[must_use] |
| 315 | pub fn classify_api_key_prefix(api_key: &str) -> &'static str { |
| 316 | if api_key.starts_with("tp-") { |
| 317 | "Xiaomi MiMo Token Plan key" |
| 318 | } else { |
| 319 | "API key" |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | fn non_empty_trimmed(value: &str) -> Option<&str> { |
| 324 | let value = value.trim(); |
| 325 | if value.is_empty() { None } else { Some(value) } |
| 326 | } |
| 327 | |
| 328 | pub fn base_url_authority(base_url: &str) -> Option<String> { |
| 329 | let base_url = non_empty_trimmed(base_url)?; |
| 330 | let without_scheme = base_url |
| 331 | .split_once("://") |
| 332 | .map_or(base_url, |(_, rest)| rest); |
| 333 | let authority = without_scheme.split('/').next().unwrap_or(without_scheme); |
| 334 | let authority = authority |
| 335 | .rsplit_once('@') |
| 336 | .map_or(authority, |(_, authority)| authority); |
| 337 | non_empty_trimmed(authority).map(str::to_string) |
| 338 | } |
| 339 | |
| 340 | fn redacted_key_fingerprint(api_key: &str) -> String { |
| 341 | let api_key = api_key.trim(); |
| 342 | let len = api_key.chars().count(); |
| 343 | match public_key_prefix(api_key) { |
| 344 | Some(prefix) => format!("{prefix}... (len={len})"), |
| 345 | None => format!("unprefixed (len={len})"), |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | fn public_key_prefix(api_key: &str) -> Option<&str> { |
| 350 | ["tp-", "sk-", "hf_", "hf-", "ak-", "rk-"] |
| 351 | .into_iter() |
| 352 | .find(|prefix| api_key.starts_with(prefix)) |
| 353 | } |
| 354 | |
| 355 | #[cfg(any(test, feature = "test-support"))] |
| 356 | fn redact_api_key_from_message(message: &str, api_key: Option<&str>) -> String { |
| 357 | let Some(api_key) = api_key.and_then(non_empty_trimmed) else { |
| 358 | return message.to_string(); |
| 359 | }; |
| 360 | message.replace(api_key, "[redacted API key]") |
| 361 | } |
| 362 | |
| 363 | // === LlmError - Classified Error Types === |
| 364 | |
| 365 | /// Evidence captured when a provider response explicitly identifies plan quota |
| 366 | /// exhaustion. The private field prevents callers outside this parser module |
| 367 | /// from manufacturing the durable classification from arbitrary text. |
| 368 | #[derive(Debug)] |
| 369 | pub struct QuotaExhaustionError { |
| 370 | message: String, |
| 371 | } |
| 372 | |
| 373 | impl QuotaExhaustionError { |
| 374 | fn from_http_message(message: String) -> Self { |
| 375 | Self { message } |
| 376 | } |
| 377 | |
| 378 | pub fn into_message(self) -> String { |
| 379 | self.message |
| 380 | } |
| 381 | |
| 382 | /// Append route guidance (which account hit the limit, how to switch) |
| 383 | /// to already-classified evidence. Cannot manufacture the class. |
| 384 | #[must_use] |
| 385 | pub fn with_guidance(mut self, guidance: &str) -> Self { |
| 386 | self.message = format!("{}\n{guidance}", self.message); |
| 387 | self |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 392 | #[serde(rename_all = "snake_case")] |
| 393 | pub enum ProviderUsageCoverage { |
| 394 | Reported, |
| 395 | Missing, |
| 396 | Incomplete, |
| 397 | NotDispatched, |
| 398 | Rejected, |
| 399 | } |
| 400 | |
| 401 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 402 | pub enum RetryOperation { |
| 403 | #[default] |
| 404 | Inference, |
| 405 | ReadOnly, |
| 406 | } |
| 407 | |
| 408 | /// Classified LLM errors with retryability information. |
| 409 | /// |
| 410 | /// This enum categorizes API errors to enable smart retry decisions. |
| 411 | /// Only authoritative rate limits and proven transient pre-dispatch failures |
| 412 | /// permit an inference retry. |
| 413 | #[derive(Debug)] |
| 414 | pub enum LlmError { |
| 415 | /// Rate limit exceeded (HTTP 429) |
| 416 | /// Contains optional Retry-After duration from server |
| 417 | RateLimited { |
| 418 | message: String, |
| 419 | retry_after: Option<Duration>, |
| 420 | }, |
| 421 | /// A quota window requiring caller policy or user action rather than a short retry. |
| 422 | QuotaWindow { |
| 423 | message: String, |
| 424 | retry_after: Option<Duration>, |
| 425 | transmission: RequestTransmission, |
| 426 | }, |
| 427 | |
| 428 | /// The provider explicitly reported that the account's plan quota is exhausted. |
| 429 | /// |
| 430 | /// Unlike an ordinary 429 rate limit, retrying the same request after a short |
| 431 | /// backoff cannot resolve this condition. This variant is constructed only at |
| 432 | /// a provider HTTP or structured stream-event boundary from explicit quota evidence. |
| 433 | QuotaExhausted(QuotaExhaustionError), |
| 434 | |
| 435 | /// Server error (HTTP 5xx) |
| 436 | ServerError { status: u16, message: String }, |
| 437 | |
| 438 | /// Network connectivity error |
| 439 | NetworkError(String), |
| 440 | |
| 441 | HeaderTimeout { |
| 442 | waited: Duration, |
| 443 | http1: bool, |
| 444 | retried: u32, |
| 445 | }, |
| 446 | |
| 447 | ConnectError { |
| 448 | message: String, |
| 449 | transient: bool, |
| 450 | timed_out: bool, |
| 451 | }, |
| 452 | |
| 453 | /// Request timed out |
| 454 | Timeout(Duration), |
| 455 | |
| 456 | /// Authentication failed (HTTP 401, selected HTTP 403) |
| 457 | AuthenticationError(AuthenticationErrorDetail), |
| 458 | |
| 459 | /// Authorization or provider-side blocking failed (HTTP 403) |
| 460 | AuthorizationError(String), |
| 461 | |
| 462 | /// Invalid request parameters or body size (HTTP 4xx) |
| 463 | InvalidRequest { status: u16, message: String }, |
| 464 | |
| 465 | /// Model-specific error (model not found, etc.) |
| 466 | ModelError(String), |
| 467 | |
| 468 | /// Content policy violation (safety filters) |
| 469 | ContentPolicyError(String), |
| 470 | |
| 471 | /// Failed to parse API response |
| 472 | ParseError(String), |
| 473 | |
| 474 | /// Context length exceeded |
| 475 | ContextLengthError(String), |
| 476 | |
| 477 | /// Catch-all for other errors |
| 478 | Other(String), |
| 479 | } |
| 480 | |
| 481 | fn opencode_go_hint(message: &str) -> &'static str { |
| 482 | let lowered = message.to_lowercase(); |
| 483 | if lowered.contains("codewhale auth set") { |
| 484 | return ""; |
| 485 | } |
| 486 | if (lowered.contains("free usage limit") |
| 487 | || lowered.contains("freeusagelimiterror") |
| 488 | || lowered.contains("free models work in opencode")) |
| 489 | && lowered.contains("opencode") |
| 490 | { |
| 491 | " OpenCode Zen's *-free models are restricted to OpenCode's own client and fail from third-party clients like Codewhale; use a paid OpenCode Zen model or another provider, or for OpenCode Go (a separate provider with its own key) run: codewhale auth set --provider opencode-go" |
| 492 | } else if lowered.contains("opencode go") || lowered.contains("opencode.ai/go") { |
| 493 | " OpenCode Go is a separate provider with its own key; run: codewhale auth set --provider opencode-go" |
| 494 | } else { |
| 495 | "" |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | impl std::fmt::Display for LlmError { |
| 500 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 501 | match self { |
| 502 | LlmError::QuotaWindow { |
| 503 | message, |
| 504 | retry_after, |
| 505 | .. |
| 506 | } => { |
| 507 | let hint = opencode_go_hint(message); |
| 508 | match retry_after { |
| 509 | Some(d) => write!( |
| 510 | f, |
| 511 | "Rate limit exceeded: {message}; quota window resets in {}; automatic retry stopped{hint}", |
| 512 | format_duration(*d) |
| 513 | ), |
| 514 | None => write!( |
| 515 | f, |
| 516 | "Rate limit exceeded: {message}; automatic retry stopped{hint}" |
| 517 | ), |
| 518 | } |
| 519 | } |
| 520 | LlmError::RateLimited { message, .. } => write!( |
| 521 | f, |
| 522 | "Rate limit exceeded: {message}{}", |
| 523 | opencode_go_hint(message) |
| 524 | ), |
| 525 | LlmError::QuotaExhausted(error) => { |
| 526 | write!(f, "Provider plan quota exhausted: {}", error.message) |
| 527 | } |
| 528 | LlmError::ServerError { status, message } => { |
| 529 | write!(f, "Server error ({status}): {message}") |
| 530 | } |
| 531 | LlmError::NetworkError(msg) => write!(f, "Network error: {msg}"), |
| 532 | LlmError::HeaderTimeout { .. } => { |
| 533 | write!(f, "Network error: {}", self.header_timeout_message()) |
| 534 | } |
| 535 | LlmError::ConnectError { message, .. } => { |
| 536 | write!(f, "Connection failed before request dispatch: {message}") |
| 537 | } |
| 538 | LlmError::Timeout(d) if d.is_zero() => write!( |
| 539 | f, |
| 540 | "Request timed out (provider request exceeded its transport budget; \ |
| 541 | exact duration not recorded)" |
| 542 | ), |
| 543 | LlmError::Timeout(d) => write!(f, "Request timed out after {d:?}"), |
| 544 | LlmError::AuthenticationError(auth) => { |
| 545 | write!(f, "Authentication failed: {}", auth.to_user_message()) |
| 546 | } |
| 547 | LlmError::AuthorizationError(msg) => write!(f, "Authorization failed: {msg}"), |
| 548 | LlmError::InvalidRequest { status, message } => { |
| 549 | write!(f, "Invalid request ({status}): {message}") |
| 550 | } |
| 551 | LlmError::ModelError(msg) => write!(f, "Model error: {msg}"), |
| 552 | LlmError::ContentPolicyError(msg) => write!(f, "Content policy violation: {msg}"), |
| 553 | LlmError::ParseError(msg) => write!(f, "Response parsing error: {msg}"), |
| 554 | LlmError::ContextLengthError(msg) => write!(f, "Context length exceeded: {msg}"), |
| 555 | LlmError::Other(msg) => write!(f, "LLM error: {msg}"), |
| 556 | } |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | impl std::error::Error for LlmError {} |
| 561 | |
| 562 | /// Added to a response-header timeout (#6889). A provider prefilling a large |
| 563 | /// or high-thinking request or loading a cold model can hold headers back |
| 564 | /// longer than this wait, and transport advice alone makes that read as a |
| 565 | /// broken connection. |
| 566 | const COLD_MODEL_HINT: &str = "The provider may still be prefilling a large or high-thinking \ |
| 567 | request or loading a cold model: wait a moment and send the message again, or allow a \ |
| 568 | longer wait with `codewhale config set stream.open_timeout_secs 300` (up to 600)."; |
| 569 | |
| 570 | impl LlmError { |
| 571 | pub(crate) fn header_timeout_message(&self) -> String { |
| 572 | let Self::HeaderTimeout { |
| 573 | waited, |
| 574 | http1, |
| 575 | retried, |
| 576 | } = self |
| 577 | else { |
| 578 | return String::new(); |
| 579 | }; |
| 580 | let protocol = if *http1 { " on HTTP/1.1" } else { "" }; |
| 581 | let retried = match retried { |
| 582 | 0 => String::new(), |
| 583 | 1 => " It was already retried once automatically and timed out again.".to_string(), |
| 584 | count => format!( |
| 585 | " It was already retried {count} times automatically and timed out each time." |
| 586 | ), |
| 587 | }; |
| 588 | format!( |
| 589 | "SSE stream request did not receive response headers after {}s{protocol}; request outcome unknown.{retried} {COLD_MODEL_HINT}", |
| 590 | waited.as_secs() |
| 591 | ) |
| 592 | } |
| 593 | |
| 594 | fn for_recovery_budget(self, remaining: Duration) -> Self { |
| 595 | if let Self::RateLimited { |
| 596 | message, |
| 597 | retry_after: Some(minimum), |
| 598 | } = self |
| 599 | { |
| 600 | if minimum >= remaining || minimum > codewhale_runtime::retry_status::MAX_PROVIDER_PAUSE |
| 601 | { |
| 602 | return Self::QuotaWindow { |
| 603 | message, |
| 604 | retry_after: Some(minimum), |
| 605 | transmission: RequestTransmission::Rejected, |
| 606 | }; |
| 607 | } |
| 608 | return Self::RateLimited { |
| 609 | message, |
| 610 | retry_after: Some(minimum), |
| 611 | }; |
| 612 | } |
| 613 | self |
| 614 | } |
| 615 | |
| 616 | pub fn transmission(&self) -> RequestTransmission { |
| 617 | match self { |
| 618 | Self::ConnectError { .. } => RequestTransmission::NotDispatched, |
| 619 | Self::QuotaWindow { transmission, .. } => *transmission, |
| 620 | Self::RateLimited { .. } |
| 621 | | Self::QuotaExhausted(_) |
| 622 | | Self::AuthenticationError(_) |
| 623 | | Self::AuthorizationError(_) |
| 624 | | Self::InvalidRequest { .. } |
| 625 | | Self::ModelError(_) |
| 626 | | Self::ContentPolicyError(_) |
| 627 | | Self::ContextLengthError(_) => RequestTransmission::Rejected, |
| 628 | _ => RequestTransmission::OutcomeUnknown, |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | pub fn is_retryable(&self) -> bool { |
| 633 | self.is_retryable_for(RetryOperation::Inference) |
| 634 | } |
| 635 | |
| 636 | pub fn is_retryable_for(&self, operation: RetryOperation) -> bool { |
| 637 | matches!( |
| 638 | self, |
| 639 | Self::RateLimited { .. } |
| 640 | | Self::ConnectError { |
| 641 | transient: true, |
| 642 | .. |
| 643 | } |
| 644 | ) || (operation == RetryOperation::ReadOnly |
| 645 | && matches!( |
| 646 | self, |
| 647 | Self::ServerError { .. } | Self::NetworkError(_) | Self::Timeout(_) |
| 648 | )) |
| 649 | } |
| 650 | |
| 651 | #[must_use] |
| 652 | pub fn into_non_retryable(self) -> Self { |
| 653 | match self { |
| 654 | Self::RateLimited { |
| 655 | message, |
| 656 | retry_after, |
| 657 | } => Self::QuotaWindow { |
| 658 | message, |
| 659 | retry_after, |
| 660 | transmission: RequestTransmission::Rejected, |
| 661 | }, |
| 662 | Self::ConnectError { |
| 663 | message, timed_out, .. |
| 664 | } => Self::ConnectError { |
| 665 | message, |
| 666 | transient: false, |
| 667 | timed_out, |
| 668 | }, |
| 669 | other => other, |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | /// Returns the server-suggested retry delay if available. |
| 674 | /// |
| 675 | /// This is typically present for rate limit errors when the server |
| 676 | /// provides a Retry-After header. |
| 677 | pub fn suggested_retry_delay(&self) -> Option<Duration> { |
| 678 | match self { |
| 679 | LlmError::RateLimited { retry_after, .. } |
| 680 | | LlmError::QuotaWindow { retry_after, .. } => *retry_after, |
| 681 | _ => None, |
| 682 | } |
| 683 | } |
| 684 | |
| 685 | /// Constructs an `LlmError` from HTTP status code and response body. |
| 686 | /// |
| 687 | /// Performs heuristic classification based on: |
| 688 | /// - Status code (429 = rate limit, 401/403 = auth, 499/5xx = transient upstream error) |
| 689 | /// - Response body keywords (`context_length`, `content_policy`, safety, etc.) |
| 690 | pub fn from_http_response(status: u16, body: &str) -> Self { |
| 691 | Self::from_http_response_with_retry_hints( |
| 692 | status, |
| 693 | body, |
| 694 | None, |
| 695 | retry_delay_from_error_body(body), |
| 696 | ) |
| 697 | } |
| 698 | |
| 699 | pub fn from_http_response_with_retry_hints( |
| 700 | status: u16, |
| 701 | body: &str, |
| 702 | retry_after: Option<Duration>, |
| 703 | body_retry_after: Option<Duration>, |
| 704 | ) -> Self { |
| 705 | if status == 525 { |
| 706 | return Self::ConnectError { |
| 707 | message: format!( |
| 708 | "HTTP 525: the gateway's TLS handshake with the provider origin failed before the request reached it: {body}" |
| 709 | ), |
| 710 | transient: true, |
| 711 | timed_out: false, |
| 712 | }; |
| 713 | } |
| 714 | if matches!(status, 400 | 499..=599) |
| 715 | && body |
| 716 | .to_ascii_lowercase() |
| 717 | .contains("request rate increased too quickly") |
| 718 | { |
| 719 | return Self::RateLimited { |
| 720 | message: body.to_string(), |
| 721 | retry_after: retry_after.max(body_retry_after), |
| 722 | }; |
| 723 | } |
| 724 | if (499..=599).contains(&status) { |
| 725 | return Self::ServerError { |
| 726 | status, |
| 727 | message: body.to_string(), |
| 728 | }; |
| 729 | } |
| 730 | if !matches!(status, 400 | 401 | 402 | 403 | 404 | 413 | 429) { |
| 731 | return Self::Other(format!("HTTP {status}: {body}")); |
| 732 | } |
| 733 | |
| 734 | if status == 413 { |
| 735 | return LlmError::InvalidRequest { |
| 736 | status, |
| 737 | message: body.to_string(), |
| 738 | }; |
| 739 | } |
| 740 | let quota_code = explicit_quota_code(body).or_else(|| explicit_quota_code_marker(body)); |
| 741 | if let Some(error) = quota_code |
| 742 | .as_deref() |
| 743 | .and_then(Self::from_subscription_sharing_error_code) |
| 744 | { |
| 745 | return error; |
| 746 | } |
| 747 | // xAI refuses an exhausted account with a 403, not a 402/429. |
| 748 | if matches!(status, 400 | 402 | 403 | 429) |
| 749 | && (quota_code.is_some() |
| 750 | || has_explicit_quota_phrase(body, status == 429 && body_retry_after.is_some())) |
| 751 | { |
| 752 | return LlmError::QuotaExhausted(QuotaExhaustionError::from_http_message( |
| 753 | body.to_string(), |
| 754 | )); |
| 755 | } |
| 756 | |
| 757 | match status { |
| 758 | 429 => LlmError::RateLimited { |
| 759 | message: body.to_string(), |
| 760 | retry_after: retry_after.max(body_retry_after), |
| 761 | }, |
| 762 | 401 => Self::authentication_error(body), |
| 763 | 403 => { |
| 764 | if looks_like_authentication_failure(body) { |
| 765 | Self::authentication_error(body) |
| 766 | } else { |
| 767 | LlmError::AuthorizationError(body.to_string()) |
| 768 | } |
| 769 | } |
| 770 | 400 => { |
| 771 | // Classify 400 errors by examining the response body |
| 772 | let body_lower = body.to_lowercase(); |
| 773 | // An "unsupported parameter" 400 names the offending field |
| 774 | // (often `max_output_tokens` or another *token* field), which |
| 775 | // the generic keyword rules below would misread as a context |
| 776 | // window overflow. Parameter shape errors are invalid |
| 777 | // requests, not prompt-size errors, so they get their own |
| 778 | // branch ahead of the heuristic. |
| 779 | if body_lower.contains("unsupported parameter") |
| 780 | || body_lower.contains("invalid_request_error") |
| 781 | && body_lower.contains("parameter") |
| 782 | { |
| 783 | LlmError::InvalidRequest { |
| 784 | status, |
| 785 | message: body.to_string(), |
| 786 | } |
| 787 | } else if is_context_length_message(&body_lower) { |
| 788 | LlmError::ContextLengthError(body.to_string()) |
| 789 | } else if body_lower.contains("content_policy") |
| 790 | || body_lower.contains("safety") |
| 791 | || body_lower.contains("harmful") |
| 792 | || body_lower.contains("inappropriate") |
| 793 | { |
| 794 | LlmError::ContentPolicyError(body.to_string()) |
| 795 | } else if body_lower.contains("model") && body_lower.contains("not found") { |
| 796 | LlmError::ModelError(body.to_string()) |
| 797 | } else { |
| 798 | LlmError::InvalidRequest { |
| 799 | status, |
| 800 | message: body.to_string(), |
| 801 | } |
| 802 | } |
| 803 | } |
| 804 | 404 => { |
| 805 | if body.to_lowercase().contains("model") { |
| 806 | LlmError::ModelError(body.to_string()) |
| 807 | } else { |
| 808 | LlmError::InvalidRequest { |
| 809 | status, |
| 810 | message: body.to_string(), |
| 811 | } |
| 812 | } |
| 813 | } |
| 814 | _ => LlmError::Other(format!("HTTP {status}: {body}")), |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | /// Official structured ChatGPT plan errors are terminal account states. |
| 819 | /// Plain text containing quota words is never enough to mint this type. |
| 820 | #[must_use] |
| 821 | pub fn from_subscription_sharing_error_code(code: &str) -> Option<Self> { |
| 822 | let message = match code { |
| 823 | "subscription_sharing_usage_limit_exceeded" => { |
| 824 | "ChatGPT plan usage limit reached. Check ChatGPT Settings > Usage for your remaining allowance and reset time." |
| 825 | } |
| 826 | "subscription_sharing_usage_unavailable" => { |
| 827 | "ChatGPT plan usage is unavailable. Check ChatGPT Settings > Usage and reconnect if needed." |
| 828 | } |
| 829 | _ => return None, |
| 830 | }; |
| 831 | Some(Self::QuotaExhausted( |
| 832 | QuotaExhaustionError::from_http_message(message.to_string()), |
| 833 | )) |
| 834 | } |
| 835 | |
| 836 | #[must_use] |
| 837 | pub fn from_linked_organization_billing_stop(status: u16, body: &str) -> Option<Self> { |
| 838 | let stopped = status == 402 |
| 839 | && (body.contains("linked_organization_spend_limit_reached") |
| 840 | || body.contains("linked_organization_billing_unavailable")); |
| 841 | stopped.then(|| { |
| 842 | Self::QuotaExhausted(QuotaExhaustionError::from_http_message( |
| 843 | "Your Claude organization's spend cap or credit stopped this request. Check Linked platforms and Billing in the Claude Console.".to_string(), |
| 844 | )) |
| 845 | }) |
| 846 | } |
| 847 | |
| 848 | #[must_use] |
| 849 | pub fn authentication_error(message: impl Into<String>) -> Self { |
| 850 | LlmError::AuthenticationError(AuthenticationErrorDetail::new(message)) |
| 851 | } |
| 852 | |
| 853 | #[must_use] |
| 854 | pub fn authentication_error_with_context( |
| 855 | message: impl Into<String>, |
| 856 | context: Option<AuthenticationErrorContext>, |
| 857 | ) -> Self { |
| 858 | LlmError::AuthenticationError(AuthenticationErrorDetail::with_context(message, context)) |
| 859 | } |
| 860 | |
| 861 | /// Constructs an `LlmError` from HTTP response data plus request context |
| 862 | /// that is safe to display when authentication fails. |
| 863 | #[must_use] |
| 864 | #[cfg(any(test, feature = "test-support"))] |
| 865 | pub fn from_http_response_with_request_context( |
| 866 | status: u16, |
| 867 | body: &str, |
| 868 | provider: Option<&str>, |
| 869 | base_url: Option<&str>, |
| 870 | model: Option<&str>, |
| 871 | key_source: Option<&str>, |
| 872 | api_key: Option<&str>, |
| 873 | ) -> Self { |
| 874 | let body = redact_api_key_from_message(body, api_key); |
| 875 | let context = |
| 876 | AuthenticationErrorContext::from_parts(provider, base_url, model, key_source, api_key); |
| 877 | Self::from_http_response_with_auth_context(status, &body, Some(context)) |
| 878 | } |
| 879 | |
| 880 | /// Constructs an `LlmError` from HTTP status code and response body, with |
| 881 | /// optional structured details for authentication failures. |
| 882 | /// |
| 883 | /// The `body` passed here must already be safe for user display. Prefer |
| 884 | /// `Self::from_http_response_with_request_context` when the raw API key is |
| 885 | /// available so the response body can be redacted before rendering. |
| 886 | #[must_use] |
| 887 | pub fn from_http_response_with_auth_context( |
| 888 | status: u16, |
| 889 | body: &str, |
| 890 | auth_context: Option<AuthenticationErrorContext>, |
| 891 | ) -> Self { |
| 892 | let classified = Self::from_http_response(status, body); |
| 893 | if matches!(classified, Self::QuotaExhausted(_)) { |
| 894 | return classified; |
| 895 | } |
| 896 | match status { |
| 897 | 401 => Self::authentication_error_with_context(body, auth_context), |
| 898 | 403 => { |
| 899 | if looks_like_authentication_failure(body) { |
| 900 | Self::authentication_error_with_context(body, auth_context) |
| 901 | } else { |
| 902 | LlmError::AuthorizationError(body.to_string()) |
| 903 | } |
| 904 | } |
| 905 | _ => classified, |
| 906 | } |
| 907 | } |
| 908 | |
| 909 | /// Constructs an `LlmError` from a reqwest error. |
| 910 | /// |
| 911 | /// `Timeout` carries `Duration::ZERO` when the spent budget cannot be |
| 912 | /// recovered: reqwest errors do not expose elapsed time, and the caller |
| 913 | /// may have pinned the per-attempt total at a distance. Display renders |
| 914 | /// the zero case as "duration unknown" instead of a misleading "0ns"; |
| 915 | /// call sites that can measure should overwrite it with the real elapsed |
| 916 | /// time (see the retry loops in `client.rs`). |
| 917 | pub fn from_reqwest(err: &reqwest::Error) -> Self { |
| 918 | if err.is_connect() { |
| 919 | LlmError::ConnectError { |
| 920 | message: err.to_string(), |
| 921 | transient: !has_tls_cause(err), |
| 922 | timed_out: err.is_timeout(), |
| 923 | } |
| 924 | } else if err.is_timeout() { |
| 925 | LlmError::Timeout(Duration::from_secs(0)) |
| 926 | } else if err.is_request() || err.is_body() || err.is_decode() { |
| 927 | LlmError::NetworkError(format!("Request failed: {err}")) |
| 928 | } else { |
| 929 | LlmError::Other(err.to_string()) |
| 930 | } |
| 931 | } |
| 932 | |
| 933 | /// [`Self::from_reqwest`] with the attempt's measured elapsed time: reqwest |
| 934 | /// errors do not carry the spent budget, so call sites that can measure |
| 935 | /// overwrite the unknown-duration sentinel with the real elapsed time |
| 936 | /// (the retry loops in `client.rs`). |
| 937 | pub(crate) fn from_reqwest_measured(err: &reqwest::Error, started: std::time::Instant) -> Self { |
| 938 | match Self::from_reqwest(err) { |
| 939 | Self::Timeout(_) => Self::Timeout(started.elapsed()), |
| 940 | mapped => mapped, |
| 941 | } |
| 942 | } |
| 943 | } |
| 944 | |
| 945 | pub(crate) fn has_tls_cause(mut error: &(dyn std::error::Error + 'static)) -> bool { |
| 946 | loop { |
| 947 | if error.is::<rustls::Error>() { |
| 948 | return true; |
| 949 | } |
| 950 | if let Some(inner) = error |
| 951 | .downcast_ref::<std::io::Error>() |
| 952 | .and_then(std::io::Error::get_ref) |
| 953 | { |
| 954 | error = inner; |
| 955 | } else if let Some(source) = error.source() { |
| 956 | error = source; |
| 957 | } else { |
| 958 | return false; |
| 959 | } |
| 960 | } |
| 961 | } |
| 962 | |
| 963 | /// Format provider HTTP error bodies before they are surfaced in the TUI. |
| 964 | /// |
| 965 | /// Providers sometimes return whole HTML error pages for gateway/WAF blocks. |
| 966 | /// Passing those pages through raw floods the transcript and can also make a |
| 967 | /// provider-side 403 look like a broken API key. Keep the useful details and |
| 968 | /// cap everything else. |
| 969 | #[must_use] |
| 970 | pub fn sanitize_http_error_body(provider_label: Option<&str>, status: u16, body: &str) -> String { |
| 971 | let json_message = extract_json_error_message(body); |
| 972 | let message = json_message.as_deref().unwrap_or(body); |
| 973 | // Gate on Google's actual rejection, not the selected provider or model: |
| 974 | // compatible gateways may manage signatures themselves (#6048). This |
| 975 | // shared boundary covers both streaming and non-streaming HTTP failures. |
| 976 | const SIGNATURE_HINT: &str = "Gemini rejected tool-call replay because a thought signature is missing. \ |
| 977 | Use the built-in `google` provider with its default endpoint, or a gateway that preserves \ |
| 978 | Google thought signatures, then start a new session before using tools. \ |
| 979 | Changing reasoning settings will not restore missing signatures."; |
| 980 | if status == 400 |
| 981 | && !is_probably_html(message) |
| 982 | && explicit_quota_code(body).is_none() |
| 983 | && !message.contains(SIGNATURE_HINT) |
| 984 | { |
| 985 | let lower = collapse_whitespace(message).to_ascii_lowercase(); |
| 986 | if lower.contains("missing a thought_signature") |
| 987 | || lower.contains("missing thought_signature") |
| 988 | || lower.contains("thought_signature is missing") |
| 989 | { |
| 990 | let detail = truncate_for_error(&collapse_whitespace(message), 900); |
| 991 | return format!("{SIGNATURE_HINT} Provider error: {detail}"); |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | if let Some(message) = json_message { |
| 996 | let message = truncate_for_error(&collapse_whitespace(&message), 2_000); |
| 997 | if let Some(code) = explicit_quota_code(body) { |
| 998 | return format!("{message} (provider error code: {code})"); |
| 999 | } |
| 1000 | return message; |
| 1001 | } |
| 1002 | |
| 1003 | if is_probably_html(body) { |
| 1004 | let text = html_to_text(body); |
| 1005 | let lower = text.to_ascii_lowercase(); |
| 1006 | let provider = provider_label.unwrap_or("Provider"); |
| 1007 | |
| 1008 | // Cloudflare's "Access Denied" interstitial strips the literal word |
| 1009 | // "cloudflare" once tags are removed (it only survives in `<meta>` |
| 1010 | // attributes and the `<style>`/`<script>` blocks we discard). Arcee's |
| 1011 | // 403 page is exactly this shape, so also key off the WAF's stock copy |
| 1012 | // ("security alert", "contact support") and a Cloudflare error/ray ID. |
| 1013 | let error_id = extract_cloudflare_error_id(&text); |
| 1014 | let is_cloudflare = lower.contains("cloudflare"); |
| 1015 | let looks_like_access_denied = lower.contains("access denied") |
| 1016 | && (is_cloudflare |
| 1017 | || lower.contains("security alert") |
| 1018 | || lower.contains("contact support") |
| 1019 | || lower.contains("contact us") |
| 1020 | || error_id.is_some()); |
| 1021 | if looks_like_access_denied { |
| 1022 | let label = if is_cloudflare { |
| 1023 | "Cloudflare Access Denied" |
| 1024 | } else { |
| 1025 | "Access Denied" |
| 1026 | }; |
| 1027 | let mut message = format!( |
| 1028 | "{provider} API returned {label} (HTTP {status}). \ |
| 1029 | The request was blocked before it reached the model; retry with a \ |
| 1030 | smaller request or fewer tools, or contact provider support" |
| 1031 | ); |
| 1032 | if let Some(id) = error_id { |
| 1033 | message.push_str(&format!(" with ID {id}")); |
| 1034 | } |
| 1035 | message.push('.'); |
| 1036 | return message; |
| 1037 | } |
| 1038 | |
| 1039 | let text = truncate_for_error(&collapse_whitespace(&text), 900); |
| 1040 | return format!("{provider} API returned an HTML error page (HTTP {status}): {text}"); |
| 1041 | } |
| 1042 | |
| 1043 | truncate_for_error(&collapse_whitespace(body), 2_000) |
| 1044 | } |
| 1045 | |
| 1046 | fn looks_like_authentication_failure(body: &str) -> bool { |
| 1047 | let lower = body.to_ascii_lowercase(); |
| 1048 | lower.contains("authentication") |
| 1049 | || lower.contains("unauthorized") |
| 1050 | || lower.contains("api key") |
| 1051 | || lower.contains("invalid key") |
| 1052 | || lower.contains("invalid token") |
| 1053 | || lower.contains("bearer token") |
| 1054 | || lower.contains("missing token") |
| 1055 | } |
| 1056 | |
| 1057 | /// A provider error is a context overflow only when it says so. Bare |
| 1058 | /// "token", "too long" or "maximum" also appear in ordinary invalid-request |
| 1059 | /// errors (`max_tokens must be ...`, a field value too long), which compaction |
| 1060 | /// or a bigger window cannot fix. This is the one phrase list: the typed 400 |
| 1061 | /// classification here and the engine's string classifier both read it. |
| 1062 | /// `lower` must already be lowercase. |
| 1063 | pub fn is_context_length_message(lower: &str) -> bool { |
| 1064 | [ |
| 1065 | "context_length", |
| 1066 | "context length", |
| 1067 | "context window", |
| 1068 | "context limit", |
| 1069 | "maximum context", |
| 1070 | "prompt is too long", |
| 1071 | "input is too long", |
| 1072 | "maximum prompt length", |
| 1073 | "exceeded model token limit", |
| 1074 | "tokens exceed", |
| 1075 | "exceeds the maximum number of tokens", |
| 1076 | // llama.cpp: "the request exceeds the available context size". |
| 1077 | "available context size", |
| 1078 | ] |
| 1079 | .iter() |
| 1080 | .any(|phrase| lower.contains(phrase)) |
| 1081 | } |
| 1082 | |
| 1083 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1084 | pub struct ImageCountRejection { |
| 1085 | pub limit: Option<usize>, |
| 1086 | } |
| 1087 | |
| 1088 | pub fn image_count_rejection(lower: &str) -> Option<ImageCountRejection> { |
| 1089 | if is_context_length_message(lower) { |
| 1090 | return None; |
| 1091 | } |
| 1092 | let phrase = [ |
| 1093 | "too many images", |
| 1094 | "maximum number of images", |
| 1095 | "max number of images", |
| 1096 | "max images", |
| 1097 | "maximum images", |
| 1098 | "images per request", |
| 1099 | "images per prompt", |
| 1100 | "images per message", |
| 1101 | "image(s) may be provided", |
| 1102 | "images may be provided", |
| 1103 | "images can be provided", |
| 1104 | ] |
| 1105 | .iter() |
| 1106 | .find_map(|phrase| lower.find(*phrase)); |
| 1107 | let number_of_images = lower.find("number of images").filter(|_| { |
| 1108 | ["exceed", "more than", "at most", "limit"] |
| 1109 | .iter() |
| 1110 | .any(|word| lower.contains(*word)) |
| 1111 | }); |
| 1112 | let bounded_images = ["at most ", "maximum of ", "max of ", "up to "] |
| 1113 | .iter() |
| 1114 | .find_map(|marker| { |
| 1115 | lower.match_indices(*marker).find_map(|(index, marker)| { |
| 1116 | let rest = &lower[index + marker.len()..]; |
| 1117 | let digits = |
| 1118 | rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len(); |
| 1119 | (digits > 0 && rest[digits..].trim_start().starts_with("image")).then_some(index) |
| 1120 | }) |
| 1121 | }); |
| 1122 | let start = phrase.or(number_of_images).or(bounded_images)?; |
| 1123 | let clause_start = lower[..start] |
| 1124 | .rfind(['.', '\n', '{', '"', ';']) |
| 1125 | .map_or(0, |index| index + 1); |
| 1126 | let clause_end = lower[start..] |
| 1127 | .find(['\n', '}', '"', ';']) |
| 1128 | .map_or(lower.len(), |index| start + index); |
| 1129 | let clause = &lower[clause_start..clause_end]; |
| 1130 | let sentence = &lower[clause_start |
| 1131 | ..lower[start..clause_end] |
| 1132 | .find('.') |
| 1133 | .map_or(clause_end, |index| start + index)]; |
| 1134 | let read = |text: &str, marker: &str| { |
| 1135 | text.match_indices(marker).find_map(|(index, marker)| { |
| 1136 | let rest = text[index + marker.len()..].trim_start(); |
| 1137 | let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len(); |
| 1138 | let unit = ["mb", "kb", "gb", "px", "pixel", "token", "byte", "%", ">"] |
| 1139 | .iter() |
| 1140 | .any(|unit| rest[digits..].trim_start().starts_with(unit)); |
| 1141 | if digits == 0 || unit { |
| 1142 | return None; |
| 1143 | } |
| 1144 | rest[..digits].parse::<usize>().ok() |
| 1145 | }) |
| 1146 | }; |
| 1147 | let limit = [ |
| 1148 | "at most ", |
| 1149 | "maximum of ", |
| 1150 | "max of ", |
| 1151 | "max is ", |
| 1152 | "maximum is ", |
| 1153 | "limit is ", |
| 1154 | "limit of ", |
| 1155 | "up to ", |
| 1156 | "allowed: ", |
| 1157 | "allowed ", |
| 1158 | "maximum: ", |
| 1159 | "max: ", |
| 1160 | "max ", |
| 1161 | "maximum ", |
| 1162 | ] |
| 1163 | .iter() |
| 1164 | .find_map(|marker| read(clause, marker)) |
| 1165 | .or_else(|| { |
| 1166 | [": ", " is "] |
| 1167 | .iter() |
| 1168 | .find_map(|marker| read(sentence, marker)) |
| 1169 | }); |
| 1170 | Some(ImageCountRejection { limit }) |
| 1171 | } |
| 1172 | |
| 1173 | pub(super) fn unwrap_single_element_json_array(value: &Value) -> &Value { |
| 1174 | value |
| 1175 | .as_array() |
| 1176 | .filter(|items| items.len() == 1) |
| 1177 | .map_or(value, |items| &items[0]) |
| 1178 | } |
| 1179 | |
| 1180 | fn explicit_quota_code(body: &str) -> Option<String> { |
| 1181 | let parsed: Value = serde_json::from_str(body).ok()?; |
| 1182 | let value = unwrap_single_element_json_array(&parsed); |
| 1183 | [ |
| 1184 | "/error/code", |
| 1185 | "/error/type", |
| 1186 | "/error/error_code", |
| 1187 | "/code", |
| 1188 | "/type", |
| 1189 | "/error_code", |
| 1190 | ] |
| 1191 | .into_iter() |
| 1192 | .filter_map(|pointer| value.pointer(pointer).and_then(Value::as_str)) |
| 1193 | .find(|code| is_explicit_quota_code(code)) |
| 1194 | .map(ToOwned::to_owned) |
| 1195 | } |
| 1196 | |
| 1197 | fn is_explicit_quota_code(code: &str) -> bool { |
| 1198 | let normalized: String = code |
| 1199 | .chars() |
| 1200 | .filter(|ch| ch.is_ascii_alphanumeric()) |
| 1201 | .map(|ch| ch.to_ascii_lowercase()) |
| 1202 | .collect(); |
| 1203 | matches!( |
| 1204 | normalized.as_str(), |
| 1205 | "insufficientquota" |
| 1206 | | "quotaexceeded" |
| 1207 | | "quotaexhausted" |
| 1208 | | "billinghardlimitreached" |
| 1209 | | "billinglimitreached" |
| 1210 | | "creditbalanceexhausted" |
| 1211 | // ChatGPT/Codex subscription window (HTTP 429, `error.type`), |
| 1212 | // as openai/codex `api_bridge.rs` maps it. It resets on the |
| 1213 | // plan's schedule, not after a short backoff. |
| 1214 | | "usagelimitreached" |
| 1215 | // Same backend, same branch: the signed-in plan does not include |
| 1216 | // Codex. Retrying cannot help; switching accounts can. |
| 1217 | | "usagenotincluded" |
| 1218 | | "subscriptionsharingusagelimitexceeded" |
| 1219 | | "subscriptionsharingusageunavailable" |
| 1220 | ) |
| 1221 | } |
| 1222 | |
| 1223 | fn explicit_quota_code_marker(body: &str) -> Option<String> { |
| 1224 | let lower = body.to_ascii_lowercase(); |
| 1225 | let (_, suffix) = lower.split_once("provider error code:")?; |
| 1226 | let code = suffix |
| 1227 | .trim_start() |
| 1228 | .split(|ch: char| !(ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-'))) |
| 1229 | .next() |
| 1230 | .unwrap_or_default(); |
| 1231 | is_explicit_quota_code(code).then(|| code.to_string()) |
| 1232 | } |
| 1233 | |
| 1234 | fn has_explicit_quota_phrase(body: &str, bounded_rate_limit_hint: bool) -> bool { |
| 1235 | let lower = body.to_ascii_lowercase(); |
| 1236 | let current_quota_exhausted = lower.contains("exceeded your current quota") |
| 1237 | || lower.contains("current quota has been exceeded"); |
| 1238 | let plan_and_billing_guidance = lower.contains("plan") && lower.contains("billing"); |
| 1239 | let durable_scope_exhausted = [ |
| 1240 | "billing quota exceeded", |
| 1241 | "billing quota exhausted", |
| 1242 | "billing quota is exhausted", |
| 1243 | "billing quota has been exceeded", |
| 1244 | "billing quota has been exhausted", |
| 1245 | "account quota exceeded", |
| 1246 | "account quota exhausted", |
| 1247 | "account quota is exhausted", |
| 1248 | "account quota has been exceeded", |
| 1249 | "account quota has been exhausted", |
| 1250 | "plan quota exceeded", |
| 1251 | "plan quota exhausted", |
| 1252 | "plan quota is exhausted", |
| 1253 | "plan quota has been exceeded", |
| 1254 | "plan quota has been exhausted", |
| 1255 | ] |
| 1256 | .into_iter() |
| 1257 | .any(|phrase| lower.contains(phrase)); |
| 1258 | |
| 1259 | // xAI: "You have run out of credits or need a Grok subscription." |
| 1260 | let credits_exhausted = [ |
| 1261 | "run out of credits", |
| 1262 | "out of credits", |
| 1263 | "insufficient credits", |
| 1264 | "used all available credits", |
| 1265 | "monthly spending limit", |
| 1266 | ] |
| 1267 | .into_iter() |
| 1268 | .any(|phrase| lower.contains(phrase)); |
| 1269 | |
| 1270 | let plan_window_exhausted = lower.contains("usage limit") |
| 1271 | && ["reached", "exceeded", "exhausted"] |
| 1272 | .iter() |
| 1273 | .any(|word| lower.contains(word)) |
| 1274 | && (["weekly", "5-hour", "five-hour", "5 hour", "five hour"] |
| 1275 | .iter() |
| 1276 | .any(|scope| lower.contains(scope)) |
| 1277 | || (lower.contains("plan") && lower.contains("limit resets"))); |
| 1278 | |
| 1279 | credits_exhausted |
| 1280 | || plan_window_exhausted |
| 1281 | || lower.contains("billing hard limit has been reached") |
| 1282 | || lower.contains("credit balance exhausted") |
| 1283 | || lower.contains("credit balance is exhausted") |
| 1284 | || durable_scope_exhausted |
| 1285 | || (current_quota_exhausted && plan_and_billing_guidance && !bounded_rate_limit_hint) |
| 1286 | } |
| 1287 | |
| 1288 | fn extract_json_error_message(body: &str) -> Option<String> { |
| 1289 | let parsed: Value = serde_json::from_str(body).ok()?; |
| 1290 | let value = unwrap_single_element_json_array(&parsed); |
| 1291 | if let (Some(class), Some(detail)) = ( |
| 1292 | value.pointer("/error").and_then(Value::as_str), |
| 1293 | value.pointer("/message").and_then(Value::as_str), |
| 1294 | ) && !class.trim().is_empty() |
| 1295 | && !detail.trim().is_empty() |
| 1296 | && !class.trim().eq_ignore_ascii_case(detail.trim()) |
| 1297 | { |
| 1298 | return Some(format!("{}: {}", class.trim(), detail.trim())); |
| 1299 | } |
| 1300 | for pointer in [ |
| 1301 | "/error/message", |
| 1302 | "/error", |
| 1303 | "/message", |
| 1304 | "/detail", |
| 1305 | "/error_description", |
| 1306 | ] { |
| 1307 | let Some(value) = value.pointer(pointer) else { |
| 1308 | continue; |
| 1309 | }; |
| 1310 | if let Some(message) = value.as_str() { |
| 1311 | if !message.trim().is_empty() { |
| 1312 | return Some(message.to_string()); |
| 1313 | } |
| 1314 | } else if value.is_object() || value.is_array() { |
| 1315 | return Some(value.to_string()); |
| 1316 | } |
| 1317 | } |
| 1318 | None |
| 1319 | } |
| 1320 | |
| 1321 | fn is_probably_html(body: &str) -> bool { |
| 1322 | let prefix = body |
| 1323 | .chars() |
| 1324 | .take(512) |
| 1325 | .collect::<String>() |
| 1326 | .to_ascii_lowercase(); |
| 1327 | prefix.contains("<!doctype html") || prefix.contains("<html") || prefix.contains("<head") |
| 1328 | } |
| 1329 | |
| 1330 | fn html_to_text(html: &str) -> String { |
| 1331 | let without_scripts = strip_html_block(html, "script"); |
| 1332 | let without_styles = strip_html_block(&without_scripts, "style"); |
| 1333 | let mut text = String::with_capacity(without_styles.len().min(4096)); |
| 1334 | let mut in_tag = false; |
| 1335 | for ch in without_styles.chars() { |
| 1336 | match ch { |
| 1337 | '<' => { |
| 1338 | in_tag = true; |
| 1339 | text.push(' '); |
| 1340 | } |
| 1341 | '>' => { |
| 1342 | in_tag = false; |
| 1343 | text.push(' '); |
| 1344 | } |
| 1345 | _ if !in_tag => text.push(ch), |
| 1346 | _ => {} |
| 1347 | } |
| 1348 | } |
| 1349 | decode_basic_html_entities(&collapse_whitespace(&text)) |
| 1350 | } |
| 1351 | |
| 1352 | fn strip_html_block(input: &str, tag: &str) -> String { |
| 1353 | let mut out = String::with_capacity(input.len()); |
| 1354 | let mut cursor = 0usize; |
| 1355 | let lower = input.to_ascii_lowercase(); |
| 1356 | let start_marker = format!("<{tag}"); |
| 1357 | let end_marker = format!("</{tag}>"); |
| 1358 | |
| 1359 | while let Some(relative_start) = lower[cursor..].find(&start_marker) { |
| 1360 | let start = cursor + relative_start; |
| 1361 | out.push_str(&input[cursor..start]); |
| 1362 | let after_start = start + start_marker.len(); |
| 1363 | let Some(relative_end) = lower[after_start..].find(&end_marker) else { |
| 1364 | cursor = input.len(); |
| 1365 | break; |
| 1366 | }; |
| 1367 | cursor = after_start + relative_end + end_marker.len(); |
| 1368 | out.push(' '); |
| 1369 | } |
| 1370 | out.push_str(&input[cursor..]); |
| 1371 | out |
| 1372 | } |
| 1373 | |
| 1374 | fn decode_basic_html_entities(input: &str) -> String { |
| 1375 | input |
| 1376 | .replace(" ", " ") |
| 1377 | .replace("&", "&") |
| 1378 | .replace("<", "<") |
| 1379 | .replace(">", ">") |
| 1380 | .replace(""", "\"") |
| 1381 | .replace("'", "'") |
| 1382 | .replace("'", "'") |
| 1383 | } |
| 1384 | |
| 1385 | fn collapse_whitespace(input: &str) -> String { |
| 1386 | input.split_whitespace().collect::<Vec<_>>().join(" ") |
| 1387 | } |
| 1388 | |
| 1389 | fn truncate_for_error(input: &str, max_chars: usize) -> String { |
| 1390 | let mut out = String::with_capacity(input.len().min(max_chars + 32)); |
| 1391 | for (count, ch) in input.chars().enumerate() { |
| 1392 | if count >= max_chars { |
| 1393 | out.push_str("..."); |
| 1394 | return out; |
| 1395 | } |
| 1396 | out.push(ch); |
| 1397 | } |
| 1398 | out |
| 1399 | } |
| 1400 | |
| 1401 | fn extract_cloudflare_error_id(text: &str) -> Option<String> { |
| 1402 | let mut last = None; |
| 1403 | for token in text.split(|ch: char| !ch.is_ascii_hexdigit()) { |
| 1404 | if (16..=64).contains(&token.len()) && token.bytes().any(|b| b.is_ascii_alphabetic()) { |
| 1405 | last = Some(token.to_string()); |
| 1406 | } |
| 1407 | } |
| 1408 | last |
| 1409 | } |
| 1410 | |
| 1411 | impl From<reqwest::Error> for LlmError { |
| 1412 | fn from(err: reqwest::Error) -> Self { |
| 1413 | LlmError::from_reqwest(&err) |
| 1414 | } |
| 1415 | } |
| 1416 | |
| 1417 | impl From<serde_json::Error> for LlmError { |
| 1418 | fn from(err: serde_json::Error) -> Self { |
| 1419 | LlmError::ParseError(err.to_string()) |
| 1420 | } |
| 1421 | } |
| 1422 | |
| 1423 | // === RetryConfig - Exponential Backoff Configuration === |
| 1424 | |
| 1425 | /// Configuration for retry behavior with exponential backoff. |
| 1426 | /// |
| 1427 | /// This struct controls how retries are performed: |
| 1428 | /// - Number of retry attempts |
| 1429 | /// - Delay calculation (exponential backoff with optional jitter) |
| 1430 | /// - Which HTTP status codes are retryable |
| 1431 | /// - Timeout handling |
| 1432 | /// |
| 1433 | /// # Default Values |
| 1434 | /// |
| 1435 | /// - `enabled`: true |
| 1436 | /// - `max_retries`: 3 |
| 1437 | /// - `initial_delay`: 1.0 seconds |
| 1438 | /// - `max_delay`: 60.0 seconds |
| 1439 | /// - `exponential_base`: 2.0 |
| 1440 | /// - `jitter`: true (adds randomness to prevent thundering herd) |
| 1441 | /// - `jitter_factor`: 0.1 (10% variation) |
| 1442 | /// - `retryable_status_codes`: [429, 499, 500, 502, 503, 504] |
| 1443 | #[derive(Debug, Clone)] |
| 1444 | pub struct RetryConfig { |
| 1445 | pub rate_limit: RateLimitRetryPolicy, |
| 1446 | pub operation: RetryOperation, |
| 1447 | /// Whether retry logic is enabled |
| 1448 | pub enabled: bool, |
| 1449 | |
| 1450 | /// Maximum number of retry attempts (0 = no retries, 3 = up to 4 total attempts) |
| 1451 | pub max_retries: u32, |
| 1452 | |
| 1453 | /// Initial delay before first retry (seconds) |
| 1454 | pub initial_delay: f64, |
| 1455 | |
| 1456 | /// Maximum delay between retries (seconds) |
| 1457 | pub max_delay: f64, |
| 1458 | |
| 1459 | /// Base for exponential backoff (delay = initial * base^attempt) |
| 1460 | pub exponential_base: f64, |
| 1461 | |
| 1462 | /// Whether to add random jitter to delays |
| 1463 | pub jitter: bool, |
| 1464 | |
| 1465 | /// Jitter factor (0.1 = +/- 10% variation) |
| 1466 | pub jitter_factor: f64, |
| 1467 | |
| 1468 | /// Whether to respect server's Retry-After header |
| 1469 | pub respect_retry_after: bool, |
| 1470 | |
| 1471 | /// HTTP status codes that should trigger a retry |
| 1472 | pub retryable_status_codes: Vec<u16>, |
| 1473 | |
| 1474 | /// Timeout for individual requests (seconds, 0 = no timeout) |
| 1475 | pub request_timeout: f64, |
| 1476 | |
| 1477 | /// Total timeout for all retry attempts (seconds, 0 = no total timeout) |
| 1478 | pub total_timeout: f64, |
| 1479 | } |
| 1480 | |
| 1481 | impl Default for RetryConfig { |
| 1482 | fn default() -> Self { |
| 1483 | Self { |
| 1484 | rate_limit: RateLimitRetryPolicy::default(), |
| 1485 | operation: RetryOperation::Inference, |
| 1486 | enabled: true, |
| 1487 | max_retries: 3, |
| 1488 | initial_delay: 1.0, |
| 1489 | max_delay: 60.0, |
| 1490 | exponential_base: 2.0, |
| 1491 | jitter: true, |
| 1492 | jitter_factor: 0.1, |
| 1493 | respect_retry_after: true, |
| 1494 | retryable_status_codes: vec![429, 499, 500, 502, 503, 504], |
| 1495 | request_timeout: 120.0, |
| 1496 | total_timeout: 0.0, // No total timeout by default |
| 1497 | } |
| 1498 | } |
| 1499 | } |
| 1500 | |
| 1501 | impl RetryConfig { |
| 1502 | /// Creates a new `RetryConfig` with default values |
| 1503 | pub fn new() -> Self { |
| 1504 | Self::default() |
| 1505 | } |
| 1506 | |
| 1507 | /// Creates a config with retry disabled |
| 1508 | pub fn disabled() -> Self { |
| 1509 | Self { |
| 1510 | enabled: false, |
| 1511 | ..Default::default() |
| 1512 | } |
| 1513 | } |
| 1514 | |
| 1515 | /// Builder method to set max retries |
| 1516 | pub fn with_max_retries(mut self, max_retries: u32) -> Self { |
| 1517 | self.max_retries = max_retries; |
| 1518 | self |
| 1519 | } |
| 1520 | |
| 1521 | /// Builder method to set initial delay |
| 1522 | pub fn with_initial_delay(mut self, delay: f64) -> Self { |
| 1523 | self.initial_delay = delay; |
| 1524 | self |
| 1525 | } |
| 1526 | |
| 1527 | /// Builder method to set max delay |
| 1528 | pub fn with_max_delay(mut self, delay: f64) -> Self { |
| 1529 | self.max_delay = delay; |
| 1530 | self |
| 1531 | } |
| 1532 | |
| 1533 | /// Builder method to enable/disable jitter |
| 1534 | pub fn with_jitter(mut self, enabled: bool) -> Self { |
| 1535 | self.jitter = enabled; |
| 1536 | self |
| 1537 | } |
| 1538 | |
| 1539 | /// Calculates the delay for a given retry attempt. |
| 1540 | /// |
| 1541 | /// Uses exponential backoff: delay = `initial_delay` * `exponential_base^attempt` |
| 1542 | /// The result is capped at `max_delay` and optionally has jitter applied. |
| 1543 | /// |
| 1544 | /// # Arguments |
| 1545 | /// |
| 1546 | /// * `attempt` - Zero-based attempt number (0 = first retry) |
| 1547 | /// |
| 1548 | /// # Returns |
| 1549 | /// |
| 1550 | /// Duration to wait before the next retry attempt |
| 1551 | pub fn delay_for_attempt(&self, attempt: u32) -> Duration { |
| 1552 | let exponent = i32::try_from(attempt).unwrap_or(i32::MAX); |
| 1553 | let base_delay = self.initial_delay * self.exponential_base.powi(exponent); |
| 1554 | let capped_delay = base_delay.min(self.max_delay); |
| 1555 | |
| 1556 | let final_delay = if self.jitter { |
| 1557 | // Add random jitter to prevent thundering herd problem |
| 1558 | let jitter_range = capped_delay * self.jitter_factor; |
| 1559 | // Use UUID v4 entropy for jitter randomness. |
| 1560 | let bytes = *Uuid::new_v4().as_bytes(); |
| 1561 | let sample = u16::from_le_bytes([bytes[0], bytes[1]]); |
| 1562 | let random_factor = f64::from(sample) / f64::from(u16::MAX); // 0.0 to 1.0 |
| 1563 | let jitter = jitter_range * (2.0 * random_factor - 1.0); // -range to +range |
| 1564 | |
| 1565 | (capped_delay + jitter).max(0.0) |
| 1566 | } else { |
| 1567 | capped_delay |
| 1568 | }; |
| 1569 | |
| 1570 | Duration::try_from_secs_f64(final_delay.max(0.0)).unwrap_or(Duration::MAX) |
| 1571 | } |
| 1572 | |
| 1573 | /// Checks if a given HTTP status code should trigger a retry |
| 1574 | pub fn is_retryable_status(&self, status: u16) -> bool { |
| 1575 | self.retryable_status_codes.contains(&status) |
| 1576 | && (self.operation == RetryOperation::ReadOnly || status == 429) |
| 1577 | } |
| 1578 | } |
| 1579 | |
| 1580 | /// Converts from the existing `RetryPolicy` in config |
| 1581 | impl From<RetryPolicy> for RetryConfig { |
| 1582 | fn from(policy: RetryPolicy) -> Self { |
| 1583 | Self { |
| 1584 | rate_limit: policy.rate_limit, |
| 1585 | enabled: policy.enabled, |
| 1586 | max_retries: policy.max_retries, |
| 1587 | initial_delay: policy.initial_delay, |
| 1588 | max_delay: policy.max_delay, |
| 1589 | exponential_base: policy.exponential_base, |
| 1590 | jitter: policy.jitter, |
| 1591 | jitter_factor: policy.jitter_factor, |
| 1592 | respect_retry_after: policy.respect_retry_after, |
| 1593 | ..Default::default() |
| 1594 | } |
| 1595 | } |
| 1596 | } |
| 1597 | |
| 1598 | /// Converts back to `RetryPolicy` for compatibility |
| 1599 | impl From<RetryConfig> for RetryPolicy { |
| 1600 | fn from(config: RetryConfig) -> Self { |
| 1601 | Self { |
| 1602 | rate_limit: config.rate_limit, |
| 1603 | enabled: config.enabled, |
| 1604 | max_retries: config.max_retries, |
| 1605 | initial_delay: config.initial_delay, |
| 1606 | max_delay: config.max_delay, |
| 1607 | exponential_base: config.exponential_base, |
| 1608 | jitter: config.jitter, |
| 1609 | jitter_factor: config.jitter_factor, |
| 1610 | respect_retry_after: config.respect_retry_after, |
| 1611 | } |
| 1612 | } |
| 1613 | } |
| 1614 | |
| 1615 | // === Retry Error and Result Types === |
| 1616 | |
| 1617 | /// Error returned when all retry attempts have been exhausted. |
| 1618 | #[derive(Debug)] |
| 1619 | pub struct RetryError { |
| 1620 | /// The last error encountered |
| 1621 | pub last_error: LlmError, |
| 1622 | |
| 1623 | /// Total number of attempts made |
| 1624 | pub attempts: u32, |
| 1625 | |
| 1626 | /// Total time spent across all attempts |
| 1627 | pub total_time: Duration, |
| 1628 | } |
| 1629 | |
| 1630 | impl std::fmt::Display for RetryError { |
| 1631 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 1632 | write!( |
| 1633 | f, |
| 1634 | "Retry exhausted after {} attempts ({:?}): {}", |
| 1635 | self.attempts, self.total_time, self.last_error |
| 1636 | ) |
| 1637 | } |
| 1638 | } |
| 1639 | |
| 1640 | impl std::error::Error for RetryError { |
| 1641 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
| 1642 | Some(&self.last_error) |
| 1643 | } |
| 1644 | } |
| 1645 | |
| 1646 | /// Result type for retry operations |
| 1647 | pub type RetryResult<T> = Result<T, RetryError>; |
| 1648 | |
| 1649 | /// Callback type for retry notifications |
| 1650 | /// |
| 1651 | /// Called before each retry with: |
| 1652 | /// - The error that triggered the retry |
| 1653 | /// - The attempt number (0-based) |
| 1654 | /// - The delay before the next attempt |
| 1655 | pub type RetryCallback = Box<dyn Fn(&LlmError, u32, Duration) + Send + Sync>; |
| 1656 | |
| 1657 | /// An observation of the existing request, never another retry driver. Its |
| 1658 | /// lexical scope captures the producing Engine queue, not an ambient session. |
| 1659 | pub type RetryStatusEmitter = |
| 1660 | std::sync::Arc<dyn Fn(String) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>; |
| 1661 | |
| 1662 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] |
| 1663 | pub struct ImageProjectionReceipt { |
| 1664 | pub cause: String, |
| 1665 | pub original_image_blocks: usize, |
| 1666 | pub omitted_oldest_blocks: usize, |
| 1667 | pub retained_newest_blocks: usize, |
| 1668 | pub body_bytes_before: usize, |
| 1669 | pub body_bytes_after: usize, |
| 1670 | pub omission_note: String, |
| 1671 | } |
| 1672 | |
| 1673 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] |
| 1674 | pub struct OutboundWireObservation { |
| 1675 | pub provider_id: String, |
| 1676 | pub route_id: Option<String>, |
| 1677 | pub endpoint_fingerprint: String, |
| 1678 | pub wire_model: String, |
| 1679 | pub wire_dialect: String, |
| 1680 | /// Responses dialect id from the prepared request. Empty for other wires. |
| 1681 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1682 | pub responses_profile_id: Option<String>, |
| 1683 | pub tools: ToolWireMeasurement, |
| 1684 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1685 | pub image_projection: Option<ImageProjectionReceipt>, |
| 1686 | } |
| 1687 | |
| 1688 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 1689 | pub struct OutboundTransmissionObservation { |
| 1690 | pub source_id: String, |
| 1691 | pub method: String, |
| 1692 | pub transmission: RequestTransmission, |
| 1693 | pub http_status: Option<u16>, |
| 1694 | } |
| 1695 | |
| 1696 | #[derive(Debug, Clone, Default, serde::Serialize)] |
| 1697 | pub struct OutboundWireObservationBatch { |
| 1698 | pub observations: Vec<OutboundWireObservation>, |
| 1699 | pub dropped: u64, |
| 1700 | pub transmissions: Vec<OutboundTransmissionObservation>, |
| 1701 | pub transmissions_dropped: u64, |
| 1702 | pub last_transmission: Option<OutboundTransmissionObservation>, |
| 1703 | } |
| 1704 | |
| 1705 | #[derive(Debug, Default)] |
| 1706 | struct OutboundWireObservationBuffer { |
| 1707 | batch: OutboundWireObservationBatch, |
| 1708 | retained_bytes: usize, |
| 1709 | next_transmission: u64, |
| 1710 | } |
| 1711 | |
| 1712 | #[derive(Debug, Clone, Default)] |
| 1713 | pub struct OutboundWireObservations { |
| 1714 | buffer: std::sync::Arc<std::sync::Mutex<OutboundWireObservationBuffer>>, |
| 1715 | } |
| 1716 | |
| 1717 | impl OutboundWireObservations { |
| 1718 | pub fn snapshot(&self) -> OutboundWireObservationBatch { |
| 1719 | self.buffer |
| 1720 | .lock() |
| 1721 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 1722 | .batch |
| 1723 | .clone() |
| 1724 | } |
| 1725 | |
| 1726 | pub fn drain(&self) -> OutboundWireObservationBatch { |
| 1727 | let mut buffer = self |
| 1728 | .buffer |
| 1729 | .lock() |
| 1730 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 1731 | buffer.retained_bytes = 0; |
| 1732 | std::mem::take(&mut buffer.batch) |
| 1733 | } |
| 1734 | |
| 1735 | fn begin_transmission(&self, request_id: &str, method: &reqwest::Method) -> String { |
| 1736 | let mut buffer = self |
| 1737 | .buffer |
| 1738 | .lock() |
| 1739 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 1740 | buffer.next_transmission = buffer.next_transmission.saturating_add(1); |
| 1741 | let source_id = format!("{request_id}:{}", buffer.next_transmission); |
| 1742 | let observation = OutboundTransmissionObservation { |
| 1743 | source_id: source_id.clone(), |
| 1744 | method: method.as_str().to_string(), |
| 1745 | transmission: RequestTransmission::OutcomeUnknown, |
| 1746 | http_status: None, |
| 1747 | }; |
| 1748 | buffer.batch.last_transmission = Some(observation.clone()); |
| 1749 | if buffer.batch.transmissions.len() < 32 { |
| 1750 | buffer.batch.transmissions.push(observation); |
| 1751 | } else { |
| 1752 | buffer.batch.transmissions_dropped = |
| 1753 | buffer.batch.transmissions_dropped.saturating_add(1); |
| 1754 | } |
| 1755 | source_id |
| 1756 | } |
| 1757 | |
| 1758 | fn settle_transmission( |
| 1759 | &self, |
| 1760 | source_id: &str, |
| 1761 | transmission: RequestTransmission, |
| 1762 | http_status: Option<u16>, |
| 1763 | ) { |
| 1764 | let mut buffer = self |
| 1765 | .buffer |
| 1766 | .lock() |
| 1767 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 1768 | if let Some(attempt) = buffer |
| 1769 | .batch |
| 1770 | .transmissions |
| 1771 | .iter_mut() |
| 1772 | .find(|attempt| attempt.source_id == source_id) |
| 1773 | { |
| 1774 | attempt.transmission = transmission; |
| 1775 | attempt.http_status = http_status; |
| 1776 | } |
| 1777 | if let Some(attempt) = buffer |
| 1778 | .batch |
| 1779 | .last_transmission |
| 1780 | .as_mut() |
| 1781 | .filter(|attempt| attempt.source_id == source_id) |
| 1782 | { |
| 1783 | attempt.transmission = transmission; |
| 1784 | attempt.http_status = http_status; |
| 1785 | } |
| 1786 | } |
| 1787 | |
| 1788 | fn record(&self, observation: OutboundWireObservation) { |
| 1789 | let retained_bytes = [ |
| 1790 | observation |
| 1791 | .image_projection |
| 1792 | .as_ref() |
| 1793 | .map_or(0, |projection| { |
| 1794 | projection.cause.capacity() + projection.omission_note.capacity() |
| 1795 | }), |
| 1796 | observation.provider_id.capacity(), |
| 1797 | observation.route_id.as_ref().map_or(0, String::capacity), |
| 1798 | observation.endpoint_fingerprint.capacity(), |
| 1799 | observation.wire_model.capacity(), |
| 1800 | observation.wire_dialect.capacity(), |
| 1801 | observation.tools.tool_schema_sha256.capacity(), |
| 1802 | observation |
| 1803 | .tools |
| 1804 | .omitted_tool_names |
| 1805 | .capacity() |
| 1806 | .saturating_mul(std::mem::size_of::<String>()), |
| 1807 | ] |
| 1808 | .into_iter() |
| 1809 | .chain( |
| 1810 | observation |
| 1811 | .tools |
| 1812 | .omitted_tool_names |
| 1813 | .iter() |
| 1814 | .map(String::capacity), |
| 1815 | ) |
| 1816 | .fold( |
| 1817 | std::mem::size_of::<OutboundWireObservation>(), |
| 1818 | usize::saturating_add, |
| 1819 | ); |
| 1820 | let mut buffer = self |
| 1821 | .buffer |
| 1822 | .lock() |
| 1823 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 1824 | if buffer.batch.observations.len() >= 32 |
| 1825 | || retained_bytes > (256 * 1024_usize).saturating_sub(buffer.retained_bytes) |
| 1826 | { |
| 1827 | buffer.batch.dropped = buffer.batch.dropped.saturating_add(1); |
| 1828 | return; |
| 1829 | } |
| 1830 | buffer.retained_bytes += retained_bytes; |
| 1831 | buffer.batch.observations.push(observation); |
| 1832 | } |
| 1833 | } |
| 1834 | |
| 1835 | #[derive(Clone)] |
| 1836 | pub struct RequestRetryObservation { |
| 1837 | pub request_id: String, |
| 1838 | pub retries: std::sync::Arc<std::sync::atomic::AtomicU32>, |
| 1839 | pub emit: RetryStatusEmitter, |
| 1840 | pub wire_observations: OutboundWireObservations, |
| 1841 | } |
| 1842 | |
| 1843 | impl RequestRetryObservation { |
| 1844 | pub fn isolated() -> Self { |
| 1845 | Self::for_auxiliary_request(uuid::Uuid::new_v4().to_string()) |
| 1846 | } |
| 1847 | |
| 1848 | pub fn for_auxiliary_request(request_id: impl Into<String>) -> Self { |
| 1849 | Self { |
| 1850 | request_id: request_id.into(), |
| 1851 | retries: std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0)), |
| 1852 | emit: std::sync::Arc::new(|_| Box::pin(async {})), |
| 1853 | wire_observations: OutboundWireObservations::default(), |
| 1854 | } |
| 1855 | } |
| 1856 | } |
| 1857 | |
| 1858 | impl OutboundWireObservationBatch { |
| 1859 | pub fn usage_coverage(&self, reported: bool, complete: bool) -> ProviderUsageCoverage { |
| 1860 | let last = self.last_transmission.as_ref(); |
| 1861 | let unknown_prior = self.transmissions_dropped != 0 |
| 1862 | || self.transmissions.iter().any(|attempt| { |
| 1863 | attempt.transmission == RequestTransmission::OutcomeUnknown |
| 1864 | && last.is_none_or(|last| last.source_id != attempt.source_id) |
| 1865 | }); |
| 1866 | if unknown_prior { |
| 1867 | return if reported { |
| 1868 | ProviderUsageCoverage::Incomplete |
| 1869 | } else { |
| 1870 | ProviderUsageCoverage::Missing |
| 1871 | }; |
| 1872 | } |
| 1873 | match last.map(|last| last.transmission) { |
| 1874 | None | Some(RequestTransmission::NotDispatched) => ProviderUsageCoverage::NotDispatched, |
| 1875 | Some(RequestTransmission::Rejected) => ProviderUsageCoverage::Rejected, |
| 1876 | Some(RequestTransmission::OutcomeUnknown) if reported && complete => { |
| 1877 | ProviderUsageCoverage::Reported |
| 1878 | } |
| 1879 | Some(RequestTransmission::OutcomeUnknown) if reported => { |
| 1880 | ProviderUsageCoverage::Incomplete |
| 1881 | } |
| 1882 | Some(RequestTransmission::OutcomeUnknown) => ProviderUsageCoverage::Missing, |
| 1883 | } |
| 1884 | } |
| 1885 | } |
| 1886 | |
| 1887 | tokio::task_local! { |
| 1888 | static REQUEST_RETRY_OBSERVATION: Option<RequestRetryObservation>; |
| 1889 | } |
| 1890 | |
| 1891 | pub async fn observe_request_retries<F: Future>( |
| 1892 | observation: Option<RequestRetryObservation>, |
| 1893 | future: F, |
| 1894 | ) -> F::Output { |
| 1895 | REQUEST_RETRY_OBSERVATION.scope(observation, future).await |
| 1896 | } |
| 1897 | |
| 1898 | pub fn begin_outbound_transmission( |
| 1899 | method: &reqwest::Method, |
| 1900 | ) -> Option<(OutboundWireObservations, String)> { |
| 1901 | REQUEST_RETRY_OBSERVATION |
| 1902 | .try_with(|observation| { |
| 1903 | observation.as_ref().map(|observation| { |
| 1904 | let wire = observation.wire_observations.clone(); |
| 1905 | let source = wire.begin_transmission(&observation.request_id, method); |
| 1906 | (wire, source) |
| 1907 | }) |
| 1908 | }) |
| 1909 | .ok() |
| 1910 | .flatten() |
| 1911 | } |
| 1912 | |
| 1913 | pub fn settle_outbound_transmission( |
| 1914 | pending: Option<(OutboundWireObservations, String)>, |
| 1915 | result: &Result<reqwest::Response, LlmError>, |
| 1916 | ) { |
| 1917 | let Some((wire, source)) = pending else { |
| 1918 | return; |
| 1919 | }; |
| 1920 | let (transmission, status) = match result { |
| 1921 | Ok(response) => { |
| 1922 | let status = response.status().as_u16(); |
| 1923 | let transmission = if matches!(status, 401 | 403 | 413 | 429) { |
| 1924 | RequestTransmission::Rejected |
| 1925 | } else { |
| 1926 | RequestTransmission::OutcomeUnknown |
| 1927 | }; |
| 1928 | (transmission, Some(status)) |
| 1929 | } |
| 1930 | Err(error) => (error.transmission(), None), |
| 1931 | }; |
| 1932 | wire.settle_transmission(&source, transmission, status); |
| 1933 | } |
| 1934 | |
| 1935 | pub fn settle_outbound_http_error(error: &LlmError) { |
| 1936 | let _ = REQUEST_RETRY_OBSERVATION.try_with(|observation| { |
| 1937 | if let Some(observation) = observation { |
| 1938 | let mut buffer = observation |
| 1939 | .wire_observations |
| 1940 | .buffer |
| 1941 | .lock() |
| 1942 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 1943 | if let Some(last) = buffer.batch.last_transmission.as_mut() { |
| 1944 | last.transmission = error.transmission(); |
| 1945 | let source = last.source_id.clone(); |
| 1946 | if let Some(attempt) = buffer |
| 1947 | .batch |
| 1948 | .transmissions |
| 1949 | .iter_mut() |
| 1950 | .find(|attempt| attempt.source_id == source) |
| 1951 | { |
| 1952 | attempt.transmission = error.transmission(); |
| 1953 | } |
| 1954 | } |
| 1955 | } |
| 1956 | }); |
| 1957 | } |
| 1958 | |
| 1959 | pub fn observe_outbound_wire(observation: impl FnOnce() -> OutboundWireObservation) { |
| 1960 | let observations = REQUEST_RETRY_OBSERVATION |
| 1961 | .try_with(|observation| { |
| 1962 | observation |
| 1963 | .as_ref() |
| 1964 | .map(|observation| observation.wire_observations.clone()) |
| 1965 | }) |
| 1966 | .ok() |
| 1967 | .flatten(); |
| 1968 | if let Some(observations) = observations { |
| 1969 | observations.record(observation()); |
| 1970 | } |
| 1971 | } |
| 1972 | |
| 1973 | pub async fn observe_transport_status(message: String) { |
| 1974 | let observation = REQUEST_RETRY_OBSERVATION |
| 1975 | .try_with(Clone::clone) |
| 1976 | .ok() |
| 1977 | .flatten(); |
| 1978 | if let Some(observation) = observation { |
| 1979 | (observation.emit)(message).await; |
| 1980 | } |
| 1981 | } |
| 1982 | |
| 1983 | pub fn observe_transport_attempt() { |
| 1984 | let _ = REQUEST_RETRY_OBSERVATION.try_with(|observation| { |
| 1985 | if let Some(observation) = observation { |
| 1986 | let mut count = observation |
| 1987 | .retries |
| 1988 | .load(std::sync::atomic::Ordering::Relaxed); |
| 1989 | loop { |
| 1990 | match observation.retries.compare_exchange_weak( |
| 1991 | count, |
| 1992 | count.saturating_add(1), |
| 1993 | std::sync::atomic::Ordering::Relaxed, |
| 1994 | std::sync::atomic::Ordering::Relaxed, |
| 1995 | ) { |
| 1996 | Ok(_) => break, |
| 1997 | Err(current) => count = current, |
| 1998 | } |
| 1999 | } |
| 2000 | } |
| 2001 | }); |
| 2002 | } |
| 2003 | |
| 2004 | /// A public receipt must never include the provider-controlled error payload. |
| 2005 | /// Raw errors remain intact in the original result and diagnostic/log paths. |
| 2006 | pub fn retry_reason_summary(error: &LlmError) -> String { |
| 2007 | match error { |
| 2008 | LlmError::RateLimited { .. } | LlmError::QuotaWindow { .. } => "rate limited".into(), |
| 2009 | LlmError::ServerError { status, .. } => format!("upstream {status}"), |
| 2010 | LlmError::NetworkError(_) | LlmError::HeaderTimeout { .. } => { |
| 2011 | "network error; request outcome unknown".into() |
| 2012 | } |
| 2013 | LlmError::ConnectError { .. } => "connection failed before dispatch".into(), |
| 2014 | LlmError::Timeout(_) => "timeout".into(), |
| 2015 | _ => "non-retryable provider failure".into(), |
| 2016 | } |
| 2017 | } |
| 2018 | |
| 2019 | async fn observe_transport_stopped(retries: u32, error: &LlmError, exhausted: bool) { |
| 2020 | if retries > 0 { |
| 2021 | let disposition = if exhausted { |
| 2022 | "Retry exhaustion" |
| 2023 | } else { |
| 2024 | "Retry stopped" |
| 2025 | }; |
| 2026 | observe_transport_status(format!( |
| 2027 | "{disposition}: transport request stopped after {retries} retries; {}", |
| 2028 | retry_reason_summary(error), |
| 2029 | )) |
| 2030 | .await; |
| 2031 | } |
| 2032 | } |
| 2033 | |
| 2034 | // === with_retry - Generic Retry Wrapper === |
| 2035 | |
| 2036 | /// Executes an async operation with configurable retry logic. |
| 2037 | /// |
| 2038 | /// This function wraps any async operation that returns `Result<T, LlmError>` |
| 2039 | /// and automatically retries on transient failures using exponential backoff. |
| 2040 | /// |
| 2041 | /// # Arguments |
| 2042 | /// |
| 2043 | /// * `config` - Retry configuration (delays, max attempts, etc.) |
| 2044 | /// * `operation` - Async closure to execute (will be called multiple times on retry) |
| 2045 | /// * `callback` - Optional callback for retry notifications (logging, metrics, etc.) |
| 2046 | /// |
| 2047 | /// # Returns |
| 2048 | /// |
| 2049 | /// * `Ok(T)` - The successful result from the operation |
| 2050 | /// * `Err(RetryError)` - All retries exhausted or non-retryable error encountered |
| 2051 | /// |
| 2052 | /// # Example |
| 2053 | /// |
| 2054 | /// ```ignore |
| 2055 | /// let result = with_retry( |
| 2056 | /// &config, |
| 2057 | /// || async { client.send_request(&req).await }, |
| 2058 | /// Some(Box::new(|err, attempt, delay| { |
| 2059 | /// eprintln!("Retry {} after {:?}: {}", attempt, delay, err); |
| 2060 | /// })), |
| 2061 | /// ).await; |
| 2062 | /// ``` |
| 2063 | // Keep the structured error inline: this is a public compatibility surface and |
| 2064 | // boxing it in a patch release would force every caller to change ownership |
| 2065 | // handling for `last_error`. |
| 2066 | #[allow(clippy::result_large_err)] |
| 2067 | pub async fn with_retry<F, Fut, T>( |
| 2068 | config: &RetryConfig, |
| 2069 | mut operation: F, |
| 2070 | callback: Option<RetryCallback>, |
| 2071 | ) -> RetryResult<T> |
| 2072 | where |
| 2073 | F: FnMut() -> Fut, |
| 2074 | Fut: Future<Output = Result<T, LlmError>>, |
| 2075 | { |
| 2076 | // If retries are disabled, just run once |
| 2077 | if !config.enabled { |
| 2078 | return operation().await.map_err(|e| RetryError { |
| 2079 | last_error: e |
| 2080 | .for_recovery_budget(Duration::from_secs(config.rate_limit.recovery_budget_secs)), |
| 2081 | attempts: 1, |
| 2082 | total_time: Duration::ZERO, |
| 2083 | }); |
| 2084 | } |
| 2085 | |
| 2086 | let start_time = Instant::now(); |
| 2087 | let mut attempts = 0u32; |
| 2088 | let mut transport_retries = 0u32; |
| 2089 | let mut rate_retries = 0u32; |
| 2090 | let mut recovery_started: Option<tokio::time::Instant> = None; |
| 2091 | let mut last_error = None; |
| 2092 | rate_limit::note_recovery_started(None); |
| 2093 | loop { |
| 2094 | if config.total_timeout > 0.0 && start_time.elapsed().as_secs_f64() >= config.total_timeout |
| 2095 | { |
| 2096 | let error = last_error.take().unwrap_or_else(|| { |
| 2097 | LlmError::Timeout(Duration::from_secs_f64(config.total_timeout)) |
| 2098 | }); |
| 2099 | observe_transport_stopped(attempts.saturating_sub(1), &error, true).await; |
| 2100 | return Err(RetryError { |
| 2101 | last_error: error, |
| 2102 | attempts, |
| 2103 | total_time: start_time.elapsed(), |
| 2104 | }); |
| 2105 | } |
| 2106 | if recovery_started.is_some_and(|started| { |
| 2107 | started.elapsed() >= Duration::from_secs(config.rate_limit.recovery_budget_secs) |
| 2108 | }) && let Some(error) = last_error.take() |
| 2109 | { |
| 2110 | observe_transport_stopped(attempts.saturating_sub(1), &error, true).await; |
| 2111 | return Err(RetryError { |
| 2112 | last_error: error, |
| 2113 | attempts, |
| 2114 | total_time: start_time.elapsed(), |
| 2115 | }); |
| 2116 | } |
| 2117 | if attempts > 0 { |
| 2118 | observe_transport_attempt(); |
| 2119 | } |
| 2120 | attempts = attempts.saturating_add(1); |
| 2121 | rate_limit::new_attempt(); |
| 2122 | match operation().await { |
| 2123 | Ok(result) => { |
| 2124 | if attempts > 1 { |
| 2125 | observe_transport_status(format!( |
| 2126 | "Retry recovery: HTTP operation recovered after {attempts} attempts" |
| 2127 | )) |
| 2128 | .await; |
| 2129 | } |
| 2130 | return Ok(result); |
| 2131 | } |
| 2132 | Err(mut err) => { |
| 2133 | let rate_limited = matches!( |
| 2134 | err, |
| 2135 | LlmError::RateLimited { .. } | LlmError::QuotaWindow { .. } |
| 2136 | ); |
| 2137 | let mut stop = !err.is_retryable_for(config.operation); |
| 2138 | let delay = if rate_limited { |
| 2139 | let started = *recovery_started.get_or_insert_with(tokio::time::Instant::now); |
| 2140 | rate_limit::note_recovery_started(Some(started)); |
| 2141 | let local = rate_limit::retry_delay(&config.rate_limit, rate_retries); |
| 2142 | rate_retries = rate_retries.saturating_add(1); |
| 2143 | let minimum = err.suggested_retry_delay().unwrap_or_default(); |
| 2144 | let delay = local.max(minimum).saturating_add(if minimum.is_zero() { |
| 2145 | Duration::ZERO |
| 2146 | } else { |
| 2147 | local.div_f64(2.0) |
| 2148 | }); |
| 2149 | let remaining = Duration::from_secs(config.rate_limit.recovery_budget_secs) |
| 2150 | .saturating_sub(started.elapsed()); |
| 2151 | stop |= attempts >= config.rate_limit.max_attempts |
| 2152 | || delay >= remaining |
| 2153 | || delay > codewhale_runtime::retry_status::MAX_PROVIDER_PAUSE; |
| 2154 | err = err.for_recovery_budget(remaining); |
| 2155 | delay |
| 2156 | } else { |
| 2157 | stop |= transport_retries >= config.max_retries; |
| 2158 | let delay = config.delay_for_attempt(transport_retries); |
| 2159 | transport_retries = transport_retries.saturating_add(1); |
| 2160 | delay.max(if config.respect_retry_after { |
| 2161 | err.suggested_retry_delay().unwrap_or_default() |
| 2162 | } else { |
| 2163 | Duration::ZERO |
| 2164 | }) |
| 2165 | }; |
| 2166 | stop |= recovery_started.is_some_and(|started| { |
| 2167 | delay |
| 2168 | >= Duration::from_secs(config.rate_limit.recovery_budget_secs) |
| 2169 | .saturating_sub(started.elapsed()) |
| 2170 | }); |
| 2171 | stop |= recovery_started.is_some() && attempts >= config.rate_limit.max_attempts; |
| 2172 | stop |= config.total_timeout > 0.0 |
| 2173 | && start_time.elapsed().saturating_add(delay).as_secs_f64() |
| 2174 | >= config.total_timeout; |
| 2175 | if stop { |
| 2176 | observe_transport_stopped(attempts.saturating_sub(1), &err, true).await; |
| 2177 | return Err(RetryError { |
| 2178 | last_error: err, |
| 2179 | attempts, |
| 2180 | total_time: start_time.elapsed(), |
| 2181 | }); |
| 2182 | } |
| 2183 | if let Some(ref cb) = callback { |
| 2184 | cb(&err, attempts - 1, delay); |
| 2185 | } |
| 2186 | observe_transport_status(format!( |
| 2187 | "Retry attempt: HTTP {attempts}; {}; waiting {:.2}s", |
| 2188 | retry_reason_summary(&err), |
| 2189 | delay.as_secs_f64() |
| 2190 | )) |
| 2191 | .await; |
| 2192 | last_error = Some(err); |
| 2193 | rate_limit::wait(delay).await; |
| 2194 | } |
| 2195 | } |
| 2196 | } |
| 2197 | } |
| 2198 | |
| 2199 | // === Utility Functions === |
| 2200 | |
| 2201 | /// Parse numeric seconds or an HTTP-date. Long server minima are preserved; |
| 2202 | /// the independent recovery budget parks the operation instead of retrying early. |
| 2203 | pub fn parse_retry_after(value: &str) -> Option<Duration> { |
| 2204 | rate_limit::server_delay(value) |
| 2205 | } |
| 2206 | |
| 2207 | /// Extracts Retry-After duration from response headers |
| 2208 | pub fn extract_retry_after(headers: &reqwest::header::HeaderMap) -> Option<Duration> { |
| 2209 | headers |
| 2210 | .get(reqwest::header::RETRY_AFTER) |
| 2211 | .and_then(|v| v.to_str().ok()) |
| 2212 | .and_then(parse_retry_after) |
| 2213 | } |
| 2214 | |
| 2215 | pub fn server_refuses_retry(status: u16, headers: &reqwest::header::HeaderMap) -> bool { |
| 2216 | status >= 400 |
| 2217 | && headers |
| 2218 | .get("x-should-retry") |
| 2219 | .and_then(|v| v.to_str().ok()) |
| 2220 | .is_some_and(|v| v.trim().eq_ignore_ascii_case("false")) |
| 2221 | } |
| 2222 | |
| 2223 | pub fn retry_delay_from_error_body(body: &str) -> Option<Duration> { |
| 2224 | static HINTS: std::sync::OnceLock<[regex::Regex; 2]> = std::sync::OnceLock::new(); |
| 2225 | let [structured, prose] = HINTS.get_or_init(|| { |
| 2226 | [ |
| 2227 | regex::Regex::new(r#"retryDelay\\?"\s*:\s*\\?"\s*(\d+(?:\.\d+)?)\s*s"#).unwrap(), |
| 2228 | regex::Regex::new(r"(?i)retry in\s+(\d+(?:\.\d+)?)\s*s").unwrap(), |
| 2229 | ] |
| 2230 | }); |
| 2231 | [structured, prose] |
| 2232 | .into_iter() |
| 2233 | .flat_map(|pattern| pattern.captures_iter(body)) |
| 2234 | .filter_map(|captures| captures.get(1)) |
| 2235 | .filter_map(|value| value.as_str().parse::<f64>().ok()) |
| 2236 | .filter_map(|seconds| Duration::try_from_secs_f64(seconds).ok()) |
| 2237 | .max() |
| 2238 | } |
| 2239 | |
| 2240 | #[cfg(test)] |
| 2241 | #[path = "tests.rs"] |
| 2242 | mod quota_tests; |
| 2243 | |
| 2244 | // === Tests === |
| 2245 | |
| 2246 | #[cfg(test)] |
| 2247 | mod tests { |
| 2248 | use super::*; |
| 2249 | |
| 2250 | #[test] |
| 2251 | fn official_chatgpt_usage_codes_are_terminal_across_http_boundaries() { |
| 2252 | for code in [ |
| 2253 | "subscription_sharing_usage_limit_exceeded", |
| 2254 | "subscription_sharing_usage_unavailable", |
| 2255 | ] { |
| 2256 | let body = serde_json::json!({"error":{"code":code,"message":"opaque"}}).to_string(); |
| 2257 | for status in [400, 403, 429] { |
| 2258 | for safe_body in [body.clone(), sanitize_http_error_body(None, status, &body)] { |
| 2259 | let error = |
| 2260 | LlmError::from_http_response_with_auth_context(status, &safe_body, None); |
| 2261 | assert!(matches!(error, LlmError::QuotaExhausted(_)), "{error:?}"); |
| 2262 | assert!(!error.is_retryable()); |
| 2263 | assert!(error.to_string().contains("ChatGPT Settings > Usage")); |
| 2264 | let envelope = crate::llm_error_envelope::envelope_for_llm_error( |
| 2265 | error.into(), |
| 2266 | "allowance unavailable".into(), |
| 2267 | ); |
| 2268 | assert!(!envelope.recoverable); |
| 2269 | assert_eq!(envelope.code, "llm_quota_exhausted"); |
| 2270 | } |
| 2271 | } |
| 2272 | } |
| 2273 | for body in [ |
| 2274 | "usage limit reached", |
| 2275 | r#"{"error":{"code":"subscription_sharing_usage_limit_exceeded_later"}}"#, |
| 2276 | ] { |
| 2277 | assert!(matches!( |
| 2278 | LlmError::from_http_response(429, body), |
| 2279 | LlmError::RateLimited { .. } |
| 2280 | )); |
| 2281 | assert!(LlmError::from_http_response(429, body).is_retryable()); |
| 2282 | } |
| 2283 | } |
| 2284 | |
| 2285 | fn assert_f64_eq(actual: f64, expected: f64) { |
| 2286 | assert!( |
| 2287 | (actual - expected).abs() < f64::EPSILON, |
| 2288 | "expected {expected}, got {actual}" |
| 2289 | ); |
| 2290 | } |
| 2291 | |
| 2292 | fn auth_user_message(error: LlmError) -> String { |
| 2293 | match error { |
| 2294 | LlmError::AuthenticationError(auth) => auth.to_user_message(), |
| 2295 | other => panic!("expected authentication error, got {other}"), |
| 2296 | } |
| 2297 | } |
| 2298 | |
| 2299 | #[test] |
| 2300 | fn test_retry_config_defaults() { |
| 2301 | let config = RetryConfig::default(); |
| 2302 | assert_eq!(config.operation, RetryOperation::Inference); |
| 2303 | assert!(!config.is_retryable_status(500)); |
| 2304 | assert!(config.is_retryable_status(429)); |
| 2305 | assert!(config.enabled); |
| 2306 | assert_eq!(config.max_retries, 3); |
| 2307 | assert_f64_eq(config.initial_delay, 1.0); |
| 2308 | assert_f64_eq(config.max_delay, 60.0); |
| 2309 | assert_f64_eq(config.exponential_base, 2.0); |
| 2310 | assert!(config.jitter); |
| 2311 | } |
| 2312 | |
| 2313 | #[test] |
| 2314 | fn test_retry_config_disabled() { |
| 2315 | let config = RetryConfig::disabled(); |
| 2316 | assert!(!config.enabled); |
| 2317 | } |
| 2318 | |
| 2319 | #[test] |
| 2320 | fn test_retry_config_builder() { |
| 2321 | let config = RetryConfig::new() |
| 2322 | .with_max_retries(5) |
| 2323 | .with_initial_delay(2.0) |
| 2324 | .with_max_delay(120.0) |
| 2325 | .with_jitter(false); |
| 2326 | |
| 2327 | assert_eq!(config.max_retries, 5); |
| 2328 | assert_f64_eq(config.initial_delay, 2.0); |
| 2329 | assert_f64_eq(config.max_delay, 120.0); |
| 2330 | assert!(!config.jitter); |
| 2331 | } |
| 2332 | |
| 2333 | #[test] |
| 2334 | fn test_delay_for_attempt_exponential() { |
| 2335 | let config = RetryConfig::new().with_jitter(false); |
| 2336 | |
| 2337 | // delay = initial * base^attempt |
| 2338 | // 1.0 * 2^0 = 1.0 |
| 2339 | let d0 = config.delay_for_attempt(0); |
| 2340 | assert_eq!(d0, Duration::from_secs_f64(1.0)); |
| 2341 | |
| 2342 | // 1.0 * 2^1 = 2.0 |
| 2343 | let d1 = config.delay_for_attempt(1); |
| 2344 | assert_eq!(d1, Duration::from_secs_f64(2.0)); |
| 2345 | |
| 2346 | // 1.0 * 2^2 = 4.0 |
| 2347 | let d2 = config.delay_for_attempt(2); |
| 2348 | assert_eq!(d2, Duration::from_secs_f64(4.0)); |
| 2349 | |
| 2350 | // 1.0 * 2^3 = 8.0 |
| 2351 | let d3 = config.delay_for_attempt(3); |
| 2352 | assert_eq!(d3, Duration::from_secs_f64(8.0)); |
| 2353 | } |
| 2354 | |
| 2355 | #[test] |
| 2356 | fn test_delay_for_attempt_capped() { |
| 2357 | let config = RetryConfig::new().with_jitter(false).with_max_delay(5.0); |
| 2358 | |
| 2359 | // 1.0 * 2^3 = 8.0, but capped at 5.0 |
| 2360 | let d3 = config.delay_for_attempt(3); |
| 2361 | assert_eq!(d3, Duration::from_secs_f64(5.0)); |
| 2362 | } |
| 2363 | |
| 2364 | #[test] |
| 2365 | fn delay_for_attempt_survives_negative_and_huge_configured_delays() { |
| 2366 | let negative = RetryConfig::new().with_jitter(false).with_max_delay(-1.0); |
| 2367 | assert_eq!(negative.delay_for_attempt(0), Duration::ZERO); |
| 2368 | |
| 2369 | let huge = RetryConfig::new() |
| 2370 | .with_jitter(false) |
| 2371 | .with_initial_delay(1e30) |
| 2372 | .with_max_delay(f64::INFINITY); |
| 2373 | assert_eq!(huge.delay_for_attempt(0), Duration::MAX); |
| 2374 | } |
| 2375 | |
| 2376 | #[test] |
| 2377 | fn test_delay_for_attempt_with_jitter() { |
| 2378 | let config = RetryConfig::new().with_jitter(true); |
| 2379 | |
| 2380 | // With jitter, delays should vary slightly |
| 2381 | let d1 = config.delay_for_attempt(1); |
| 2382 | let d2 = config.delay_for_attempt(1); |
| 2383 | |
| 2384 | // Both should be close to 2.0 seconds (within 10% jitter) |
| 2385 | let base = 2.0; |
| 2386 | let range = base * 0.1; |
| 2387 | assert!(d1.as_secs_f64() >= base - range); |
| 2388 | assert!(d1.as_secs_f64() <= base + range); |
| 2389 | assert!(d2.as_secs_f64() >= base - range); |
| 2390 | assert!(d2.as_secs_f64() <= base + range); |
| 2391 | } |
| 2392 | |
| 2393 | #[test] |
| 2394 | fn test_is_retryable_status() { |
| 2395 | let config = RetryConfig { |
| 2396 | operation: RetryOperation::ReadOnly, |
| 2397 | ..RetryConfig::default() |
| 2398 | }; |
| 2399 | |
| 2400 | assert!(config.is_retryable_status(429)); // Rate limit |
| 2401 | assert!(config.is_retryable_status(499)); // Upstream request cancelled |
| 2402 | assert!(config.is_retryable_status(500)); // Internal server error |
| 2403 | assert!(config.is_retryable_status(502)); // Bad gateway |
| 2404 | assert!(config.is_retryable_status(503)); // Service unavailable |
| 2405 | assert!(config.is_retryable_status(504)); // Gateway timeout |
| 2406 | |
| 2407 | assert!(!config.is_retryable_status(400)); // Bad request |
| 2408 | assert!(!config.is_retryable_status(401)); // Unauthorized |
| 2409 | assert!(!config.is_retryable_status(403)); // Forbidden |
| 2410 | assert!(!config.is_retryable_status(404)); // Not found |
| 2411 | } |
| 2412 | |
| 2413 | #[test] |
| 2414 | fn pre_dispatch_and_rate_bodies_retry_while_server_refusal_needs_error_status() { |
| 2415 | let origin_tls = LlmError::from_http_response(525, "SSL handshake failed"); |
| 2416 | assert!(origin_tls.is_retryable()); |
| 2417 | assert_eq!( |
| 2418 | origin_tls.transmission(), |
| 2419 | RequestTransmission::NotDispatched |
| 2420 | ); |
| 2421 | |
| 2422 | for status in [400, 500, 503] { |
| 2423 | let rate = LlmError::from_http_response( |
| 2424 | status, |
| 2425 | r#"{"error":{"message":"The request rate increased too quickly. Scale up gradually."}}"#, |
| 2426 | ); |
| 2427 | assert!( |
| 2428 | matches!(rate, LlmError::RateLimited { .. }), |
| 2429 | "{status}: {rate:?}" |
| 2430 | ); |
| 2431 | assert!(rate.is_retryable()); |
| 2432 | } |
| 2433 | assert!(!LlmError::from_http_response(502, "MALFORMED_RESPONSE").is_retryable()); |
| 2434 | assert!(!LlmError::from_http_response(500, "upstream SSE stream failed").is_retryable()); |
| 2435 | |
| 2436 | let mut headers = reqwest::header::HeaderMap::new(); |
| 2437 | headers.insert("x-should-retry", "false".parse().unwrap()); |
| 2438 | assert!(!server_refuses_retry(200, &headers)); |
| 2439 | assert!(!server_refuses_retry(206, &headers)); |
| 2440 | assert!(server_refuses_retry(429, &headers)); |
| 2441 | assert!(!server_refuses_retry( |
| 2442 | 429, |
| 2443 | &reqwest::header::HeaderMap::new() |
| 2444 | )); |
| 2445 | headers.insert("x-should-retry", "true".parse().unwrap()); |
| 2446 | assert!(!server_refuses_retry(429, &headers)); |
| 2447 | |
| 2448 | let refused = LlmError::from_http_response(429, "slow down").into_non_retryable(); |
| 2449 | assert!(!refused.is_retryable()); |
| 2450 | assert_eq!(refused.transmission(), RequestTransmission::Rejected); |
| 2451 | assert!(!origin_tls.into_non_retryable().is_retryable()); |
| 2452 | } |
| 2453 | |
| 2454 | #[test] |
| 2455 | fn auth_error_with_context_includes_provider_authority_model_and_key_source() { |
| 2456 | let err = LlmError::from_http_response_with_request_context( |
| 2457 | 401, |
| 2458 | "Invalid API Key", |
| 2459 | Some("Xiaomi MiMo"), |
| 2460 | Some("https://token-plan-sgp.xiaomimimo.com/v1"), |
| 2461 | Some("mimo-v2.5"), |
| 2462 | Some("env"), |
| 2463 | Some("tp-secret-token-plan-value"), |
| 2464 | ); |
| 2465 | let message = auth_user_message(err); |
| 2466 | |
| 2467 | assert!(message.contains("Invalid API Key")); |
| 2468 | assert!(message.contains("provider: Xiaomi MiMo")); |
| 2469 | assert!(message.contains("base URL authority: token-plan-sgp.xiaomimimo.com")); |
| 2470 | assert!(message.contains("model: mimo-v2.5")); |
| 2471 | assert!(message.contains("key source: env")); |
| 2472 | assert!(message.contains("key fingerprint: tp-... (len=26)")); |
| 2473 | } |
| 2474 | |
| 2475 | #[test] |
| 2476 | fn auth_error_redacts_full_api_key_from_body_and_context() { |
| 2477 | let api_key = "tp-secret-token-plan-value"; |
| 2478 | let err = LlmError::from_http_response_with_request_context( |
| 2479 | 401, |
| 2480 | &format!("Invalid API Key: {api_key}"), |
| 2481 | Some("Xiaomi MiMo"), |
| 2482 | Some("https://token-plan-sgp.xiaomimimo.com/v1"), |
| 2483 | Some("mimo-v2.5"), |
| 2484 | Some("config-file"), |
| 2485 | Some(api_key), |
| 2486 | ); |
| 2487 | let message = auth_user_message(err); |
| 2488 | |
| 2489 | assert!(!message.contains(api_key)); |
| 2490 | assert!(!message.contains("secret-token-plan-value")); |
| 2491 | assert!(message.contains("[redacted API key]")); |
| 2492 | assert!(message.contains("key fingerprint: tp-... (len=26)")); |
| 2493 | } |
| 2494 | |
| 2495 | #[test] |
| 2496 | fn auth_error_classifies_xiaomi_token_plan_key_prefix() { |
| 2497 | let token_plan = AuthenticationErrorContext::from_parts( |
| 2498 | None, |
| 2499 | None, |
| 2500 | None, |
| 2501 | Some("session"), |
| 2502 | Some("tp-secret-token-plan-value"), |
| 2503 | ); |
| 2504 | let generic = AuthenticationErrorContext::from_parts( |
| 2505 | None, |
| 2506 | None, |
| 2507 | None, |
| 2508 | Some("session"), |
| 2509 | Some("sk-other"), |
| 2510 | ); |
| 2511 | let unprefixed = AuthenticationErrorContext::from_parts( |
| 2512 | None, |
| 2513 | None, |
| 2514 | None, |
| 2515 | Some("session"), |
| 2516 | Some("plainsecretvalue"), |
| 2517 | ); |
| 2518 | |
| 2519 | assert_eq!( |
| 2520 | token_plan.key_kind.as_deref(), |
| 2521 | Some("Xiaomi MiMo Token Plan key") |
| 2522 | ); |
| 2523 | assert_eq!(generic.key_kind.as_deref(), Some("API key")); |
| 2524 | assert_eq!(unprefixed.key_kind.as_deref(), Some("API key")); |
| 2525 | assert_eq!( |
| 2526 | unprefixed.key_fingerprint.as_deref(), |
| 2527 | Some("unprefixed (len=16)") |
| 2528 | ); |
| 2529 | } |
| 2530 | |
| 2531 | #[test] |
| 2532 | fn authorization_403_is_not_reclassified_by_auth_context() { |
| 2533 | let err = LlmError::from_http_response_with_request_context( |
| 2534 | 403, |
| 2535 | "forbidden", |
| 2536 | Some("Arcee AI"), |
| 2537 | Some("https://api.arcee.ai/v1"), |
| 2538 | Some("auto"), |
| 2539 | Some("env"), |
| 2540 | Some("sk-arcee-secret"), |
| 2541 | ); |
| 2542 | |
| 2543 | assert!(matches!(err, LlmError::AuthorizationError(_))); |
| 2544 | } |
| 2545 | |
| 2546 | #[test] |
| 2547 | fn auth_error_without_context_preserves_bare_message() { |
| 2548 | let err = LlmError::from_http_response_with_auth_context( |
| 2549 | 401, |
| 2550 | "Invalid API Key", |
| 2551 | Some(AuthenticationErrorContext::default()), |
| 2552 | ); |
| 2553 | |
| 2554 | assert_eq!(auth_user_message(err), "Invalid API Key"); |
| 2555 | } |
| 2556 | |
| 2557 | /// A flat `{"error","message"}` body keeps its detail: the class alone |
| 2558 | /// ("Bad Request") told the person nothing about the rejected model. |
| 2559 | #[test] |
| 2560 | fn flat_error_and_message_body_surfaces_both_halves() { |
| 2561 | let body = r#"{"error":"Bad Request","message":"Invalid model name: 'invalid-model-xyz'"}"#; |
| 2562 | assert_eq!( |
| 2563 | sanitize_http_error_body(Some("Concentrate"), 400, body), |
| 2564 | "Bad Request: Invalid model name: 'invalid-model-xyz'" |
| 2565 | ); |
| 2566 | // Identical halves are not doubled, and the nested OpenAI shape is |
| 2567 | // untouched. |
| 2568 | assert_eq!( |
| 2569 | sanitize_http_error_body( |
| 2570 | Some("Concentrate"), |
| 2571 | 401, |
| 2572 | r#"{"error":"Unauthorized","message":"Unauthorized"}"# |
| 2573 | ), |
| 2574 | "Unauthorized" |
| 2575 | ); |
| 2576 | assert_eq!( |
| 2577 | sanitize_http_error_body( |
| 2578 | Some("fixture"), |
| 2579 | 400, |
| 2580 | r#"{"error":{"message":"nested detail"}}"# |
| 2581 | ), |
| 2582 | "nested detail" |
| 2583 | ); |
| 2584 | } |
| 2585 | |
| 2586 | #[test] |
| 2587 | fn cloudflare_html_error_is_summarized_without_raw_markup() { |
| 2588 | let body = r#"<!DOCTYPE html><html><head><title>Access Denied</title><style> |
| 2589 | .hidden { display: none; } |
| 2590 | </style></head><body> |
| 2591 | <h1>Access Denied</h1> |
| 2592 | <p>The action you just performed triggered a security alert.</p> |
| 2593 | <script>window.noisy = true;</script> |
| 2594 | <span>2600:1700:467:d410:f137:b94f:1dd0:d1e4</span> |
| 2595 | <span>a059a2873f3fdf82</span> |
| 2596 | <div>Cloudflare Error Pages</div> |
| 2597 | </body></html>"#; |
| 2598 | |
| 2599 | let message = sanitize_http_error_body(Some("Arcee AI"), 403, body); |
| 2600 | |
| 2601 | assert!(message.contains("Arcee AI API returned Cloudflare Access Denied")); |
| 2602 | assert!(message.contains("ID a059a2873f3fdf82")); |
| 2603 | assert!(!message.contains("<!DOCTYPE")); |
| 2604 | assert!(!message.contains("tailwindcss")); |
| 2605 | assert!(message.len() < 300); |
| 2606 | } |
| 2607 | |
| 2608 | #[test] |
| 2609 | fn cloudflare_access_denied_403_is_authorization_not_authentication() { |
| 2610 | let message = sanitize_http_error_body( |
| 2611 | Some("Arcee AI"), |
| 2612 | 403, |
| 2613 | r#"<!doctype html><html><body><h1>Access Denied</h1><p>Cloudflare Error Pages</p></body></html>"#, |
| 2614 | ); |
| 2615 | let err = LlmError::from_http_response(403, &message); |
| 2616 | |
| 2617 | assert!(matches!(err, LlmError::AuthorizationError(_))); |
| 2618 | } |
| 2619 | |
| 2620 | #[test] |
| 2621 | fn arcee_access_denied_without_literal_cloudflare_is_still_summarized() { |
| 2622 | // Mirrors api.arcee.ai's real 403 page: "Cloudflare" appears only in a |
| 2623 | // `<meta>` attribute and the `<style>` block, both stripped, so the |
| 2624 | // visible text never contains it. The summary must still fire from the |
| 2625 | // WAF's stock "security alert" / "Contact Support" copy + error ID. |
| 2626 | let body = r#"<!DOCTYPE html><html lang="en"><head> |
| 2627 | <meta name="description" content="Cloudflare Error Pages"> |
| 2628 | <title>Access Denied</title> |
| 2629 | <style>:root{--accent:cloudflare}</style></head><body> |
| 2630 | <h1>Access Denied</h1> |
| 2631 | <p>The action you just performed triggered a security alert.</p> |
| 2632 | <p>Please contact us if this was a mistake.</p> |
| 2633 | <a>Contact Support</a> |
| 2634 | <span>2600:1700:467:d410:f137:b94f:1dd0:d1e4</span> |
| 2635 | <span>a059c0d4caf1f9cc</span> |
| 2636 | </body></html>"#; |
| 2637 | |
| 2638 | let message = sanitize_http_error_body(Some("Arcee AI"), 403, body); |
| 2639 | |
| 2640 | assert!( |
| 2641 | message.contains("Arcee AI API returned Access Denied"), |
| 2642 | "got: {message}" |
| 2643 | ); |
| 2644 | assert!(message.contains("ID a059c0d4caf1f9cc"), "got: {message}"); |
| 2645 | assert!( |
| 2646 | !message.to_ascii_lowercase().contains("cloudflare"), |
| 2647 | "stripped Arcee page has no literal Cloudflare: {message}" |
| 2648 | ); |
| 2649 | assert!(!message.contains('<'), "no raw markup: {message}"); |
| 2650 | assert!(message.len() < 300, "stays concise: {message}"); |
| 2651 | |
| 2652 | // A WAF block is authorization, not a bad API key. |
| 2653 | let err = LlmError::from_http_response(403, &message); |
| 2654 | assert!(matches!(err, LlmError::AuthorizationError(_))); |
| 2655 | } |
| 2656 | |
| 2657 | #[test] |
| 2658 | fn test_llm_error_suggested_retry_delay() { |
| 2659 | let err = LlmError::RateLimited { |
| 2660 | message: "slow down".to_string(), |
| 2661 | retry_after: Some(Duration::from_secs(60)), |
| 2662 | }; |
| 2663 | assert_eq!(err.suggested_retry_delay(), Some(Duration::from_secs(60))); |
| 2664 | |
| 2665 | let err = LlmError::ServerError { |
| 2666 | status: 500, |
| 2667 | message: "error".to_string(), |
| 2668 | }; |
| 2669 | assert_eq!(err.suggested_retry_delay(), None); |
| 2670 | } |
| 2671 | |
| 2672 | #[test] |
| 2673 | fn test_parse_retry_after() { |
| 2674 | // Integer seconds |
| 2675 | assert_eq!(parse_retry_after("120"), Some(Duration::from_secs(120))); |
| 2676 | assert_eq!(parse_retry_after("0"), Some(Duration::from_secs(0))); |
| 2677 | |
| 2678 | // Float seconds keep sub-second precision |
| 2679 | assert_eq!(parse_retry_after("1.5"), Some(Duration::from_secs_f64(1.5))); |
| 2680 | |
| 2681 | // Invalid |
| 2682 | assert_eq!(parse_retry_after("invalid"), None); |
| 2683 | assert_eq!(parse_retry_after(""), None); |
| 2684 | } |
| 2685 | |
| 2686 | /// A `Retry-After` value is server-controlled. Malformed floats used to |
| 2687 | /// reach `Duration::from_secs_f64`, which panics on a negative — a |
| 2688 | /// remote-triggerable crash in the request path (2026-08-04 review). |
| 2689 | #[test] |
| 2690 | fn parse_retry_after_never_panics_and_is_bounded_on_hostile_input() { |
| 2691 | // None of these may panic. |
| 2692 | assert_eq!(parse_retry_after("-5"), None, "negative is not a delay"); |
| 2693 | assert_eq!(parse_retry_after("nan"), None); |
| 2694 | assert_eq!(parse_retry_after("inf"), None); |
| 2695 | assert_eq!(parse_retry_after("-inf"), None); |
| 2696 | // Absurdly large values clamp to the ceiling rather than overflowing |
| 2697 | // or wedging the turn for a day. |
| 2698 | assert_eq!(parse_retry_after("1e300"), None); |
| 2699 | assert_eq!(parse_retry_after("86400"), Some(Duration::from_secs(86400))); |
| 2700 | assert_eq!( |
| 2701 | parse_retry_after("999999999999"), |
| 2702 | Some(Duration::from_secs(999999999999)), |
| 2703 | "valid long minima are preserved" |
| 2704 | ); |
| 2705 | // A normal value still passes through untouched. |
| 2706 | assert_eq!(parse_retry_after("30"), Some(Duration::from_secs(30))); |
| 2707 | } |
| 2708 | |
| 2709 | #[test] |
| 2710 | fn test_retry_policy_conversion() { |
| 2711 | let policy = RetryPolicy { |
| 2712 | rate_limit: RateLimitRetryPolicy::default(), |
| 2713 | enabled: true, |
| 2714 | max_retries: 5, |
| 2715 | initial_delay: 2.0, |
| 2716 | max_delay: 30.0, |
| 2717 | exponential_base: 3.0, |
| 2718 | jitter: false, |
| 2719 | jitter_factor: 0.25, |
| 2720 | respect_retry_after: false, |
| 2721 | }; |
| 2722 | |
| 2723 | let config: RetryConfig = policy.clone().into(); |
| 2724 | assert_eq!(config.enabled, policy.enabled); |
| 2725 | assert_eq!(config.max_retries, policy.max_retries); |
| 2726 | assert_f64_eq(config.initial_delay, policy.initial_delay); |
| 2727 | assert_f64_eq(config.max_delay, policy.max_delay); |
| 2728 | assert_f64_eq(config.exponential_base, policy.exponential_base); |
| 2729 | |
| 2730 | // #6700: the jitter and Retry-After knobs survive the conversion |
| 2731 | // instead of silently resetting to `RetryConfig::default()`. |
| 2732 | assert!(!config.jitter); |
| 2733 | assert_f64_eq(config.jitter_factor, 0.25); |
| 2734 | assert!(!config.respect_retry_after); |
| 2735 | |
| 2736 | // Convert back |
| 2737 | let policy2: RetryPolicy = config.into(); |
| 2738 | assert_eq!(policy2.enabled, policy.enabled); |
| 2739 | assert_eq!(policy2.max_retries, policy.max_retries); |
| 2740 | assert_eq!(policy2.jitter, policy.jitter); |
| 2741 | assert_f64_eq(policy2.jitter_factor, policy.jitter_factor); |
| 2742 | assert_eq!(policy2.respect_retry_after, policy.respect_retry_after); |
| 2743 | } |
| 2744 | |
| 2745 | #[tokio::test] |
| 2746 | async fn test_with_retry_success_first_attempt() { |
| 2747 | let config = RetryConfig { |
| 2748 | operation: RetryOperation::ReadOnly, |
| 2749 | ..RetryConfig::default() |
| 2750 | }; |
| 2751 | let mut call_count = 0; |
| 2752 | |
| 2753 | let result = with_retry( |
| 2754 | &config, |
| 2755 | || { |
| 2756 | call_count += 1; |
| 2757 | async { Ok::<_, LlmError>(42) } |
| 2758 | }, |
| 2759 | None, |
| 2760 | ) |
| 2761 | .await; |
| 2762 | |
| 2763 | assert!(result.is_ok()); |
| 2764 | assert_eq!(result.unwrap(), 42); |
| 2765 | assert_eq!(call_count, 1); |
| 2766 | } |
| 2767 | |
| 2768 | #[tokio::test] |
| 2769 | async fn test_with_retry_disabled() { |
| 2770 | let config = RetryConfig::disabled(); |
| 2771 | let mut call_count = 0; |
| 2772 | |
| 2773 | let result: RetryResult<i32> = with_retry( |
| 2774 | &config, |
| 2775 | || { |
| 2776 | call_count += 1; |
| 2777 | async { |
| 2778 | Err(LlmError::ServerError { |
| 2779 | status: 500, |
| 2780 | message: "error".to_string(), |
| 2781 | }) |
| 2782 | } |
| 2783 | }, |
| 2784 | None, |
| 2785 | ) |
| 2786 | .await; |
| 2787 | |
| 2788 | assert!(result.is_err()); |
| 2789 | assert_eq!(call_count, 1); // No retries when disabled |
| 2790 | } |
| 2791 | |
| 2792 | #[tokio::test] |
| 2793 | async fn test_with_retry_eventual_success() { |
| 2794 | let mut config = RetryConfig::new() |
| 2795 | .with_max_retries(3) |
| 2796 | .with_initial_delay(0.01); |
| 2797 | config.operation = RetryOperation::ReadOnly; // Fast for testing |
| 2798 | |
| 2799 | let call_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0)); |
| 2800 | let cc = call_count.clone(); |
| 2801 | |
| 2802 | let result = with_retry( |
| 2803 | &config, |
| 2804 | || { |
| 2805 | let count = cc.fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 2806 | async move { |
| 2807 | if count < 2 { |
| 2808 | Err(LlmError::ServerError { |
| 2809 | status: 500, |
| 2810 | message: "temporary error".to_string(), |
| 2811 | }) |
| 2812 | } else { |
| 2813 | Ok::<_, LlmError>(42) |
| 2814 | } |
| 2815 | } |
| 2816 | }, |
| 2817 | None, |
| 2818 | ) |
| 2819 | .await; |
| 2820 | |
| 2821 | assert!(result.is_ok()); |
| 2822 | assert_eq!(result.unwrap(), 42); |
| 2823 | assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 3); // 2 failures + 1 success |
| 2824 | } |
| 2825 | |
| 2826 | #[tokio::test] |
| 2827 | async fn test_with_retry_exhausted() { |
| 2828 | let mut config = RetryConfig::new() |
| 2829 | .with_max_retries(2) |
| 2830 | .with_initial_delay(0.01); |
| 2831 | config.operation = RetryOperation::ReadOnly; |
| 2832 | |
| 2833 | let call_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0)); |
| 2834 | let cc = call_count.clone(); |
| 2835 | |
| 2836 | let result: RetryResult<i32> = with_retry( |
| 2837 | &config, |
| 2838 | || { |
| 2839 | cc.fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 2840 | async { |
| 2841 | Err(LlmError::ServerError { |
| 2842 | status: 500, |
| 2843 | message: "persistent error".to_string(), |
| 2844 | }) |
| 2845 | } |
| 2846 | }, |
| 2847 | None, |
| 2848 | ) |
| 2849 | .await; |
| 2850 | |
| 2851 | assert!(result.is_err()); |
| 2852 | let err = result.unwrap_err(); |
| 2853 | assert_eq!(err.attempts, 3); // 1 initial + 2 retries |
| 2854 | assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 3); |
| 2855 | } |
| 2856 | |
| 2857 | #[tokio::test] |
| 2858 | async fn test_with_retry_callback() { |
| 2859 | let mut config = RetryConfig::new() |
| 2860 | .with_max_retries(2) |
| 2861 | .with_initial_delay(0.01); |
| 2862 | config.operation = RetryOperation::ReadOnly; |
| 2863 | |
| 2864 | let callback_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0)); |
| 2865 | let cc = callback_count.clone(); |
| 2866 | |
| 2867 | let _: RetryResult<i32> = with_retry( |
| 2868 | &config, |
| 2869 | || async { |
| 2870 | Err(LlmError::ServerError { |
| 2871 | status: 500, |
| 2872 | message: "error".to_string(), |
| 2873 | }) |
| 2874 | }, |
| 2875 | Some(Box::new(move |_err, _attempt, _delay| { |
| 2876 | cc.fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 2877 | })), |
| 2878 | ) |
| 2879 | .await; |
| 2880 | |
| 2881 | // Callback called once per retry (not for the final failure) |
| 2882 | assert_eq!(callback_count.load(std::sync::atomic::Ordering::SeqCst), 2); |
| 2883 | } |
| 2884 | |
| 2885 | #[test] |
| 2886 | fn test_retry_error_display() { |
| 2887 | let err = RetryError { |
| 2888 | last_error: LlmError::ServerError { |
| 2889 | status: 500, |
| 2890 | message: "internal error".to_string(), |
| 2891 | }, |
| 2892 | attempts: 4, |
| 2893 | total_time: Duration::from_secs(10), |
| 2894 | }; |
| 2895 | |
| 2896 | let display = format!("{err}"); |
| 2897 | assert!(display.contains("4 attempts")); |
| 2898 | assert!(display.contains("10")); |
| 2899 | assert!(display.contains("Server error")); |
| 2900 | } |
| 2901 | |
| 2902 | #[test] |
| 2903 | fn test_opencode_zen_free_limit_hint_explains_client_restriction() { |
| 2904 | let message = "Free usage limit reached. Free models work in OpenCode (https://opencode.ai); subscribe to OpenCode Go to keep going: https://opencode.ai/go"; |
| 2905 | let rendered = LlmError::QuotaWindow { |
| 2906 | message: message.into(), |
| 2907 | retry_after: Some(Duration::from_secs(78867)), |
| 2908 | transmission: RequestTransmission::Rejected, |
| 2909 | } |
| 2910 | .to_string(); |
| 2911 | assert!(rendered.contains("*-free"), "{rendered}"); |
| 2912 | assert!(rendered.contains("third-party clients"), "{rendered}"); |
| 2913 | assert!(rendered.contains("paid OpenCode Zen model"), "{rendered}"); |
| 2914 | assert_eq!( |
| 2915 | rendered |
| 2916 | .matches("codewhale auth set --provider opencode-go") |
| 2917 | .count(), |
| 2918 | 1, |
| 2919 | "{rendered}" |
| 2920 | ); |
| 2921 | |
| 2922 | let wrapped = LlmError::RateLimited { |
| 2923 | message: rendered.clone(), |
| 2924 | retry_after: None, |
| 2925 | } |
| 2926 | .to_string(); |
| 2927 | assert_eq!( |
| 2928 | wrapped |
| 2929 | .matches("codewhale auth set --provider opencode-go") |
| 2930 | .count(), |
| 2931 | 1, |
| 2932 | "{wrapped}" |
| 2933 | ); |
| 2934 | |
| 2935 | let generic = LlmError::RateLimited { |
| 2936 | message: "Free usage limit reached".into(), |
| 2937 | retry_after: None, |
| 2938 | } |
| 2939 | .to_string(); |
| 2940 | assert!(!generic.contains("OpenCode"), "{generic}"); |
| 2941 | } |
| 2942 | |
| 2943 | #[test] |
| 2944 | fn single_element_array_error_envelope_extracts_message_and_quota_code() { |
| 2945 | let google_err = serde_json::json!([{ |
| 2946 | "error": { |
| 2947 | "code": 400, |
| 2948 | "message": "Function call is missing a thought_signature in functionCall parts.", |
| 2949 | "status": "INVALID_ARGUMENT" |
| 2950 | } |
| 2951 | }]) |
| 2952 | .to_string(); |
| 2953 | assert_eq!( |
| 2954 | extract_json_error_message(&google_err).as_deref(), |
| 2955 | Some("Function call is missing a thought_signature in functionCall parts.") |
| 2956 | ); |
| 2957 | |
| 2958 | let google_quota = serde_json::json!([{ |
| 2959 | "error": { |
| 2960 | "code": "quota_exceeded", |
| 2961 | "message": "Quota exceeded for metric.", |
| 2962 | "details": [{ |
| 2963 | "@type": "type.googleapis.com/google.rpc.RetryInfo", |
| 2964 | "retryDelay": "42s" |
| 2965 | }] |
| 2966 | } |
| 2967 | }]) |
| 2968 | .to_string(); |
| 2969 | assert_eq!( |
| 2970 | explicit_quota_code(&google_quota).as_deref(), |
| 2971 | Some("quota_exceeded") |
| 2972 | ); |
| 2973 | assert_eq!( |
| 2974 | rate_limit::body_delay(&google_quota), |
| 2975 | Some(Duration::from_secs(42)) |
| 2976 | ); |
| 2977 | } |
| 2978 | } |
| 2979 |