| 1 | use super::*; |
| 2 | |
| 3 | #[test] |
| 4 | fn missing_google_thought_signature_errors_explain_recovery() { |
| 5 | for detail in [ |
| 6 | "Function call is missing a thought_signature in functionCall parts.", |
| 7 | "Function call is missing thought_signature.", |
| 8 | "The thought_signature is missing from the function call.", |
| 9 | ] { |
| 10 | for body in [ |
| 11 | detail.to_string(), |
| 12 | serde_json::json!({"error": {"message": detail, "code": 400}}).to_string(), |
| 13 | serde_json::json!({"error": "Bad Request", "message": detail}).to_string(), |
| 14 | ] { |
| 15 | let message = sanitize_http_error_body(Some("Custom"), 400, &body); |
| 16 | assert!(message.contains("built-in `google` provider"), "{message}"); |
| 17 | assert!(message.contains("start a new session"), "{message}"); |
| 18 | assert!(message.contains(detail), "provider detail must survive"); |
| 19 | assert_eq!(sanitize_http_error_body(None, 400, &message), message); |
| 20 | let error = LlmError::from_http_response(400, &message); |
| 21 | assert!(matches!( |
| 22 | error, |
| 23 | LlmError::InvalidRequest { status: 400, .. } |
| 24 | )); |
| 25 | assert!(!error.is_retryable()); |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | #[test] |
| 31 | fn google_thought_signature_hint_requires_a_missing_signature_400() { |
| 32 | for (status, detail) in [ |
| 33 | (400, "Invalid model name"), |
| 34 | (400, "Invalid thought_signature in functionCall parts"), |
| 35 | (400, "Unsupported parameter: thought_signature"), |
| 36 | ( |
| 37 | 401, |
| 38 | "Function call is missing a thought_signature in functionCall parts.", |
| 39 | ), |
| 40 | ( |
| 41 | 429, |
| 42 | "Function call is missing a thought_signature in functionCall parts.", |
| 43 | ), |
| 44 | ( |
| 45 | 500, |
| 46 | "Function call is missing a thought_signature in functionCall parts.", |
| 47 | ), |
| 48 | ] { |
| 49 | let body = serde_json::json!({"error": {"message": detail}}).to_string(); |
| 50 | assert_eq!( |
| 51 | sanitize_http_error_body(Some("Custom"), status, &body), |
| 52 | detail |
| 53 | ); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | #[test] |
| 58 | fn google_thought_signature_hint_keeps_large_provider_errors_bounded() { |
| 59 | let body = format!( |
| 60 | "Function call is missing a thought_signature in functionCall parts. {}", |
| 61 | "界".repeat(3_000) |
| 62 | ); |
| 63 | let message = sanitize_http_error_body(None, 400, &body); |
| 64 | assert!(message.contains("start a new session")); |
| 65 | assert!(message.chars().count() < 2_000); |
| 66 | assert_eq!(sanitize_http_error_body(None, 400, &message), message); |
| 67 | } |
| 68 | |
| 69 | #[test] |
| 70 | fn google_thought_signature_hint_preserves_quota_and_html_handling() { |
| 71 | let detail = "Function call is missing a thought_signature in functionCall parts."; |
| 72 | let body = serde_json::json!({ |
| 73 | "error": {"message": detail, "code": "insufficient_quota"} |
| 74 | }) |
| 75 | .to_string(); |
| 76 | let message = sanitize_http_error_body(None, 400, &body); |
| 77 | assert!(matches!( |
| 78 | LlmError::from_http_response(400, &message), |
| 79 | LlmError::QuotaExhausted(_) |
| 80 | )); |
| 81 | let html = format!("<!doctype html><html><body>{detail}</body></html>"); |
| 82 | let message = sanitize_http_error_body(None, 400, &html); |
| 83 | assert!(message.contains("HTML error page")); |
| 84 | assert!(!message.contains("<html>")); |
| 85 | } |
| 86 | |
| 87 | #[test] |
| 88 | fn retryability_distinguishes_transient_failures_from_durable_failures() { |
| 89 | for error in [ |
| 90 | LlmError::RateLimited { |
| 91 | message: "too many requests".into(), |
| 92 | retry_after: None, |
| 93 | }, |
| 94 | LlmError::ConnectError { |
| 95 | message: "refused".into(), |
| 96 | transient: true, |
| 97 | timed_out: false, |
| 98 | }, |
| 99 | ] { |
| 100 | assert!(error.is_retryable(), "expected transient error: {error}"); |
| 101 | } |
| 102 | for error in [ |
| 103 | LlmError::ServerError { |
| 104 | status: 500, |
| 105 | message: "internal error".into(), |
| 106 | }, |
| 107 | LlmError::NetworkError("connection refused".into()), |
| 108 | LlmError::Timeout(Duration::from_secs(30)), |
| 109 | LlmError::authentication_error("invalid key"), |
| 110 | LlmError::AuthorizationError("blocked".into()), |
| 111 | LlmError::InvalidRequest { |
| 112 | status: 400, |
| 113 | message: "bad json".into(), |
| 114 | }, |
| 115 | LlmError::ContentPolicyError("unsafe content".into()), |
| 116 | LlmError::ContextLengthError("too long".into()), |
| 117 | ] { |
| 118 | assert!(!error.is_retryable(), "expected durable error: {error}"); |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | #[test] |
| 123 | fn quota_window_display_prints_reset_time_as_plain_text() { |
| 124 | let windowed = LlmError::QuotaWindow { |
| 125 | message: "Free usage limit reached".into(), |
| 126 | retry_after: Some(Duration::from_secs(70168)), |
| 127 | transmission: RequestTransmission::Rejected, |
| 128 | } |
| 129 | .to_string(); |
| 130 | assert!(windowed.contains("resets in 19h29m"), "{windowed}"); |
| 131 | assert!(windowed.contains("automatic retry stopped"), "{windowed}"); |
| 132 | |
| 133 | let open_ended = LlmError::QuotaWindow { |
| 134 | message: "Free usage limit reached".into(), |
| 135 | retry_after: None, |
| 136 | transmission: RequestTransmission::Rejected, |
| 137 | } |
| 138 | .to_string(); |
| 139 | assert!(!open_ended.contains("reset"), "{open_ended}"); |
| 140 | assert!( |
| 141 | open_ended.contains("automatic retry stopped"), |
| 142 | "{open_ended}" |
| 143 | ); |
| 144 | |
| 145 | for text in [&windowed, &open_ended] { |
| 146 | assert!(!text.contains("Some("), "{text}"); |
| 147 | assert!(!text.contains("None"), "{text}"); |
| 148 | } |
| 149 | |
| 150 | let hinted = LlmError::QuotaWindow { |
| 151 | message: "OpenCode Go free usage limit reached".into(), |
| 152 | retry_after: Some(Duration::from_secs(70168)), |
| 153 | transmission: RequestTransmission::Rejected, |
| 154 | } |
| 155 | .to_string(); |
| 156 | assert_eq!( |
| 157 | hinted |
| 158 | .matches("codewhale auth set --provider opencode-go") |
| 159 | .count(), |
| 160 | 1, |
| 161 | "{hinted}" |
| 162 | ); |
| 163 | |
| 164 | let rate_limited = LlmError::RateLimited { |
| 165 | message: "OpenCode Go free usage limit reached".into(), |
| 166 | retry_after: None, |
| 167 | } |
| 168 | .to_string(); |
| 169 | assert_eq!( |
| 170 | rate_limited |
| 171 | .matches("codewhale auth set --provider opencode-go") |
| 172 | .count(), |
| 173 | 1, |
| 174 | "{rate_limited}" |
| 175 | ); |
| 176 | |
| 177 | let already_hinted = LlmError::QuotaWindow { |
| 178 | message: hinted.clone(), |
| 179 | retry_after: Some(Duration::from_secs(70168)), |
| 180 | transmission: RequestTransmission::Rejected, |
| 181 | } |
| 182 | .to_string(); |
| 183 | assert_eq!( |
| 184 | already_hinted |
| 185 | .matches("codewhale auth set --provider opencode-go") |
| 186 | .count(), |
| 187 | 1, |
| 188 | "{already_hinted}" |
| 189 | ); |
| 190 | } |
| 191 | |
| 192 | #[test] |
| 193 | fn http_response_boundary_classifies_status_contract() { |
| 194 | for status in [408, 409, 499, 500, 502, 503, 504] { |
| 195 | let error = LlmError::from_http_response( |
| 196 | status, |
| 197 | r#"{"error":{"code":"usage_limit_reached","message":"context length,429 and HTTP413"}}"#, |
| 198 | ); |
| 199 | assert_eq!(error.transmission(), RequestTransmission::OutcomeUnknown); |
| 200 | assert!(!error.is_retryable()); |
| 201 | if status >= 499 { |
| 202 | assert!(matches!(error, LlmError::ServerError { .. })); |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | let body = LlmError::from_http_response(413, "maximum images exceeded model token limit"); |
| 207 | assert!(matches!(body, LlmError::InvalidRequest { status: 413, .. })); |
| 208 | assert!(!body.is_retryable()); |
| 209 | assert!(matches!( |
| 210 | LlmError::from_http_response(429, "rate limit exceeded"), |
| 211 | LlmError::RateLimited { .. } |
| 212 | )); |
| 213 | assert!(matches!( |
| 214 | LlmError::from_http_response(401, "invalid api key"), |
| 215 | LlmError::AuthenticationError(_) |
| 216 | )); |
| 217 | assert!(matches!( |
| 218 | LlmError::from_http_response(403, "forbidden"), |
| 219 | LlmError::AuthorizationError(_) |
| 220 | )); |
| 221 | assert!(matches!( |
| 222 | LlmError::from_http_response(403, "invalid api key"), |
| 223 | LlmError::AuthenticationError(_) |
| 224 | )); |
| 225 | let cancelled = LlmError::from_http_response(499, "upstream request cancelled"); |
| 226 | assert!(matches!( |
| 227 | &cancelled, |
| 228 | LlmError::ServerError { status: 499, .. } |
| 229 | )); |
| 230 | assert!(!cancelled.is_retryable()); |
| 231 | assert!(cancelled.is_retryable_for(RetryOperation::ReadOnly)); |
| 232 | assert!(matches!( |
| 233 | LlmError::from_http_response(500, "internal server error"), |
| 234 | LlmError::ServerError { status: 500, .. } |
| 235 | )); |
| 236 | assert!(matches!( |
| 237 | LlmError::from_http_response(503, "service unavailable"), |
| 238 | LlmError::ServerError { status: 503, .. } |
| 239 | )); |
| 240 | assert!(matches!( |
| 241 | LlmError::from_http_response(400, "context_length_exceeded"), |
| 242 | LlmError::ContextLengthError(_) |
| 243 | )); |
| 244 | assert!(matches!( |
| 245 | LlmError::from_http_response(400, "content_policy_violation"), |
| 246 | LlmError::ContentPolicyError(_) |
| 247 | )); |
| 248 | assert!(matches!( |
| 249 | LlmError::from_http_response(400, "invalid json"), |
| 250 | LlmError::InvalidRequest { status: 400, .. } |
| 251 | )); |
| 252 | for context in [ |
| 253 | "This model's maximum context length is 131072 tokens.", |
| 254 | "prompt is too long: 250000 tokens > 200000 maximum", |
| 255 | "input tokens exceed the configured limit", |
| 256 | "The input token count (2000000) exceeds the maximum number of tokens allowed (1048576).", |
| 257 | // xAI, Moonshot, Anthropic and Bedrock wording. |
| 258 | "This model's maximum prompt length is 131072 but the request contains 200000 tokens.", |
| 259 | "Invalid request: Your request exceeded model token limit: 262144", |
| 260 | "input length and `max_tokens` exceed context limit: 187254 + 20000 > 204798", |
| 261 | "Input is too long for requested model.", |
| 262 | ] { |
| 263 | assert!( |
| 264 | matches!( |
| 265 | LlmError::from_http_response(400, context), |
| 266 | LlmError::ContextLengthError(_) |
| 267 | ), |
| 268 | "{context}" |
| 269 | ); |
| 270 | } |
| 271 | for invalid in [ |
| 272 | "max_tokens must be less than or equal to 8192", |
| 273 | "Invalid 'messages[1].name': string too long. Expected a maximum length of 64.", |
| 274 | "invalid token in JSON body", |
| 275 | ] { |
| 276 | assert!( |
| 277 | matches!( |
| 278 | LlmError::from_http_response(400, invalid), |
| 279 | LlmError::InvalidRequest { status: 400, .. } |
| 280 | ), |
| 281 | "{invalid}" |
| 282 | ); |
| 283 | } |
| 284 | // "Unsupported parameter: max_output_tokens" names a *token* field, which |
| 285 | // the generic keyword rules misread as a context-window overflow. It is a |
| 286 | // request-shape error, and retrying or compacting cannot fix it. |
| 287 | assert!(matches!( |
| 288 | LlmError::from_http_response( |
| 289 | 400, |
| 290 | "{\"error\":{\"code\":\"unsupported_parameter\",\"message\":\"Unsupported parameter: max_output_tokens\"}}" |
| 291 | ), |
| 292 | LlmError::InvalidRequest { status: 400, .. } |
| 293 | )); |
| 294 | assert!(matches!( |
| 295 | LlmError::from_http_response( |
| 296 | 400, |
| 297 | "{\"error\":{\"type\":\"invalid_request_error\",\"message\":\"Unsupported parameter: temperature\"}}" |
| 298 | ), |
| 299 | LlmError::InvalidRequest { status: 400, .. } |
| 300 | )); |
| 301 | } |
| 302 | |
| 303 | #[test] |
| 304 | fn explicit_400_402_and_429_quota_responses_are_typed_and_non_retryable() { |
| 305 | for (status, body) in [ |
| 306 | ( |
| 307 | 400, |
| 308 | r#"{"error":{"code":"insufficient_quota","message":"You exceeded your current quota"}}"#, |
| 309 | ), |
| 310 | ( |
| 311 | 429, |
| 312 | r#"{"error":{"type":"insufficient_quota","message":"Billing limit reached"}}"#, |
| 313 | ), |
| 314 | ( |
| 315 | 402, |
| 316 | r#"{"error":{"code":"billing_hard_limit_reached","message":"Payment required"}}"#, |
| 317 | ), |
| 318 | ( |
| 319 | 429, |
| 320 | "You exceeded your current quota. Please check your plan and billing details.", |
| 321 | ), |
| 322 | (429, "Account quota exhausted"), |
| 323 | ( |
| 324 | 429, |
| 325 | "You've reached your weekly usage limit for your plan. Your limit resets at 12:00.", |
| 326 | ), |
| 327 | ( |
| 328 | 429, |
| 329 | "You've reached your 5-hour usage limit. Your limit resets at 12:00.", |
| 330 | ), |
| 331 | (429, "You exceeded your five-hour usage limit."), |
| 332 | ( |
| 333 | 429, |
| 334 | "Your plan usage limit has been reached; the limit resets tomorrow.", |
| 335 | ), |
| 336 | ] { |
| 337 | let error = LlmError::from_http_response(status, body); |
| 338 | assert!(matches!(error, LlmError::QuotaExhausted(_))); |
| 339 | assert!(!error.is_retryable()); |
| 340 | } |
| 341 | |
| 342 | let raw = r#"{"error":{"code":"billing_hard_limit_reached","message":"Account unavailable"}}"#; |
| 343 | let safe = sanitize_http_error_body(Some("fixture"), 429, raw); |
| 344 | assert!(matches!( |
| 345 | LlmError::from_http_response(429, &safe), |
| 346 | LlmError::QuotaExhausted(_) |
| 347 | )); |
| 348 | } |
| 349 | |
| 350 | #[test] |
| 351 | fn chatgpt_usage_limit_is_quota_and_carries_account_guidance() { |
| 352 | // Shape of the ChatGPT Codex backend's subscription-window 429, as |
| 353 | // openai/codex `codex-api/src/api_bridge.rs` parses it. |
| 354 | let raw = r#"{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_at":1790000000}}"#; |
| 355 | let safe = sanitize_http_error_body(Some("OpenAI Codex"), 429, raw); |
| 356 | let error = LlmError::from_http_response(429, &safe); |
| 357 | assert!(!error.is_retryable()); |
| 358 | let LlmError::QuotaExhausted(evidence) = error else { |
| 359 | panic!("usage_limit_reached must be typed quota, got {error:?}"); |
| 360 | }; |
| 361 | let rendered = LlmError::QuotaExhausted(evidence.with_guidance( |
| 362 | "This limit belongs to the ChatGPT account a@example.com (plus). Run `codewhale auth chatgpt`.", |
| 363 | )) |
| 364 | .to_string(); |
| 365 | assert!( |
| 366 | rendered.contains("The usage limit has been reached"), |
| 367 | "{rendered}" |
| 368 | ); |
| 369 | assert!(rendered.contains("a@example.com (plus)"), "{rendered}"); |
| 370 | assert!(rendered.contains("`codewhale auth chatgpt`"), "{rendered}"); |
| 371 | |
| 372 | // Same backend branch: the signed-in plan does not include Codex. |
| 373 | // Retrying cannot help, so it must not be a retryable rate limit. |
| 374 | let raw = |
| 375 | r#"{"error":{"type":"usage_not_included","message":"Your plan does not include Codex"}}"#; |
| 376 | let safe = sanitize_http_error_body(Some("OpenAI Codex"), 429, raw); |
| 377 | let error = LlmError::from_http_response(429, &safe); |
| 378 | assert!(!error.is_retryable()); |
| 379 | assert!(matches!(error, LlmError::QuotaExhausted(_)), "{error:?}"); |
| 380 | } |
| 381 | |
| 382 | #[test] |
| 383 | fn generic_429_stays_rate_limited_and_retryable() { |
| 384 | for body in [ |
| 385 | "Too Many Requests", |
| 386 | "Rate limit on your API quota exceeded", |
| 387 | "Requests per minute quota exceeded", |
| 388 | "usage limit reached", |
| 389 | "Requests per minute usage limit reached; limit resets in 1 second.", |
| 390 | "Quota rate limit exceeded; retry after 10 seconds", |
| 391 | ] { |
| 392 | let error = LlmError::from_http_response(429, body); |
| 393 | assert!( |
| 394 | matches!(error, LlmError::RateLimited { .. }), |
| 395 | "expected transient rate limit for {body:?}, got {error:?}" |
| 396 | ); |
| 397 | assert!(error.is_retryable()); |
| 398 | } |
| 399 | |
| 400 | let raw = r#"{"error":{"code":"RESOURCE_EXHAUSTED","message":"Rate limit on your API quota exceeded"}}"#; |
| 401 | let safe = sanitize_http_error_body(Some("fixture"), 429, raw); |
| 402 | let error = LlmError::from_http_response(429, &safe); |
| 403 | assert!(matches!(error, LlmError::RateLimited { .. })); |
| 404 | assert!(error.is_retryable()); |
| 405 | } |
| 406 | |
| 407 | #[test] |
| 408 | fn missing_google_signature_400_explains_recovery_without_widening_gateway_preflight() { |
| 409 | let message = "Function call is missing a thought_signature in functionCall parts"; |
| 410 | for body in [ |
| 411 | message.to_string(), |
| 412 | serde_json::json!({"error": {"message": message}}).to_string(), |
| 413 | format!("{message} {}", "详情".repeat(2_000)), |
| 414 | ] { |
| 415 | let safe = sanitize_http_error_body(Some("OpenAI-compatible"), 400, &body); |
| 416 | assert!(safe.contains(message)); |
| 417 | assert!(safe.contains("built-in `google` provider")); |
| 418 | assert!(safe.contains("start a new session")); |
| 419 | assert!(safe.contains("gateway")); |
| 420 | assert!( |
| 421 | safe.chars().count() <= 2_003, |
| 422 | "error bound survives the hint" |
| 423 | ); |
| 424 | } |
| 425 | for (status, body) in [ |
| 426 | (429, message), |
| 427 | (200, message), |
| 428 | (400, "Invalid thought_signature"), |
| 429 | (400, "Missing required parameter: model"), |
| 430 | ] { |
| 431 | assert_eq!(sanitize_http_error_body(None, status, body), body); |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | #[tokio::test] |
| 436 | async fn retry_loop_stops_after_one_typed_quota_failure() { |
| 437 | for (status, body) in [ |
| 438 | (429, r#"{"error":{"code":"insufficient_quota"}}"#), |
| 439 | (500, "upstream accepted then failed"), |
| 440 | (408, "request timeout"), |
| 441 | (409, "conflict"), |
| 442 | ] { |
| 443 | let mut calls = 0; |
| 444 | let result: RetryResult<i32> = with_retry( |
| 445 | &RetryConfig::default(), |
| 446 | || { |
| 447 | calls += 1; |
| 448 | async move { Err(LlmError::from_http_response(status, body)) } |
| 449 | }, |
| 450 | None, |
| 451 | ) |
| 452 | .await; |
| 453 | assert_eq!(result.unwrap_err().attempts, 1); |
| 454 | assert_eq!(calls, 1); |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | #[tokio::test] |
| 459 | async fn retry_loop_stops_after_one_authentication_failure() { |
| 460 | let mut calls = 0; |
| 461 | let result: RetryResult<i32> = with_retry( |
| 462 | &RetryConfig::default(), |
| 463 | || { |
| 464 | calls += 1; |
| 465 | async { Err(LlmError::authentication_error("bad key")) } |
| 466 | }, |
| 467 | None, |
| 468 | ) |
| 469 | .await; |
| 470 | assert!(result.is_err()); |
| 471 | assert_eq!(calls, 1); |
| 472 | } |
| 473 | |
| 474 | fn retry_receipt_observation() -> ( |
| 475 | RequestRetryObservation, |
| 476 | std::sync::Arc<std::sync::Mutex<Vec<String>>>, |
| 477 | ) { |
| 478 | let receipts = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); |
| 479 | let captured = receipts.clone(); |
| 480 | ( |
| 481 | RequestRetryObservation { |
| 482 | request_id: format!("fixture:{}", uuid::Uuid::new_v4().simple()), |
| 483 | wire_observations: Default::default(), |
| 484 | retries: std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0)), |
| 485 | emit: std::sync::Arc::new(move |message| { |
| 486 | let captured = captured.clone(); |
| 487 | Box::pin(async move { |
| 488 | captured.lock().unwrap().push(message); |
| 489 | }) |
| 490 | }), |
| 491 | }, |
| 492 | receipts, |
| 493 | ) |
| 494 | } |
| 495 | |
| 496 | fn immediate_retry_policy(max_retries: u32) -> RetryConfig { |
| 497 | RetryConfig { |
| 498 | operation: RetryOperation::ReadOnly, |
| 499 | max_retries, |
| 500 | initial_delay: 0.0, |
| 501 | jitter: false, |
| 502 | ..RetryConfig::default() |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | #[tokio::test] |
| 507 | async fn scoped_retry_records_first_transport_failure_and_recovery_without_remote_payload() { |
| 508 | let (observation, receipts) = retry_receipt_observation(); |
| 509 | let count = observation.retries.clone(); |
| 510 | let mut calls = 0; |
| 511 | let result = observe_request_retries( |
| 512 | Some(observation), |
| 513 | with_retry( |
| 514 | &immediate_retry_policy(2), |
| 515 | || { |
| 516 | calls += 1; |
| 517 | let call = calls; |
| 518 | async move { |
| 519 | if call == 1 { |
| 520 | Err(LlmError::ServerError { |
| 521 | status: 503, |
| 522 | message: "PRIVATE-PROVIDER-BODY".into(), |
| 523 | }) |
| 524 | } else { |
| 525 | Ok(17) |
| 526 | } |
| 527 | } |
| 528 | }, |
| 529 | None, |
| 530 | ), |
| 531 | ) |
| 532 | .await |
| 533 | .unwrap(); |
| 534 | assert_eq!(result, 17); |
| 535 | assert_eq!(calls, 2); |
| 536 | assert_eq!(count.load(std::sync::atomic::Ordering::Relaxed), 1); |
| 537 | assert_eq!( |
| 538 | *receipts.lock().unwrap(), |
| 539 | [ |
| 540 | "Retry attempt: HTTP 1; upstream 503; waiting 0.00s", |
| 541 | "Retry recovery: HTTP operation recovered after 2 attempts", |
| 542 | ] |
| 543 | ); |
| 544 | } |
| 545 | |
| 546 | #[tokio::test] |
| 547 | async fn scoped_retry_exhaustion_retains_typed_original_error_and_every_attempt() { |
| 548 | let (observation, receipts) = retry_receipt_observation(); |
| 549 | let count = observation.retries.clone(); |
| 550 | let mut calls = 0; |
| 551 | let result: RetryResult<()> = observe_request_retries( |
| 552 | Some(observation), |
| 553 | with_retry( |
| 554 | &immediate_retry_policy(2), |
| 555 | || { |
| 556 | calls += 1; |
| 557 | async { |
| 558 | Err(LlmError::ServerError { |
| 559 | status: 503, |
| 560 | message: "RAW-TERMINAL-PROVIDER-BODY".into(), |
| 561 | }) |
| 562 | } |
| 563 | }, |
| 564 | None, |
| 565 | ), |
| 566 | ) |
| 567 | .await; |
| 568 | let error = result.unwrap_err(); |
| 569 | assert_eq!(calls, 3); |
| 570 | assert_eq!(error.attempts, 3); |
| 571 | assert!( |
| 572 | matches!(error.last_error, LlmError::ServerError { status: 503, ref message } if message == "RAW-TERMINAL-PROVIDER-BODY") |
| 573 | ); |
| 574 | assert_eq!(count.load(std::sync::atomic::Ordering::Relaxed), 2); |
| 575 | assert_eq!( |
| 576 | *receipts.lock().unwrap(), |
| 577 | [ |
| 578 | "Retry attempt: HTTP 1; upstream 503; waiting 0.00s", |
| 579 | "Retry attempt: HTTP 2; upstream 503; waiting 0.00s", |
| 580 | "Retry exhaustion: transport request stopped after 2 retries; upstream 503", |
| 581 | ] |
| 582 | ); |
| 583 | } |
| 584 | |
| 585 | #[tokio::test] |
| 586 | async fn isolated_retry_scope_never_observes_foreground_attempts() { |
| 587 | let (observation, receipts) = retry_receipt_observation(); |
| 588 | let count = observation.retries.clone(); |
| 589 | let mut calls = 0; |
| 590 | let result = observe_request_retries( |
| 591 | Some(observation), |
| 592 | observe_request_retries( |
| 593 | None, |
| 594 | with_retry( |
| 595 | &immediate_retry_policy(2), |
| 596 | || { |
| 597 | calls += 1; |
| 598 | let call = calls; |
| 599 | async move { |
| 600 | if call == 1 { |
| 601 | Err(LlmError::NetworkError("private endpoint".into())) |
| 602 | } else { |
| 603 | Ok(()) |
| 604 | } |
| 605 | } |
| 606 | }, |
| 607 | None, |
| 608 | ), |
| 609 | ), |
| 610 | ) |
| 611 | .await; |
| 612 | assert!(result.is_ok()); |
| 613 | assert_eq!(calls, 2); |
| 614 | assert_eq!(count.load(std::sync::atomic::Ordering::Relaxed), 0); |
| 615 | assert!(receipts.lock().unwrap().is_empty()); |
| 616 | } |
| 617 | |
| 618 | #[tokio::test] |
| 619 | async fn concurrent_request_retry_observations_keep_exact_producing_scope() { |
| 620 | let (first, first_receipts) = retry_receipt_observation(); |
| 621 | let (second, second_receipts) = retry_receipt_observation(); |
| 622 | let first_count = first.retries.clone(); |
| 623 | let second_count = second.retries.clone(); |
| 624 | let mut first_calls = 0; |
| 625 | let mut second_calls = 0; |
| 626 | let first_policy = immediate_retry_policy(2); |
| 627 | let second_policy = immediate_retry_policy(4); |
| 628 | let (a, b) = tokio::join!( |
| 629 | observe_request_retries( |
| 630 | Some(first), |
| 631 | with_retry( |
| 632 | &first_policy, |
| 633 | || { |
| 634 | first_calls += 1; |
| 635 | let call = first_calls; |
| 636 | async move { |
| 637 | if call == 1 { |
| 638 | Err(LlmError::Timeout(Duration::from_secs(1))) |
| 639 | } else { |
| 640 | Ok(()) |
| 641 | } |
| 642 | } |
| 643 | }, |
| 644 | None |
| 645 | ) |
| 646 | ), |
| 647 | observe_request_retries( |
| 648 | Some(second), |
| 649 | with_retry( |
| 650 | &second_policy, |
| 651 | || { |
| 652 | second_calls += 1; |
| 653 | let call = second_calls; |
| 654 | async move { |
| 655 | if call == 1 { |
| 656 | Err(LlmError::ServerError { |
| 657 | status: 502, |
| 658 | message: "opaque".into(), |
| 659 | }) |
| 660 | } else { |
| 661 | Ok(()) |
| 662 | } |
| 663 | } |
| 664 | }, |
| 665 | None |
| 666 | ) |
| 667 | ), |
| 668 | ); |
| 669 | assert!(a.is_ok() && b.is_ok()); |
| 670 | assert_eq!((first_calls, second_calls), (2, 2)); |
| 671 | assert_eq!(first_count.load(std::sync::atomic::Ordering::Relaxed), 1); |
| 672 | assert_eq!(second_count.load(std::sync::atomic::Ordering::Relaxed), 1); |
| 673 | assert_eq!( |
| 674 | first_receipts.lock().unwrap()[0], |
| 675 | "Retry attempt: HTTP 1; timeout; waiting 0.00s" |
| 676 | ); |
| 677 | assert_eq!( |
| 678 | second_receipts.lock().unwrap()[0], |
| 679 | "Retry attempt: HTTP 1; upstream 502; waiting 0.00s" |
| 680 | ); |
| 681 | } |
| 682 | |
| 683 | #[test] |
| 684 | fn timeout_display_zero_reports_unknown_duration_instead_of_0ns() { |
| 685 | // from_reqwest maps reqwest is_timeout() to Timeout(ZERO) because the spent |
| 686 | // budget is not recoverable from the error. The user-facing text must never |
| 687 | // claim "after 0ns" — that reads as a zero-length budget and hides the real |
| 688 | // failure (see hengqu order mini-20261108-123645, turn_f2409014). |
| 689 | let zero = LlmError::Timeout(Duration::from_secs(0)).to_string(); |
| 690 | assert!(!zero.contains("0ns"), "zero duration leaked as 0ns: {zero}"); |
| 691 | assert!(zero.contains("Request timed out"), "{zero}"); |
| 692 | assert!(zero.contains("duration not recorded"), "{zero}"); |
| 693 | |
| 694 | let measured = LlmError::Timeout(Duration::from_secs(120)).to_string(); |
| 695 | assert!( |
| 696 | measured.contains("Request timed out after 120s"), |
| 697 | "{measured}" |
| 698 | ); |
| 699 | } |
| 700 |