| 1 | #[tokio::test] |
| 2 | async fn rate_limit_unknown_quota_sender_and_billing_boundary() { |
| 3 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 4 | for (provider, message, detail, expected_wires) in [ |
| 5 | ("custom", "TPM exceeded", "", 2), |
| 6 | ("custom", "Credit balance exhausted", "", 1), |
| 7 | ("openai", "TPM exceeded", "", 1), |
| 8 | ( |
| 9 | "custom", |
| 10 | "Too many requests", |
| 11 | "Billing quota has been exhausted", |
| 12 | 1, |
| 13 | ), |
| 14 | ] { |
| 15 | let server = MockServer::start().await; |
| 16 | let mut config = Config::default(); |
| 17 | config.provider = Some(provider.into()); |
| 18 | config.providers = Some(ProvidersConfig { |
| 19 | openai: ProviderConfig { |
| 20 | api_key: Some("unknown-quota-fixture".into()), |
| 21 | base_url: Some(server.uri()), |
| 22 | ..Default::default() |
| 23 | }, |
| 24 | ..Default::default() |
| 25 | }); |
| 26 | let mut client = CodewhaleClient::new( |
| 27 | &config.with_legacy_root(Some("unknown-quota-fixture".into()), Some(server.uri())), |
| 28 | ) |
| 29 | .unwrap(); |
| 30 | client.retry.rate_limit.initial_delay_secs = 1; |
| 31 | client.retry.rate_limit.max_delay_secs = 1; |
| 32 | let calls = AtomicUsize::new(0); |
| 33 | let first = std::sync::Mutex::new(None::<tokio::time::Instant>); |
| 34 | let result = client.send_retry_loop(|| async { |
| 35 | let response = if calls.fetch_add(1, Ordering::SeqCst) == 0 { |
| 36 | *first.lock().unwrap() = Some(tokio::time::Instant::now()); |
| 37 | http::Response::builder().status(429).header("retry-after", "1") |
| 38 | .body(reqwest::Body::from(serde_json::json!({"error":{"type":if detail.is_empty() { "insufficient_quota" } else { "gateway_limit" },"message":message},"detail":detail}).to_string())).unwrap() |
| 39 | } else { |
| 40 | assert!(first.lock().unwrap().unwrap().elapsed() >= Duration::from_secs(1)); |
| 41 | http::Response::builder().body(reqwest::Body::from("ok")).unwrap() |
| 42 | }; |
| 43 | Ok(reqwest::Response::from(response)) |
| 44 | }, None, &ErrorBodyDisclosure::Full, crate::llm_client::RetryOperation::ReadOnly).await; |
| 45 | assert_eq!(calls.load(Ordering::SeqCst), expected_wires); |
| 46 | if expected_wires == 2 { |
| 47 | assert!(result.is_ok(), "{result:?}"); |
| 48 | } else { |
| 49 | assert!(matches!( |
| 50 | result.unwrap_err().downcast_ref::<LlmError>(), |
| 51 | Some(LlmError::QuotaExhausted(_)) |
| 52 | )); |
| 53 | } |
| 54 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | #[tokio::test] |
| 59 | async fn rate_limit_inherited_minimum_parks_before_wire() { |
| 60 | let server = MockServer::start().await; |
| 61 | let client = deepseek_request_boundary_client(&server.uri(), server.uri()); |
| 62 | let scope = client.rate_limit_scope(); |
| 63 | codewhale_runtime::retry_status::note_rate_limit(&scope, Duration::from_secs(3600)); |
| 64 | let calls = std::sync::atomic::AtomicU32::new(0); |
| 65 | let error = client |
| 66 | .send_retry_loop( |
| 67 | || async { |
| 68 | calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 69 | Ok(reqwest::Response::from( |
| 70 | http::Response::builder() |
| 71 | .body(reqwest::Body::from("ok")) |
| 72 | .unwrap(), |
| 73 | )) |
| 74 | }, |
| 75 | Some(Duration::from_secs(2)), |
| 76 | &ErrorBodyDisclosure::Full, |
| 77 | crate::llm_client::RetryOperation::ReadOnly, |
| 78 | ) |
| 79 | .await |
| 80 | .unwrap_err(); |
| 81 | assert!(matches!( |
| 82 | error.downcast_ref::<LlmError>(), |
| 83 | Some(LlmError::QuotaWindow { |
| 84 | transmission: crate::llm_client::RequestTransmission::NotDispatched, |
| 85 | .. |
| 86 | }) |
| 87 | )); |
| 88 | assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0); |
| 89 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 90 | } |
| 91 | |
| 92 | #[tokio::test] |
| 93 | async fn rate_limit_guarded_native_json_uses_actual_disclosure_boundary() { |
| 94 | let server = MockServer::start().await; |
| 95 | let client = minimax_request_boundary_client(&server.uri(), "MiniMax-M2.5", server.uri()); |
| 96 | let disclosure = ErrorBodyDisclosure::Guarded { |
| 97 | request_secrets: vec!["request-fixture".into()], |
| 98 | }; |
| 99 | let error = client.send_retry_loop(|| async { |
| 100 | Ok(reqwest::Response::from(http::Response::builder() |
| 101 | .header("content-type", "application/json").header("retry-after", "3600") |
| 102 | .body(reqwest::Body::from(r#"{"base_resp":{"status_code":1002,"status_msg":"minimax-request-boundary-key request-fixture"}}"#)).unwrap())) |
| 103 | }, None, &disclosure, crate::llm_client::RetryOperation::ReadOnly).await.unwrap_err(); |
| 104 | assert!(matches!( |
| 105 | error.downcast_ref::<LlmError>(), |
| 106 | Some(LlmError::QuotaWindow { .. }) |
| 107 | )); |
| 108 | assert!(!error.to_string().contains("minimax-request-boundary-key")); |
| 109 | assert!(!error.to_string().contains("request-fixture")); |
| 110 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 111 | } |
| 112 | |
| 113 | #[tokio::test] |
| 114 | async fn rate_limit_extreme_header_parks_without_instant_overflow() { |
| 115 | let server = MockServer::start().await; |
| 116 | let client = deepseek_request_boundary_client(&server.uri(), server.uri()); |
| 117 | let error = client |
| 118 | .send_retry_loop( |
| 119 | || async { |
| 120 | Ok(reqwest::Response::from( |
| 121 | http::Response::builder() |
| 122 | .status(429) |
| 123 | .header("retry-after", "18446744073709551615") |
| 124 | .body(reqwest::Body::from("fixture throttle")) |
| 125 | .unwrap(), |
| 126 | )) |
| 127 | }, |
| 128 | None, |
| 129 | &ErrorBodyDisclosure::Full, |
| 130 | crate::llm_client::RetryOperation::ReadOnly, |
| 131 | ) |
| 132 | .await |
| 133 | .unwrap_err(); |
| 134 | assert_eq!( |
| 135 | error |
| 136 | .downcast_ref::<LlmError>() |
| 137 | .unwrap() |
| 138 | .suggested_retry_delay(), |
| 139 | Some(Duration::from_secs(u64::MAX)) |
| 140 | ); |
| 141 | let remaining = |
| 142 | codewhale_runtime::retry_status::rate_limit_remaining(&client.rate_limit_scope()).unwrap(); |
| 143 | assert!(remaining <= Duration::from_secs(3600)); |
| 144 | assert!(remaining > Duration::from_secs(3598)); |
| 145 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 146 | } |
| 147 | |
| 148 | #[tokio::test] |
| 149 | async fn rate_limit_inherited_wait_is_outside_actual_nonstream_active_envelope() { |
| 150 | let _env_lock = crate::test_support::lock_test_env(); |
| 151 | let _envelope = NonStreamingEnvelopeGuard::millis(2000); |
| 152 | let server = MockServer::start().await; |
| 153 | let client = deepseek_request_boundary_client(&server.uri(), server.uri()); |
| 154 | codewhale_runtime::retry_status::note_rate_limit( |
| 155 | &client.rate_limit_scope(), |
| 156 | Duration::from_millis(1200), |
| 157 | ); |
| 158 | let result = client |
| 159 | .send_retry_loop( |
| 160 | || async { |
| 161 | tokio::time::sleep(Duration::from_millis(1200)).await; |
| 162 | Ok(reqwest::Response::from( |
| 163 | http::Response::builder() |
| 164 | .body(reqwest::Body::from("ok")) |
| 165 | .unwrap(), |
| 166 | )) |
| 167 | }, |
| 168 | Some(Duration::from_secs(2)), |
| 169 | &ErrorBodyDisclosure::Full, |
| 170 | crate::llm_client::RetryOperation::ReadOnly, |
| 171 | ) |
| 172 | .await; |
| 173 | assert!(result.is_ok(), "{result:?}"); |
| 174 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 175 | } |
| 176 | |
| 177 | #[tokio::test] |
| 178 | async fn rate_limit_isolated_unknown_quota_uses_route_classification() { |
| 179 | let server = MockServer::start().await; |
| 180 | let mut config = Config::default(); |
| 181 | config.provider = Some("custom".into()); |
| 182 | let mut client = CodewhaleClient::new( |
| 183 | &config.with_legacy_root(Some("isolated-quota-fixture".into()), Some(server.uri())), |
| 184 | ) |
| 185 | .unwrap(); |
| 186 | client.retry.enabled = false; |
| 187 | let error = client.send_with_isolated_retry(|| async { |
| 188 | Ok(reqwest::Response::from(http::Response::builder().status(429).body(reqwest::Body::from( |
| 189 | r#"{"error":{"code":null,"type":"insufficient_quota","message":"TPM exceeded"}}"# |
| 190 | )).unwrap())) |
| 191 | }, &ErrorBodyDisclosure::Full,crate::llm_client::RetryOperation::ReadOnly).await.unwrap_err(); |
| 192 | assert!(matches!( |
| 193 | error.downcast_ref::<LlmError>(), |
| 194 | Some(LlmError::RateLimited { .. }) |
| 195 | )); |
| 196 | } |
| 197 | |
| 198 | #[tokio::test] |
| 199 | async fn rate_limit_native_envelope_settles_both_sender_attempts() { |
| 200 | use crate::llm_client::{ |
| 201 | RequestRetryObservation, RequestTransmission, observe_request_retries, |
| 202 | }; |
| 203 | for (isolated, billing) in [(false, false), (true, false), (false, true), (true, true)] { |
| 204 | let status = if billing { 429 } else { 200 }; |
| 205 | let body = if billing { |
| 206 | serde_json::json!({"error":{"message":"Too many requests"},"detail":"Billing quota has been exhausted"}) |
| 207 | } else { |
| 208 | serde_json::json!({"base_resp":{"status_code":2045,"status_msg":"retry in 30s"}}) |
| 209 | }; |
| 210 | let server = MockServer::start().await; |
| 211 | Mock::given(method("POST")) |
| 212 | .respond_with(ResponseTemplate::new(status).set_body_json(body)) |
| 213 | .mount(&server) |
| 214 | .await; |
| 215 | let mut client = |
| 216 | minimax_request_boundary_client(&server.uri(), "MiniMax-M2.5", server.uri()); |
| 217 | client.isolated_request_state = isolated; |
| 218 | let observation = RequestRetryObservation { |
| 219 | request_id: "envelope-settlement".into(), |
| 220 | wire_observations: Default::default(), |
| 221 | retries: Default::default(), |
| 222 | emit: std::sync::Arc::new(|_| Box::pin(async {})), |
| 223 | }; |
| 224 | let wire = observation.wire_observations.clone(); |
| 225 | let error = observe_request_retries( |
| 226 | Some(observation), |
| 227 | client.send_with_retry(|| client.http_client.post(server.uri()).body("{}")), |
| 228 | ) |
| 229 | .await |
| 230 | .unwrap_err(); |
| 231 | let error = error.downcast_ref::<LlmError>().unwrap(); |
| 232 | if billing { |
| 233 | assert!(matches!(error, LlmError::QuotaExhausted(_))); |
| 234 | } else { |
| 235 | assert!(matches!(error, LlmError::QuotaWindow { .. })); |
| 236 | assert_eq!(error.suggested_retry_delay(), Some(Duration::from_secs(30))); |
| 237 | } |
| 238 | assert_eq!(server.received_requests().await.unwrap().len(), 1); |
| 239 | let attempts = wire.snapshot().transmissions; |
| 240 | assert_eq!(attempts.len(), 1); |
| 241 | assert_eq!(attempts[0].http_status, Some(status)); |
| 242 | assert_eq!(attempts[0].transmission, RequestTransmission::Rejected); |
| 243 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | #[tokio::test] |
| 248 | async fn rate_limit_local_bucket_still_consumes_the_nonstream_active_envelope() { |
| 249 | let _env_lock = crate::test_support::lock_test_env(); |
| 250 | let _envelope = NonStreamingEnvelopeGuard::millis(2000); |
| 251 | let server = MockServer::start().await; |
| 252 | let client = deepseek_request_boundary_client(&server.uri(), server.uri()); |
| 253 | *client.rate_limiter.lock().await = TokenBucket { |
| 254 | enabled: true, |
| 255 | capacity: 1.0, |
| 256 | tokens: 0.0, |
| 257 | refill_per_sec: 0.0001, |
| 258 | last_refill: Instant::now(), |
| 259 | }; |
| 260 | let calls = std::sync::atomic::AtomicU32::new(0); |
| 261 | let error = tokio::time::timeout( |
| 262 | Duration::from_secs(5), |
| 263 | client.send_retry_loop( |
| 264 | || async { |
| 265 | calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 266 | Ok(reqwest::Response::from( |
| 267 | http::Response::builder() |
| 268 | .body(reqwest::Body::from("ok")) |
| 269 | .unwrap(), |
| 270 | )) |
| 271 | }, |
| 272 | Some(Duration::from_secs(2)), |
| 273 | &ErrorBodyDisclosure::Full, |
| 274 | crate::llm_client::RetryOperation::Inference, |
| 275 | ), |
| 276 | ) |
| 277 | .await |
| 278 | .expect("local token admission remains inside the active deadline") |
| 279 | .unwrap_err(); |
| 280 | assert!(matches!( |
| 281 | error.downcast_ref::<LlmError>(), |
| 282 | Some(LlmError::Timeout(_)) |
| 283 | )); |
| 284 | assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0); |
| 285 | } |
| 286 | |
| 287 | #[tokio::test] |
| 288 | async fn rate_limit_official_quota_retains_route_guidance_in_both_senders() { |
| 289 | for isolated in [false, true] { |
| 290 | for code in [ |
| 291 | "subscription_sharing_usage_limit_exceeded", |
| 292 | "subscription_sharing_usage_unavailable", |
| 293 | ] { |
| 294 | let server = MockServer::start().await; |
| 295 | Mock::given(method("POST")) |
| 296 | .respond_with( |
| 297 | ResponseTemplate::new(429).set_body_json( |
| 298 | serde_json::json!({"error":{"code":code,"message":"opaque"}}), |
| 299 | ), |
| 300 | ) |
| 301 | .mount(&server) |
| 302 | .await; |
| 303 | let mut config = Config::default(); |
| 304 | config.provider = Some("openai-codex".into()); |
| 305 | config.providers = Some(ProvidersConfig { |
| 306 | openai_codex: ProviderConfig { |
| 307 | api_key: Some("guidance-fixture-token".into()), |
| 308 | base_url: Some(server.uri()), |
| 309 | ..Default::default() |
| 310 | }, |
| 311 | ..Default::default() |
| 312 | }); |
| 313 | let mut client = CodewhaleClient::new(&config).unwrap(); |
| 314 | client.isolated_request_state = isolated; |
| 315 | client.subscription_limit_guidance = Some("fixture-owned-account-guidance".into()); |
| 316 | let error = client |
| 317 | .send_with_retry(|| client.http_client.post(server.uri()).body("{}")) |
| 318 | .await |
| 319 | .unwrap_err(); |
| 320 | let typed = error.downcast_ref::<LlmError>().unwrap(); |
| 321 | assert!(matches!(typed, LlmError::QuotaExhausted(_))); |
| 322 | assert!(!typed.is_retryable()); |
| 323 | assert!( |
| 324 | typed.to_string().contains("ChatGPT Settings > Usage"), |
| 325 | "{typed}" |
| 326 | ); |
| 327 | assert!( |
| 328 | typed.to_string().contains("fixture-owned-account-guidance"), |
| 329 | "{typed}" |
| 330 | ); |
| 331 | assert_eq!(server.received_requests().await.unwrap().len(), 1); |
| 332 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | #[tokio::test] |
| 338 | async fn recovery_probe_never_holds_back_the_request_error() { |
| 339 | let server = MockServer::start().await; |
| 340 | Mock::given(method("POST")) |
| 341 | .respond_with(ResponseTemplate::new(400).set_body_string("bad request")) |
| 342 | .mount(&server) |
| 343 | .await; |
| 344 | Mock::given(method("GET")) |
| 345 | .respond_with( |
| 346 | ResponseTemplate::new(200) |
| 347 | .set_body_json(serde_json::json!({"data": []})) |
| 348 | .set_delay(Duration::from_secs(20)), |
| 349 | ) |
| 350 | .mount(&server) |
| 351 | .await; |
| 352 | let base_url = format!("{}/v1", server.uri()); |
| 353 | let mut config = Config::default(); |
| 354 | config.provider = Some("openai".into()); |
| 355 | config.providers = Some(ProvidersConfig { |
| 356 | openai: ProviderConfig { |
| 357 | api_key: Some("probe-fixture".into()), |
| 358 | base_url: Some(base_url.clone()), |
| 359 | ..Default::default() |
| 360 | }, |
| 361 | ..Default::default() |
| 362 | }); |
| 363 | let mut client = CodewhaleClient::new( |
| 364 | &config.with_legacy_root(Some("probe-fixture".into()), Some(base_url)), |
| 365 | ) |
| 366 | .unwrap(); |
| 367 | client.retry.enabled = false; |
| 368 | apply_request_failure(&mut *client.connection_health.lock().await, Instant::now()); |
| 369 | |
| 370 | let started = std::time::Instant::now(); |
| 371 | let result = client |
| 372 | .send_with_retry(|| client.http_client.post(server.uri()).body("{}")) |
| 373 | .await; |
| 374 | assert!(result.is_err()); |
| 375 | assert!( |
| 376 | started.elapsed() < Duration::from_secs(5), |
| 377 | "the error waited {:?} on the recovery probe", |
| 378 | started.elapsed() |
| 379 | ); |
| 380 | { |
| 381 | let health = client.connection_health.lock().await; |
| 382 | assert_eq!(health.state, ConnectionState::Recovering); |
| 383 | assert!(health.last_probe.is_some()); |
| 384 | } |
| 385 | |
| 386 | let deadline = std::time::Instant::now() + Duration::from_secs(5); |
| 387 | loop { |
| 388 | let requests = server.received_requests().await.unwrap(); |
| 389 | if requests.iter().any(|r| r.method.as_str() == "GET") { |
| 390 | break; |
| 391 | } |
| 392 | assert!( |
| 393 | std::time::Instant::now() < deadline, |
| 394 | "the detached recovery probe never reached /models" |
| 395 | ); |
| 396 | tokio::time::sleep(Duration::from_millis(20)).await; |
| 397 | } |
| 398 | } |
| 399 |