返回 CodeWhale
rate_limit.rs
根目录 / crates / engine / src / llm_client / rate_limit.rs
1 //! Recovery policy for a refused model operation. Generation time is not a retry budget.
2
3 use std::time::Duration;
4
5 use super::{LlmError, RateLimitRetryPolicy};
6
7 #[derive(Default)]
8 struct Clock {
9 recovery_started: Option<tokio::time::Instant>,
10 phase: u64,
11 waited: Duration,
12 waiting: Option<tokio::time::Instant>,
13 }
14
15 tokio::task_local! {
16 static RECOVERY_CLOCK: std::sync::Arc<std::sync::Mutex<Clock>>;
17 }
18
19 struct PauseGuard(std::sync::Arc<std::sync::Mutex<Clock>>);
20 impl Drop for PauseGuard {
21 fn drop(&mut self) {
22 let mut clock = self
23 .0
24 .lock()
25 .unwrap_or_else(std::sync::PoisonError::into_inner);
26 if let Some(started) = clock.waiting.take() {
27 clock.waited += started.elapsed();
28 }
29 }
30 }
31
32 /// Establish the transport clock when polled, so an enclosing active deadline
33 /// and the complete streaming-open retry loop observe the same wait ledger.
34 pub fn with_recovery_clock<F: std::future::Future>(
35 future: F,
36 ) -> std::pin::Pin<Box<impl std::future::Future<Output = F::Output>>> {
37 Box::pin(async move {
38 let clock = RECOVERY_CLOCK.try_with(Clone::clone).unwrap_or_default();
39 RECOVERY_CLOCK.scope(clock, future).await
40 })
41 }
42
43 /// Admission and the retry loop share the same transport-local recovery clock.
44 pub fn note_recovery_started(started: Option<tokio::time::Instant>) {
45 let _ = RECOVERY_CLOCK.try_with(|clock| {
46 clock
47 .lock()
48 .unwrap_or_else(std::sync::PoisonError::into_inner)
49 .recovery_started = started;
50 });
51 }
52
53 pub fn remaining_recovery_budget(policy: &RateLimitRetryPolicy) -> Duration {
54 let elapsed = RECOVERY_CLOCK
55 .try_with(|clock| {
56 clock
57 .lock()
58 .unwrap_or_else(std::sync::PoisonError::into_inner)
59 .recovery_started
60 .map_or(Duration::ZERO, |started| started.elapsed())
61 })
62 .unwrap_or_default();
63 Duration::from_secs(policy.recovery_budget_secs).saturating_sub(elapsed)
64 }
65
66 pub fn new_attempt() {
67 let _ = RECOVERY_CLOCK.try_with(|clock| {
68 let mut clock = clock
69 .lock()
70 .unwrap_or_else(std::sync::PoisonError::into_inner);
71 clock.phase = clock.phase.wrapping_add(1);
72 });
73 }
74
75 pub async fn without_active_time<F: std::future::Future>(future: F) -> F::Output {
76 let _pause = RECOVERY_CLOCK
77 .try_with(|clock| {
78 clock
79 .lock()
80 .unwrap_or_else(std::sync::PoisonError::into_inner)
81 .waiting = Some(tokio::time::Instant::now());
82 PauseGuard(clock.clone())
83 })
84 .ok();
85 future.await
86 }
87
88 pub async fn wait(delay: Duration) {
89 without_active_time(tokio::time::sleep(delay)).await;
90 }
91
92 /// Bound active work while a provider-directed backoff belongs to its own recovery budget.
93 pub fn active_timeout<F: std::future::Future>(
94 duration: Duration,
95 future: F,
96 ) -> std::pin::Pin<Box<impl std::future::Future<Output = Result<F::Output, ()>>>> {
97 active_timeout_policy(duration, future, true)
98 }
99
100 pub fn active_timeout_total<F: std::future::Future>(
101 duration: Duration,
102 future: F,
103 ) -> std::pin::Pin<Box<impl std::future::Future<Output = Result<F::Output, ()>>>> {
104 active_timeout_policy(duration, future, false)
105 }
106
107 fn active_timeout_policy<F: std::future::Future>(
108 duration: Duration,
109 future: F,
110 reset_on_attempt: bool,
111 ) -> std::pin::Pin<Box<impl std::future::Future<Output = Result<F::Output, ()>>>> {
112 let clock = RECOVERY_CLOCK.try_with(Clone::clone).unwrap_or_default();
113 Box::pin(RECOVERY_CLOCK.scope(clock.clone(), async move {
114 let mut start = tokio::time::Instant::now();
115 let mut baseline = clock
116 .lock()
117 .unwrap_or_else(std::sync::PoisonError::into_inner)
118 .waited;
119 let mut phase = clock
120 .lock()
121 .unwrap_or_else(std::sync::PoisonError::into_inner)
122 .phase;
123 tokio::pin!(future);
124 loop {
125 let waiting = {
126 let clock = clock
127 .lock()
128 .unwrap_or_else(std::sync::PoisonError::into_inner);
129 if reset_on_attempt && clock.phase != phase {
130 phase = clock.phase;
131 start = tokio::time::Instant::now();
132 baseline = clock.waited;
133 }
134 clock.waited.saturating_sub(baseline)
135 + clock.waiting.map_or(Duration::ZERO, |t| t.elapsed())
136 };
137 let remaining = duration.saturating_sub(start.elapsed().saturating_sub(waiting));
138 if remaining.is_zero() {
139 return Err(());
140 }
141 tokio::select! {
142 biased;
143 result = &mut future => return Ok(result),
144 () = tokio::time::sleep(remaining.min(Duration::from_millis(100))) => {}
145 }
146 }
147 }))
148 }
149
150 pub fn server_delay(value: &str) -> Option<Duration> {
151 let value = value.trim();
152 if let Ok(seconds) = value.parse::<u64>() {
153 return Some(Duration::from_secs(seconds));
154 }
155 if let Ok(seconds) = value.parse::<f64>() {
156 return Duration::try_from_secs_f64(seconds).ok();
157 }
158 chrono::DateTime::parse_from_rfc2822(value)
159 .ok()
160 .map(|date| {
161 (date.with_timezone(&chrono::Utc) - chrono::Utc::now())
162 .to_std()
163 .unwrap_or_default()
164 })
165 }
166
167 /// Some native providers report logical failures in a successful JSON envelope.
168 /// SSE bodies remain streaming and are owned by their existing recovery path.
169 #[cfg(test)]
170 #[allow(
171 clippy::result_large_err,
172 reason = "Keep the shared transport typed LlmError contract"
173 )]
174 async fn inspect_json_envelope(
175 provider: &str,
176 response: reqwest::Response,
177 ) -> Result<reqwest::Response, LlmError> {
178 inspect_json_envelope_with_disclosure(provider, response, None, |status, raw| {
179 super::sanitize_http_error_body(Some(provider), status, raw)
180 })
181 .await
182 }
183
184 #[allow(
185 clippy::result_large_err,
186 reason = "Keep the shared transport typed LlmError contract"
187 )]
188 pub async fn inspect_json_envelope_with_disclosure<F>(
189 provider: &str,
190 mut response: reqwest::Response,
191 body_timeouts: Option<(Duration, Duration)>,
192 disclose: F,
193 ) -> Result<reqwest::Response, LlmError>
194 where
195 F: Fn(u16, &str) -> String + Send,
196 {
197 if !response.status().is_success()
198 || !matches!(provider, "minimax" | "minimax-anthropic" | "zai")
199 || !response
200 .headers()
201 .get(reqwest::header::CONTENT_TYPE)
202 .and_then(|v| v.to_str().ok())
203 .is_some_and(|value| {
204 value
205 .split(';')
206 .next()
207 .is_some_and(|kind| kind.trim().eq_ignore_ascii_case("application/json"))
208 })
209 {
210 return Ok(response);
211 }
212 let status = response.status();
213 let version = response.version();
214 let headers = response.headers().clone();
215 let retry_after = super::extract_retry_after(&headers);
216 const MAX_ENVELOPE_BYTES: usize = 32 * 1024 * 1024;
217 if response
218 .content_length()
219 .is_some_and(|length| length > MAX_ENVELOPE_BYTES as u64)
220 {
221 return Err(LlmError::ParseError(
222 "Provider JSON envelope exceeds 32 MiB".into(),
223 ));
224 }
225 let mut bytes = Vec::new();
226 loop {
227 let chunk = if let Some((first_byte, idle)) = body_timeouts {
228 let timeout = if bytes.is_empty() { first_byte } else { idle };
229 tokio::time::timeout(timeout, response.chunk())
230 .await
231 .map_err(|_| LlmError::Timeout(timeout))?
232 } else {
233 response.chunk().await
234 }
235 .map_err(|error| LlmError::from_reqwest(&error))?;
236 let Some(chunk) = chunk else { break };
237 if chunk.len() > MAX_ENVELOPE_BYTES.saturating_sub(bytes.len()) {
238 return Err(LlmError::ParseError(
239 "Provider JSON envelope exceeds 32 MiB".into(),
240 ));
241 }
242 bytes.extend_from_slice(&chunk);
243 }
244 let raw = String::from_utf8_lossy(&bytes);
245 if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&raw) {
246 let body = super::unwrap_single_element_json_array(&parsed);
247 let failed = body
248 .pointer("/base_resp/status_code")
249 .and_then(serde_json::Value::as_i64)
250 .is_some_and(|code| code != 0)
251 || body.get("error").is_some_and(|error| !error.is_null());
252 if failed {
253 let safe = disclose(status.as_u16(), &raw);
254 return Err(
255 provider_error(provider, status.as_u16(), &raw, &safe, retry_after).unwrap_or(
256 LlmError::InvalidRequest {
257 status: status.as_u16(),
258 message: safe,
259 },
260 ),
261 );
262 }
263 }
264 let mut rebuilt = http::Response::new(reqwest::Body::from(bytes));
265 *rebuilt.status_mut() = status;
266 *rebuilt.version_mut() = version;
267 *rebuilt.headers_mut() = headers;
268 Ok(reqwest::Response::from(rebuilt))
269 }
270
271 pub fn body_delay(body: &str) -> Option<Duration> {
272 let parsed: serde_json::Value = serde_json::from_str(body).ok()?;
273 let body = super::unwrap_single_element_json_array(&parsed);
274 let mut objects = vec![
275 body,
276 body.get("error").unwrap_or(body),
277 body.get("base_resp").unwrap_or(body),
278 ];
279 if let Some(details) = body
280 .pointer("/error/details")
281 .and_then(serde_json::Value::as_array)
282 {
283 objects.extend(details.iter());
284 }
285 let mut delay = None;
286 for object in objects {
287 for key in ["retry_after", "retry_after_seconds", "retryDelay"] {
288 if let Some(value) = object.get(key) {
289 let text = value
290 .as_str()
291 .map(str::to_owned)
292 .unwrap_or_else(|| value.to_string());
293 delay = delay.max(server_delay(text.trim_end_matches('s')));
294 }
295 }
296 for key in ["next_flush_time", "reset_time", "reset_at"] {
297 if let Some(value) = object.get(key) {
298 let text = value
299 .as_str()
300 .map(str::to_owned)
301 .unwrap_or_else(|| value.to_string());
302 let reset = text
303 .parse::<i64>()
304 .ok()
305 .and_then(|n| {
306 if n > 10_000_000_000 {
307 chrono::DateTime::from_timestamp_millis(n)
308 } else {
309 chrono::DateTime::from_timestamp(n, 0)
310 }
311 })
312 .or_else(|| {
313 chrono::DateTime::parse_from_rfc3339(&text)
314 .ok()
315 .map(|d| d.with_timezone(&chrono::Utc))
316 });
317 delay =
318 delay.max(reset.map(|d| (d - chrono::Utc::now()).to_std().unwrap_or_default()));
319 }
320 }
321 }
322 delay
323 }
324
325 fn normalized_error_code(code: &str) -> String {
326 code.chars()
327 .filter(char::is_ascii_alphanumeric)
328 .map(|ch| ch.to_ascii_lowercase())
329 .collect()
330 }
331
332 fn independent_billing_evidence(body: &serde_json::Value, raw: &str, bounded_hint: bool) -> bool {
333 let coded = [
334 "/error/code",
335 "/error/type",
336 "/error/error_code",
337 "/code",
338 "/type",
339 "/error_code",
340 ]
341 .into_iter()
342 .filter_map(|p| body.pointer(p).and_then(serde_json::Value::as_str))
343 .any(|code| {
344 normalized_error_code(code) != "insufficientquota" && super::is_explicit_quota_code(code)
345 });
346 // Reuse the legacy durable-message contract, excluding only the ambiguous
347 // code. Check every supported message field so a gateway's generic class
348 // cannot hide an explicit billing detail. Decode JSON Unicode escapes too.
349 coded
350 || std::iter::once(raw)
351 .chain(
352 [
353 "/error/message",
354 "/error",
355 "/message",
356 "/detail",
357 "/error_description",
358 ]
359 .into_iter()
360 .filter_map(|p| body.pointer(p).and_then(serde_json::Value::as_str)),
361 )
362 .any(|message| {
363 let message = message.to_ascii_lowercase();
364 super::has_explicit_quota_phrase(&message, bounded_hint)
365 || [
366 "billing hard limit reached",
367 "billing limit reached",
368 "billing limit has been reached",
369 "credit balance too low",
370 "insufficient credits",
371 "out of credits",
372 "insufficient balance",
373 "insufficient funds",
374 "payment required",
375 "subscription expired",
376 "subscription has expired",
377 "\u{4f59}\u{989d}\u{4e0d}\u{8db3}",
378 "\u{4f59}\u{989d}\u{5df2}\u{8017}\u{5c3d}",
379 "\u{6b20}\u{8d39}",
380 "\u{8ba2}\u{9605}\u{5df2}\u{8fc7}\u{671f}",
381 ]
382 .iter()
383 .any(|phrase| message.contains(phrase))
384 })
385 }
386
387 /// Interpret native codes before sanitization; unknown 429s remain bounded.
388 pub fn provider_error(
389 provider: &str,
390 status: u16,
391 raw: &str,
392 safe: &str,
393 hint: Option<Duration>,
394 ) -> Option<LlmError> {
395 let hint = hint
396 .max(body_delay(raw))
397 .max(super::retry_delay_from_error_body(raw));
398 let parsed: serde_json::Value = serde_json::from_str(raw).unwrap_or(serde_json::Value::Null);
399 let body = super::unwrap_single_element_json_array(&parsed);
400 let code = [
401 "/error/code",
402 "/error/type",
403 "/error/error_code",
404 "/base_resp/status_code",
405 "/code",
406 "/type",
407 "/error_code",
408 ]
409 .into_iter()
410 .find_map(|p| body.pointer(p));
411 let code = code
412 .map(|code| {
413 code.as_str()
414 .map(str::to_owned)
415 .unwrap_or_else(|| code.to_string())
416 })
417 .unwrap_or_default();
418 let provider = provider.to_ascii_lowercase();
419 let code_lower = code.to_ascii_lowercase();
420 let window = match provider.as_str() {
421 "minimax" | "minimax-anthropic" | "minimax_anthropic" => {
422 matches!(code.as_str(), "2045" | "2046" | "2047")
423 }
424 "glm" | "zai" | "zhipu" => matches!(
425 code.as_str(),
426 "1308" | "1310" | "1316" | "1317" | "1318" | "1319" | "1320" | "1321"
427 ),
428 _ => false,
429 };
430 if window {
431 return Some(LlmError::QuotaWindow {
432 message: safe.to_owned(),
433 retry_after: hint,
434 transmission: super::RequestTransmission::Rejected,
435 });
436 }
437 if (matches!(status, 400 | 402 | 403 | 429) || (200..300).contains(&status))
438 && independent_billing_evidence(body, raw, true)
439 {
440 return Some(LlmError::QuotaExhausted(
441 super::QuotaExhaustionError::from_http_message(safe.to_owned()),
442 ));
443 }
444 // This code means billing on OpenAI, but RPM/TPM on other surfaces.
445 // An unknown relay must not turn that ambiguous code alone into a
446 // permanent account failure. Independent billing evidence still wins.
447 let raw_lower = raw.to_ascii_lowercase();
448 let marked = raw_lower
449 .split_once("provider error code:")
450 .map(|(_, tail)| {
451 tail.trim_start()
452 .split(|ch: char| !(ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-')))
453 .next()
454 .unwrap_or_default()
455 })
456 .unwrap_or_default();
457 let ambiguous_quota = status == 429
458 && !matches!(
459 provider.as_str(),
460 "openai" | "openai-codex" | "openai_codex"
461 )
462 && ([
463 "/error/code",
464 "/error/type",
465 "/error/error_code",
466 "/code",
467 "/type",
468 "/error_code",
469 ]
470 .into_iter()
471 .filter_map(|p| body.pointer(p).and_then(serde_json::Value::as_str))
472 .any(|code| normalized_error_code(code) == "insufficientquota")
473 || normalized_error_code(marked) == "insufficientquota");
474 if ambiguous_quota && independent_billing_evidence(body, raw, hint.is_some()) {
475 return Some(LlmError::QuotaExhausted(
476 super::QuotaExhaustionError::from_http_message(safe.to_owned()),
477 ));
478 }
479 let transient = match provider.as_str() {
480 "qwen"
481 | "dashscope"
482 | "alibaba"
483 | "modelstudio"
484 | "modelstudio-token-plan"
485 | "modelstudio-token-plan-anthropic"
486 | "modelstudio_token_plan"
487 | "modelstudio_token_plan_anthropic" => {
488 status == 429
489 && matches!(
490 code_lower.as_str(),
491 "insufficient_quota" | "throttling" | "throttling.ratequota"
492 )
493 }
494 "minimax" | "minimax-anthropic" | "minimax_anthropic" => {
495 matches!(code.as_str(), "1002" | "1041")
496 }
497 "glm" | "zai" | "zhipu" => matches!(
498 code.as_str(),
499 "1302" | "1305" | "1308" | "1310" | "1316" | "1317" | "1318" | "1319" | "1320" | "1321"
500 ),
501 _ => false,
502 };
503 if transient {
504 return Some(LlmError::RateLimited {
505 message: safe.to_owned(),
506 retry_after: hint,
507 });
508 }
509 let user_action = match provider.as_str() {
510 "minimax" | "minimax-anthropic" | "minimax_anthropic" => {
511 matches!(code.as_str(), "1008" | "1039")
512 }
513 "glm" | "zai" | "zhipu" => matches!(code.as_str(), "1113" | "1309"),
514 _ => false,
515 };
516 if user_action && code != "1039" {
517 return Some(LlmError::QuotaExhausted(
518 super::QuotaExhaustionError::from_http_message(safe.to_owned()),
519 ));
520 }
521 if user_action {
522 return Some(LlmError::InvalidRequest {
523 status,
524 message: safe.to_owned(),
525 });
526 }
527 if ambiguous_quota {
528 return Some(LlmError::RateLimited {
529 message: safe.to_owned(),
530 retry_after: hint,
531 });
532 }
533 None
534 }
535
536 pub fn retry_delay(policy: &RateLimitRetryPolicy, retry: u32) -> Duration {
537 let multiplier = 2u32.saturating_pow(retry.min(31));
538 let base = Duration::from_secs(policy.initial_delay_secs)
539 .saturating_mul(multiplier)
540 .min(Duration::from_secs(policy.max_delay_secs));
541 let bytes = *uuid::Uuid::new_v4().as_bytes();
542 let unit = f64::from(u16::from_le_bytes([bytes[0], bytes[1]])) / f64::from(u16::MAX);
543 base.mul_f64(0.5 + unit * 0.5)
544 }
545
546 #[cfg(test)]
547 mod tests;
548
548 lines RUST