| 1 | use super::*; |
| 2 | use crate::llm_client::{RetryConfig, RetryResult, with_retry}; |
| 3 | use std::sync::{ |
| 4 | Arc, |
| 5 | atomic::{AtomicU32, Ordering}, |
| 6 | }; |
| 7 | |
| 8 | fn refused(hint: Option<Duration>) -> LlmError { |
| 9 | LlmError::RateLimited { |
| 10 | message: "fixture refusal".into(), |
| 11 | retry_after: hint, |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | #[test] |
| 16 | fn server_minima_and_provider_codes() { |
| 17 | assert_eq!(server_delay("86400"), Some(Duration::from_secs(86400))); |
| 18 | for invalid in ["-1", "NaN", "inf", "1e300", "bad"] { |
| 19 | assert_eq!(server_delay(invalid), None); |
| 20 | } |
| 21 | let date = chrono::Utc::now() + chrono::Duration::hours(1); |
| 22 | let parsed = server_delay(&date.to_rfc2822()).unwrap(); |
| 23 | assert!(parsed >= Duration::from_secs(3598) && parsed <= Duration::from_secs(3600)); |
| 24 | let raw = r#"{"error":{"code":"insufficient_quota","message":"TPM exceeded"}}"#; |
| 25 | assert!(matches!( |
| 26 | provider_error("dashscope", 429, raw, "safe", None), |
| 27 | Some(LlmError::RateLimited { .. }) |
| 28 | )); |
| 29 | assert!(provider_error("openai", 429, raw, "safe", None).is_none()); |
| 30 | assert!(matches!( |
| 31 | LlmError::from_http_response(429, raw), |
| 32 | LlmError::QuotaExhausted(_) |
| 33 | )); |
| 34 | let raw = r#"{"base_resp":{"status_code":1002,"status_msg":"retry in 30s"}}"#; |
| 35 | assert_eq!( |
| 36 | provider_error("minimax", 429, raw, "safe", Some(Duration::from_secs(2))) |
| 37 | .unwrap() |
| 38 | .suggested_retry_delay(), |
| 39 | Some(Duration::from_secs(30)) |
| 40 | ); |
| 41 | for raw in [ |
| 42 | r#"{"base_resp":{"status_code":1002,"status_msg":"retry in 7200s"}}"#, |
| 43 | r#"{"error":{"code":1002,"details":[{"retryDelay":"7200s"}]}}"#, |
| 44 | ] { |
| 45 | assert_eq!( |
| 46 | provider_error("minimax", 429, raw, "safe", None) |
| 47 | .unwrap() |
| 48 | .suggested_retry_delay(), |
| 49 | Some(Duration::from_secs(7200)) |
| 50 | ); |
| 51 | } |
| 52 | for (provider, code, expected) in [ |
| 53 | ("minimax", 1002, "retry"), |
| 54 | ("minimax", 1008, "billing"), |
| 55 | ("minimax", 1039, "input"), |
| 56 | ("minimax", 2045, "window"), |
| 57 | ("zai", 1308, "window"), |
| 58 | ("zai", 1302, "retry"), |
| 59 | ] { |
| 60 | let raw = serde_json::json!({"error":{"code":code,"message":"fixture"}}).to_string(); |
| 61 | let error = provider_error(provider, 429, &raw, "safe", None).unwrap(); |
| 62 | if expected == "window" { |
| 63 | assert_eq!( |
| 64 | error.transmission(), |
| 65 | super::super::RequestTransmission::Rejected |
| 66 | ); |
| 67 | assert!(!error.is_retryable()); |
| 68 | assert!(!error.to_string().contains("checkpoint retained")); |
| 69 | let envelope = codewhale_error_taxonomy::ErrorEnvelope::from( |
| 70 | provider_error(provider, 429, &raw, "safe", None).unwrap(), |
| 71 | ); |
| 72 | assert!(!envelope.recoverable); |
| 73 | } |
| 74 | assert!( |
| 75 | match expected { |
| 76 | "retry" => matches!(error, LlmError::RateLimited { .. }), |
| 77 | "billing" => matches!(error, LlmError::QuotaExhausted(_)), |
| 78 | "window" => matches!(error, LlmError::QuotaWindow { .. }), |
| 79 | _ => matches!(error, LlmError::InvalidRequest { .. }), |
| 80 | }, |
| 81 | "{provider}/{code}: {error:?}" |
| 82 | ); |
| 83 | } |
| 84 | assert_eq!( |
| 85 | body_delay(r#"{"error":{"retry_after":300}}"#), |
| 86 | Some(Duration::from_secs(300)) |
| 87 | ); |
| 88 | assert_eq!( |
| 89 | body_delay(r#"{"error":{"retryDelay":"120s"}}"#), |
| 90 | Some(Duration::from_secs(120)) |
| 91 | ); |
| 92 | let window = provider_error( |
| 93 | "minimax", |
| 94 | 200, |
| 95 | r#"{"base_resp":{"status_code":2045,"status_msg":"weekly usage limit reached"}}"#, |
| 96 | "safe", |
| 97 | Some(Duration::from_secs(7200)), |
| 98 | ) |
| 99 | .unwrap(); |
| 100 | assert!(matches!(window, LlmError::QuotaWindow { .. })); |
| 101 | assert_eq!( |
| 102 | window.suggested_retry_delay(), |
| 103 | Some(Duration::from_secs(7200)) |
| 104 | ); |
| 105 | let reset = (chrono::Utc::now() + chrono::Duration::hours(5)).timestamp(); |
| 106 | let hint = |
| 107 | body_delay(&serde_json::json!({"error":{"next_flush_time":reset}}).to_string()).unwrap(); |
| 108 | assert!(hint > Duration::from_secs(17998)); |
| 109 | } |
| 110 | |
| 111 | #[test] |
| 112 | fn policy_validation_and_equal_jitter() { |
| 113 | assert!(serde_json::from_str::<RateLimitRetryPolicy>(r#"{"max_attempts":0}"#).is_err()); |
| 114 | assert!( |
| 115 | serde_json::from_str::<RateLimitRetryPolicy>( |
| 116 | r#"{"initial_delay_secs":70,"max_delay_secs":60}"# |
| 117 | ) |
| 118 | .is_err() |
| 119 | ); |
| 120 | let p = RateLimitRetryPolicy::default(); |
| 121 | assert_eq!(p.max_attempts, 20); |
| 122 | assert_eq!(p.recovery_budget_secs, 600); |
| 123 | for n in 0..100 { |
| 124 | let delay = retry_delay(&p, n); |
| 125 | let base = (5u64.saturating_mul(2u64.saturating_pow(n.min(63)))).min(60); |
| 126 | assert!( |
| 127 | delay >= Duration::from_secs(base).div_f64(2.0) && delay <= Duration::from_secs(base) |
| 128 | ); |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | #[tokio::test(start_paused = true)] |
| 133 | async fn rate_budget_is_independent_from_transport_retries() { |
| 134 | let config = RetryConfig { |
| 135 | max_retries: 0, |
| 136 | rate_limit: RateLimitRetryPolicy { |
| 137 | max_attempts: 3, |
| 138 | ..Default::default() |
| 139 | }, |
| 140 | ..Default::default() |
| 141 | }; |
| 142 | let calls = AtomicU32::new(0); |
| 143 | let result: RetryResult<()> = with_retry( |
| 144 | &config, |
| 145 | || async { |
| 146 | calls.fetch_add(1, Ordering::SeqCst); |
| 147 | Err(refused(None)) |
| 148 | }, |
| 149 | None, |
| 150 | ) |
| 151 | .await; |
| 152 | assert_eq!(result.unwrap_err().attempts, 3); |
| 153 | assert_eq!(calls.load(Ordering::SeqCst), 3); |
| 154 | } |
| 155 | |
| 156 | #[tokio::test(start_paused = true)] |
| 157 | async fn long_hints_and_quota_windows_park_without_early_retry() { |
| 158 | let mut config = RetryConfig::default(); |
| 159 | config.rate_limit.recovery_budget_secs = 7200; |
| 160 | for (window, enabled) in [(false, true), (true, true), (false, false), (true, false)] { |
| 161 | config.enabled = enabled; |
| 162 | let calls = AtomicU32::new(0); |
| 163 | let start = tokio::time::Instant::now(); |
| 164 | let result: RetryResult<()> = with_retry( |
| 165 | &config, |
| 166 | || async { |
| 167 | calls.fetch_add(1, Ordering::SeqCst); |
| 168 | Err(if window { |
| 169 | LlmError::QuotaWindow { |
| 170 | message: "window".into(), |
| 171 | retry_after: Some(Duration::from_secs(2)), |
| 172 | transmission: super::super::RequestTransmission::Rejected, |
| 173 | } |
| 174 | } else { |
| 175 | refused(Some(Duration::from_secs(86400))) |
| 176 | }) |
| 177 | }, |
| 178 | None, |
| 179 | ) |
| 180 | .await; |
| 181 | assert!(matches!( |
| 182 | result.unwrap_err().last_error, |
| 183 | LlmError::QuotaWindow { .. } |
| 184 | )); |
| 185 | assert_eq!(calls.load(Ordering::SeqCst), 1); |
| 186 | assert_eq!(start.elapsed(), Duration::ZERO); |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | #[tokio::test(start_paused = true)] |
| 191 | async fn active_work_deadline_excludes_backoff_and_cancellation_drops_retries() { |
| 192 | assert!( |
| 193 | active_timeout(Duration::from_secs(3), async { |
| 194 | wait(Duration::from_secs(30)).await; |
| 195 | tokio::time::sleep(Duration::from_secs(2)).await; |
| 196 | }) |
| 197 | .await |
| 198 | .is_ok() |
| 199 | ); |
| 200 | assert!( |
| 201 | active_timeout( |
| 202 | Duration::from_secs(3), |
| 203 | tokio::time::sleep(Duration::from_secs(5)) |
| 204 | ) |
| 205 | .await |
| 206 | .is_err() |
| 207 | ); |
| 208 | let calls = Arc::new(AtomicU32::new(0)); |
| 209 | let count = calls.clone(); |
| 210 | let task = tokio::spawn(async move { |
| 211 | let _: RetryResult<()> = with_retry( |
| 212 | &RetryConfig::default(), |
| 213 | || async { |
| 214 | count.fetch_add(1, Ordering::SeqCst); |
| 215 | Err(refused(None)) |
| 216 | }, |
| 217 | None, |
| 218 | ) |
| 219 | .await; |
| 220 | }); |
| 221 | tokio::task::yield_now().await; |
| 222 | task.abort(); |
| 223 | let _ = task.await; |
| 224 | tokio::time::advance(Duration::from_secs(1000)).await; |
| 225 | assert_eq!(calls.load(Ordering::SeqCst), 1); |
| 226 | } |
| 227 | |
| 228 | #[tokio::test] |
| 229 | async fn native_json_envelopes_are_classified_before_model_parsing() { |
| 230 | let make = |body: &str| { |
| 231 | reqwest::Response::from( |
| 232 | http::Response::builder() |
| 233 | .header("content-type", "application/json") |
| 234 | .body(reqwest::Body::from(body.to_owned())) |
| 235 | .unwrap(), |
| 236 | ) |
| 237 | }; |
| 238 | let error = inspect_json_envelope( |
| 239 | "minimax", |
| 240 | make(r#"{"base_resp":{"status_code":1002,"status_msg":"throttled"}}"#), |
| 241 | ) |
| 242 | .await |
| 243 | .unwrap_err(); |
| 244 | assert!(matches!(error, LlmError::RateLimited { .. })); |
| 245 | let error = inspect_json_envelope( |
| 246 | "zai", |
| 247 | make(r#"[{"error":{"code":1308,"details":[{"retryDelay":"42s"}]}}]"#), |
| 248 | ) |
| 249 | .await |
| 250 | .unwrap_err(); |
| 251 | assert!(matches!(error, LlmError::QuotaWindow { .. })); |
| 252 | assert_eq!(error.suggested_retry_delay(), Some(Duration::from_secs(42))); |
| 253 | let body = r#"{"base_resp":{"status_code":0},"choices":[]}"#; |
| 254 | let response = inspect_json_envelope("minimax", make(body)).await.unwrap(); |
| 255 | assert_eq!(response.text().await.unwrap(), body); |
| 256 | } |
| 257 | |
| 258 | #[tokio::test(start_paused = true)] |
| 259 | async fn successful_json_refusal_preserves_header_minimum_and_disclosure() { |
| 260 | let response = reqwest::Response::from(http::Response::builder() |
| 261 | .header("content-type", "Application/JSON; charset=utf-8") |
| 262 | .header("retry-after", "3600") |
| 263 | .body(reqwest::Body::from(r#"{"base_resp":{"status_code":1002,"status_msg":"fixture-secret"},"retry_after":7200}"#)).unwrap()); |
| 264 | let error = inspect_json_envelope_with_disclosure("minimax", response, None, |_, body| { |
| 265 | body.replace("fixture-secret", "[redacted]") |
| 266 | }) |
| 267 | .await |
| 268 | .unwrap_err(); |
| 269 | assert_eq!( |
| 270 | error.suggested_retry_delay(), |
| 271 | Some(Duration::from_secs(7200)) |
| 272 | ); |
| 273 | assert!(!error.to_string().contains("fixture-secret")); |
| 274 | // A larger/header-only minimum must also survive; the body-max case |
| 275 | // above alone would not detect a dropped Retry-After header. |
| 276 | let response = reqwest::Response::from( |
| 277 | http::Response::builder() |
| 278 | .header("content-type", "application/json") |
| 279 | .header("retry-after", "3600") |
| 280 | .body(reqwest::Body::from( |
| 281 | r#"{"base_resp":{"status_code":1002,"status_msg":"throttled"}}"#, |
| 282 | )) |
| 283 | .unwrap(), |
| 284 | ); |
| 285 | let header_only = inspect_json_envelope("minimax", response) |
| 286 | .await |
| 287 | .unwrap_err(); |
| 288 | assert_eq!( |
| 289 | header_only.suggested_retry_delay(), |
| 290 | Some(Duration::from_secs(3600)) |
| 291 | ); |
| 292 | let config = RetryConfig::default(); |
| 293 | let mut refusal = Some(error); |
| 294 | let calls = AtomicU32::new(0); |
| 295 | let result: RetryResult<()> = with_retry( |
| 296 | &config, |
| 297 | || { |
| 298 | calls.fetch_add(1, Ordering::SeqCst); |
| 299 | let error = refusal |
| 300 | .take() |
| 301 | .expect("long hint must not dispatch a second attempt"); |
| 302 | async move { Err(error) } |
| 303 | }, |
| 304 | None, |
| 305 | ) |
| 306 | .await; |
| 307 | assert_eq!(result.unwrap_err().attempts, 1); |
| 308 | assert_eq!(calls.load(Ordering::SeqCst), 1); |
| 309 | } |
| 310 | |
| 311 | #[tokio::test(start_paused = true)] |
| 312 | async fn long_backoff_does_not_consume_the_nonstream_active_envelope() { |
| 313 | let mut config = RetryConfig::default(); |
| 314 | config.rate_limit.recovery_budget_secs = 3600; |
| 315 | let calls = AtomicU32::new(0); |
| 316 | let result = active_timeout_total( |
| 317 | Duration::from_secs(1800), |
| 318 | with_retry( |
| 319 | &config, |
| 320 | || async { |
| 321 | if calls.fetch_add(1, Ordering::SeqCst) < 2 { |
| 322 | Err(refused(Some(Duration::from_secs(1000)))) |
| 323 | } else { |
| 324 | Ok(()) |
| 325 | } |
| 326 | }, |
| 327 | None, |
| 328 | ), |
| 329 | ) |
| 330 | .await; |
| 331 | assert!(result.unwrap().is_ok()); |
| 332 | assert_eq!(calls.load(Ordering::SeqCst), 3); |
| 333 | // Excluding waits must not disable a real active-work timeout. |
| 334 | assert!( |
| 335 | active_timeout_total( |
| 336 | Duration::from_secs(3), |
| 337 | tokio::time::sleep(Duration::from_secs(4)) |
| 338 | ) |
| 339 | .await |
| 340 | .is_err() |
| 341 | ); |
| 342 | } |
| 343 | |
| 344 | #[tokio::test(start_paused = true)] |
| 345 | async fn mixed_transport_failure_cannot_restart_expired_rate_recovery() { |
| 346 | let config = RetryConfig { |
| 347 | operation: super::super::RetryOperation::ReadOnly, |
| 348 | rate_limit: RateLimitRetryPolicy { |
| 349 | initial_delay_secs: 1, |
| 350 | max_delay_secs: 1, |
| 351 | ..Default::default() |
| 352 | }, |
| 353 | ..Default::default() |
| 354 | }; |
| 355 | let calls = AtomicU32::new(0); |
| 356 | let result: RetryResult<()> = with_retry( |
| 357 | &config, |
| 358 | || async { |
| 359 | if calls.fetch_add(1, Ordering::SeqCst) == 0 { |
| 360 | Err(refused(None)) |
| 361 | } else { |
| 362 | tokio::time::sleep(Duration::from_secs(601)).await; |
| 363 | Err(LlmError::ServerError { |
| 364 | status: 503, |
| 365 | message: "fixture".into(), |
| 366 | }) |
| 367 | } |
| 368 | }, |
| 369 | None, |
| 370 | ) |
| 371 | .await; |
| 372 | assert!(matches!( |
| 373 | result.unwrap_err().last_error, |
| 374 | LlmError::ServerError { status: 503, .. } |
| 375 | )); |
| 376 | assert_eq!(calls.load(Ordering::SeqCst), 2); |
| 377 | } |
| 378 | |
| 379 | #[test] |
| 380 | fn unknown_rate_limit_quota_code_requires_independent_billing_evidence() { |
| 381 | let hint = Some(Duration::from_secs(30)); |
| 382 | for raw in [ |
| 383 | r#"{"error":{"code":null,"type":"insufficient_quota","message":"TPM exceeded"},"retry_after":40}"#, |
| 384 | r#"{"error":{"code":"gateway_limit","error_code":"insufficient_quota","message":"TPM exceeded"},"retry_after":40}"#, |
| 385 | r#"{"error":{"code":"insufficient_quota","message":"TPM exceeded"},"retry_after":40}"#, |
| 386 | r#"{"error":{"type":"insufficient_quota","message":"quota exceeded"},"retry_after":40}"#, |
| 387 | r#"{"error_code":"insufficient_quota","message":"quota exceeded","retry_after":40}"#, |
| 388 | ] { |
| 389 | let error = provider_error("custom", 429, raw, "safe", hint).unwrap(); |
| 390 | assert!(matches!(error, LlmError::RateLimited { .. })); |
| 391 | assert_eq!(error.suggested_retry_delay(), Some(Duration::from_secs(40))); |
| 392 | assert!(!error.to_string().contains("TPM")); |
| 393 | } |
| 394 | let raw = "TPM exceeded (provider error code: insufficient_quota)"; |
| 395 | assert!(matches!( |
| 396 | provider_error("custom", 429, raw, "safe", hint), |
| 397 | Some(LlmError::RateLimited { .. }) |
| 398 | )); |
| 399 | for raw in [ |
| 400 | r#"{"error":{"code":"insufficient_quota","message":"Credit balance exhausted"}}"#, |
| 401 | r#"{"error":{"code":"insufficient_quota","message":"Billing quota has been exhausted"}}"#, |
| 402 | r#"{"error":{"code":"insufficient_quota","message":"Account quota exhausted"}}"#, |
| 403 | r#"{"error":{"code":"insufficient_quota","message":"Plan quota is exhausted"}}"#, |
| 404 | r#"{"error":{"code":"insufficient_quota","message":"TPM exceeded"},"detail":"Billing quota has been exhausted"}"#, |
| 405 | r#"{"error":{"message":"Too many requests"},"detail":"Billing quota has been exhausted"}"#, |
| 406 | r#"{"error":{"code":"gateway_limit","message":"Too many requests"},"detail":"Billing quota has been exhausted"}"#, |
| 407 | r#"{"error":{"code":"insufficient_quota","type":"billing_hard_limit_reached","message":"fixture"}}"#, |
| 408 | r#"{"error":{"code":"insufficient_quota","message":"\u4f59\u989d\u4e0d\u8db3"}}"#, |
| 409 | ] { |
| 410 | for provider in ["custom", "dashscope", "qwen"] { |
| 411 | assert!(matches!( |
| 412 | provider_error(provider, 429, raw, "safe", hint), |
| 413 | Some(LlmError::QuotaExhausted(_)) |
| 414 | )); |
| 415 | } |
| 416 | } |
| 417 | // Upstream's existing generic plan/billing guidance remains bounded when |
| 418 | // a reset hint is present; explicit billing/account exhaustion above wins. |
| 419 | let guidance = r#"{"error":{"code":"insufficient_quota","message":"You exceeded your current quota. Check plan and billing"}}"#; |
| 420 | assert!(matches!( |
| 421 | provider_error("custom", 429, guidance, "safe", hint), |
| 422 | Some(LlmError::RateLimited { .. }) |
| 423 | )); |
| 424 | assert!(matches!( |
| 425 | provider_error("custom", 429, guidance, "safe", None), |
| 426 | Some(LlmError::QuotaExhausted(_)) |
| 427 | )); |
| 428 | let raw = r#"{"error":{"code":"insufficient_quota","message":"TPM exceeded"}}"#; |
| 429 | assert!(provider_error("openai", 429, raw, "safe", hint).is_none()); |
| 430 | assert!(matches!( |
| 431 | LlmError::from_http_response(429, raw), |
| 432 | LlmError::QuotaExhausted(_) |
| 433 | )); |
| 434 | assert!(provider_error("custom", 401, raw, "safe", hint).is_none()); |
| 435 | } |
| 436 | |
| 437 | #[tokio::test(start_paused = true)] |
| 438 | async fn native_json_envelope_bounds_first_byte_idle_and_size() { |
| 439 | use futures_util::StreamExt; |
| 440 | for sent in [false, true] { |
| 441 | let prefix = futures_util::stream::iter(if sent { |
| 442 | vec![Ok::<_, std::io::Error>("{")] |
| 443 | } else { |
| 444 | vec![] |
| 445 | }); |
| 446 | let body = reqwest::Body::wrap_stream(prefix.chain(futures_util::stream::pending())); |
| 447 | let response = reqwest::Response::from( |
| 448 | http::Response::builder() |
| 449 | .header("content-type", "application/json") |
| 450 | .body(body) |
| 451 | .unwrap(), |
| 452 | ); |
| 453 | let error = inspect_json_envelope_with_disclosure( |
| 454 | "minimax", |
| 455 | response, |
| 456 | Some((Duration::from_secs(2), Duration::from_secs(3))), |
| 457 | |_, _| "safe".into(), |
| 458 | ) |
| 459 | .await |
| 460 | .unwrap_err(); |
| 461 | assert!( |
| 462 | matches!(error, LlmError::Timeout(delay) if delay == Duration::from_secs(if sent {3} else {2})) |
| 463 | ); |
| 464 | assert_eq!( |
| 465 | error.transmission(), |
| 466 | super::super::RequestTransmission::OutcomeUnknown |
| 467 | ); |
| 468 | } |
| 469 | for declared in [false, true] { |
| 470 | let body = reqwest::Body::wrap_stream(futures_util::stream::iter( |
| 471 | (0..33).map(|_| Ok::<_, std::io::Error>(vec![b' '; 1024 * 1024])), |
| 472 | )); |
| 473 | let mut response = http::Response::builder().header("content-type", "application/json"); |
| 474 | if declared { |
| 475 | response = response.header("content-length", 33 * 1024 * 1024); |
| 476 | } |
| 477 | let response = reqwest::Response::from(response.body(body).unwrap()); |
| 478 | let error = inspect_json_envelope("minimax", response) |
| 479 | .await |
| 480 | .unwrap_err(); |
| 481 | assert!(matches!(error, LlmError::ParseError(ref message) if message.contains("32 MiB"))); |
| 482 | assert_eq!( |
| 483 | error.transmission(), |
| 484 | super::super::RequestTransmission::OutcomeUnknown |
| 485 | ); |
| 486 | } |
| 487 | } |
| 488 |