1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
// LLM Rate Limit Retry Logic
//
// Provider-specific retry handling for transient API errors (429, 408, 409, 5xx).
// Separate from durable execution RetryPolicy - this handles transient API errors.
//
// Aligns with official SDK behavior:
// - Anthropic SDK: https://github.com/anthropics/anthropic-sdk-python
// - OpenAI SDK: https://github.com/openai/openai-python
//
// Provider-specific headers:
// - Anthropic: retry-after, retry-after-ms, anthropic-ratelimit-*
// - OpenAI: retry-after, retry-after-ms, x-ratelimit-*
//
// Design: exponential backoff with 25% jitter, respecting provider retry-after hints.
// Defaults match official SDKs: 2 retries, 1s initial, 60s max, 2x multiplier.
use std::time::Duration;
/// Maximum retry-after value to honor (seconds).
/// Matches official SDK behavior - if server says wait longer, use backoff instead.
const MAX_RETRY_AFTER_SECS: u64 = 60;
/// Configuration for LLM rate limit retry behavior.
///
/// Defaults match official Anthropic/OpenAI SDK behavior:
/// - max_retries: 2
/// - initial_backoff: 1 second
/// - max_backoff: 60 seconds
/// - backoff_multiplier: 2.0
/// - jitter_factor: 0.25 (±25%)
#[derive(Debug, Clone)]
pub struct LlmRetryConfig {
/// Maximum number of retry attempts (0 = no retries)
pub max_retries: u32,
/// Initial backoff duration (before exponential increase)
pub initial_backoff: Duration,
/// Maximum backoff duration (cap for exponential growth)
pub max_backoff: Duration,
/// Backoff multiplier (typically 2.0 for exponential)
pub backoff_multiplier: f64,
/// Jitter factor (0.0-1.0, adds randomness to avoid thundering herd)
/// Official SDKs use 0.25 (±25%)
pub jitter_factor: f64,
}
impl Default for LlmRetryConfig {
fn default() -> Self {
// Matches official Anthropic/OpenAI SDK defaults
Self {
max_retries: 2,
initial_backoff: Duration::from_secs(1),
max_backoff: Duration::from_secs(60),
backoff_multiplier: 2.0,
jitter_factor: 0.25,
}
}
}
impl LlmRetryConfig {
/// Create a config with no retries (fail immediately on rate limit)
pub fn no_retry() -> Self {
Self {
max_retries: 0,
..Default::default()
}
}
/// Create a config with aggressive retry settings (more retries, longer waits)
pub fn aggressive() -> Self {
Self {
max_retries: 5,
initial_backoff: Duration::from_millis(500),
max_backoff: Duration::from_secs(120),
backoff_multiplier: 2.0,
jitter_factor: 0.25,
}
}
/// Calculate backoff duration for a given attempt number (0-indexed)
pub fn calculate_backoff(&self, attempt: u32) -> Duration {
let base_backoff =
self.initial_backoff.as_secs_f64() * self.backoff_multiplier.powi(attempt as i32);
let capped_backoff = base_backoff.min(self.max_backoff.as_secs_f64());
// Add jitter (±jitter_factor around the base)
// Official SDKs use: sleep_seconds * (1 - 0.25 * random()) where random is 0-1
// This gives range [0.75, 1.0] * base
let jitter = if self.jitter_factor > 0.0 {
let jitter_range = capped_backoff * self.jitter_factor;
// Simple deterministic jitter based on attempt number
// In production, use rand crate for true randomness
let jitter_offset = (attempt as f64 * 0.37).fract() * 2.0 - 1.0; // -1 to 1
jitter_range * jitter_offset
} else {
0.0
};
Duration::from_secs_f64((capped_backoff + jitter).max(0.0))
}
}
/// Rate limit information extracted from provider response headers
#[derive(Debug, Clone, Default)]
pub struct RateLimitInfo {
/// Retry-After header value (seconds to wait)
pub retry_after_secs: Option<u64>,
/// Requests remaining before limit
pub requests_remaining: Option<u32>,
/// Tokens remaining before limit
pub tokens_remaining: Option<u32>,
/// Time until request limit resets
pub requests_reset: Option<String>,
/// Time until token limit resets
pub tokens_reset: Option<String>,
/// Provider-specific limit type that was hit
pub limit_type: Option<RateLimitType>,
}
/// Type of rate limit that was exceeded
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RateLimitType {
/// Requests per minute/hour
Requests,
/// Input tokens per minute
InputTokens,
/// Output tokens per minute
OutputTokens,
/// Total tokens per minute
TotalTokens,
/// Unknown or unspecified
Unknown,
}
impl RateLimitInfo {
/// Get the recommended wait duration, preferring retry-after if available.
/// Caps retry-after at MAX_RETRY_AFTER_SECS (60s) like official SDKs.
pub fn recommended_wait(&self, config: &LlmRetryConfig, attempt: u32) -> Duration {
if let Some(retry_after) = self.retry_after_secs {
// Provider told us how long to wait
// Cap at 60s like official SDKs - if longer, use backoff instead
if retry_after > 0 && retry_after <= MAX_RETRY_AFTER_SECS {
return Duration::from_secs(retry_after);
}
}
// Fall back to exponential backoff
config.calculate_backoff(attempt)
}
/// Parse rate limit info from Anthropic response headers
pub fn from_anthropic_headers(headers: &reqwest::header::HeaderMap) -> Self {
let mut info = Self::default();
// Try non-standard retry-after-ms header first (milliseconds)
// Used by some providers for sub-second precision
if let Some(val) = headers.get("retry-after-ms")
&& let Ok(s) = val.to_str()
&& let Ok(ms) = s.parse::<u64>()
{
// Convert ms to seconds (round up)
info.retry_after_secs = Some(ms.div_ceil(1000));
}
// retry-after header (standard, seconds)
if info.retry_after_secs.is_none()
&& let Some(val) = headers.get("retry-after")
&& let Ok(s) = val.to_str()
{
info.retry_after_secs = s.parse().ok();
}
// anthropic-ratelimit-requests-remaining
if let Some(val) = headers.get("anthropic-ratelimit-requests-remaining")
&& let Ok(s) = val.to_str()
{
info.requests_remaining = s.parse().ok();
}
// anthropic-ratelimit-tokens-remaining
if let Some(val) = headers.get("anthropic-ratelimit-tokens-remaining")
&& let Ok(s) = val.to_str()
{
info.tokens_remaining = s.parse().ok();
}
// anthropic-ratelimit-requests-reset
if let Some(val) = headers.get("anthropic-ratelimit-requests-reset")
&& let Ok(s) = val.to_str()
{
info.requests_reset = Some(s.to_string());
}
// anthropic-ratelimit-tokens-reset
if let Some(val) = headers.get("anthropic-ratelimit-tokens-reset")
&& let Ok(s) = val.to_str()
{
info.tokens_reset = Some(s.to_string());
}
// Determine limit type from remaining values
if info.requests_remaining == Some(0) {
info.limit_type = Some(RateLimitType::Requests);
} else if info.tokens_remaining == Some(0) {
info.limit_type = Some(RateLimitType::InputTokens);
}
info
}
/// Parse rate limit info from OpenAI response headers
pub fn from_openai_headers(headers: &reqwest::header::HeaderMap) -> Self {
let mut info = Self::default();
// Try non-standard retry-after-ms header first (milliseconds)
if let Some(val) = headers.get("retry-after-ms")
&& let Ok(s) = val.to_str()
&& let Ok(ms) = s.parse::<u64>()
{
// Convert ms to seconds (round up)
info.retry_after_secs = Some(ms.div_ceil(1000));
}
// retry-after header (standard, seconds)
if info.retry_after_secs.is_none()
&& let Some(val) = headers.get("retry-after")
&& let Ok(s) = val.to_str()
{
info.retry_after_secs = s.parse().ok();
}
// x-ratelimit-remaining-requests
if let Some(val) = headers.get("x-ratelimit-remaining-requests")
&& let Ok(s) = val.to_str()
{
info.requests_remaining = s.parse().ok();
}
// x-ratelimit-remaining-tokens
if let Some(val) = headers.get("x-ratelimit-remaining-tokens")
&& let Ok(s) = val.to_str()
{
// OpenAI sometimes returns -1 for unlimited
let val: i64 = s.parse().unwrap_or(-1);
if val >= 0 {
info.tokens_remaining = Some(val as u32);
}
}
// x-ratelimit-reset-requests (e.g., "1s", "6m0s")
if let Some(val) = headers.get("x-ratelimit-reset-requests")
&& let Ok(s) = val.to_str()
{
info.requests_reset = Some(s.to_string());
// Try to parse as seconds for retry-after fallback
if info.retry_after_secs.is_none() {
info.retry_after_secs = parse_duration_string(s);
}
}
// x-ratelimit-reset-tokens
if let Some(val) = headers.get("x-ratelimit-reset-tokens")
&& let Ok(s) = val.to_str()
{
info.tokens_reset = Some(s.to_string());
}
// Determine limit type
if info.requests_remaining == Some(0) {
info.limit_type = Some(RateLimitType::Requests);
} else if info.tokens_remaining == Some(0) {
info.limit_type = Some(RateLimitType::TotalTokens);
}
info
}
}
/// Parse duration strings like "1s", "6m0s", "1h30m"
fn parse_duration_string(s: &str) -> Option<u64> {
let s = s.trim();
if s.is_empty() {
return None;
}
let mut total_secs: u64 = 0;
let mut current_num = String::new();
for c in s.chars() {
if c.is_ascii_digit() {
current_num.push(c);
} else {
let num: u64 = current_num.parse().ok()?;
current_num.clear();
match c {
'h' => total_secs += num * 3600,
'm' => total_secs += num * 60,
's' => total_secs += num,
_ => return None,
}
}
}
if total_secs > 0 {
Some(total_secs)
} else {
None
}
}
/// Metadata about retry attempts for observability
#[derive(Debug, Clone, Default)]
pub struct RetryMetadata {
/// Number of retry attempts made (0 = succeeded on first try)
pub attempts: u32,
/// Total time spent waiting between retries
pub total_retry_wait: Duration,
/// Rate limit info from the last 429 response (if any)
pub last_rate_limit_info: Option<RateLimitInfo>,
}
impl RetryMetadata {
/// Check if any retries were made
pub fn had_retries(&self) -> bool {
self.attempts > 0
}
/// Create metadata for a successful first attempt
pub fn first_attempt_success() -> Self {
Self::default()
}
/// Record a retry attempt
pub fn record_retry(
&mut self,
wait_duration: Duration,
rate_limit_info: Option<RateLimitInfo>,
) {
self.attempts += 1;
self.total_retry_wait += wait_duration;
if rate_limit_info.is_some() {
self.last_rate_limit_info = rate_limit_info;
}
}
}
/// Check if an HTTP status code is a rate limit error (429)
pub fn is_rate_limit_status(status: reqwest::StatusCode) -> bool {
status == reqwest::StatusCode::TOO_MANY_REQUESTS
}
/// Check if an error is a transient error that should be retried.
///
/// Matches official SDK behavior - retries on:
/// - 408 Request Timeout
/// - 409 Conflict (lock timeout)
/// - 429 Too Many Requests (rate limit)
/// - 5xx Server errors (except 501 Not Implemented)
pub fn is_transient_error(status: reqwest::StatusCode) -> bool {
// 408 Request Timeout
if status == reqwest::StatusCode::REQUEST_TIMEOUT {
return true;
}
// 409 Conflict (often lock timeout in APIs)
if status == reqwest::StatusCode::CONFLICT {
return true;
}
// 429 Too Many Requests
if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
return true;
}
// 5xx Server errors (except 501 Not Implemented)
if status.is_server_error() && status != reqwest::StatusCode::NOT_IMPLEMENTED {
return true;
}
false
}
/// Check if an in-band provider error message looks transient and safe to retry.
///
/// This complements HTTP-status-based retry detection for streaming APIs that can
/// emit retryable provider failures inside an otherwise successful event stream.
pub fn is_transient_error_message(message: &str) -> bool {
let msg = message.trim().to_ascii_lowercase();
[
"server_error",
"internal server error",
"overloaded",
"overloaded_error",
"rate limit",
"too many requests",
"request timeout",
"timed out",
"service unavailable",
"bad gateway",
"gateway timeout",
"temporarily unavailable",
]
.iter()
.any(|needle| msg.contains(needle))
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config_matches_official_sdks() {
// Defaults should match official Anthropic/OpenAI SDK behavior
let config = LlmRetryConfig::default();
assert_eq!(config.max_retries, 2); // SDK default is 2
assert_eq!(config.initial_backoff, Duration::from_secs(1));
assert_eq!(config.max_backoff, Duration::from_secs(60));
assert_eq!(config.backoff_multiplier, 2.0);
assert!((config.jitter_factor - 0.25).abs() < 0.001); // SDK uses ±25%
}
#[test]
fn test_calculate_backoff_exponential() {
let config = LlmRetryConfig {
initial_backoff: Duration::from_secs(1),
max_backoff: Duration::from_secs(60),
backoff_multiplier: 2.0,
jitter_factor: 0.0, // No jitter for predictable test
..Default::default()
};
// attempt 0: 1s * 2^0 = 1s
assert_eq!(config.calculate_backoff(0), Duration::from_secs(1));
// attempt 1: 1s * 2^1 = 2s
assert_eq!(config.calculate_backoff(1), Duration::from_secs(2));
// attempt 2: 1s * 2^2 = 4s
assert_eq!(config.calculate_backoff(2), Duration::from_secs(4));
// attempt 3: 1s * 2^3 = 8s
assert_eq!(config.calculate_backoff(3), Duration::from_secs(8));
}
#[test]
fn test_calculate_backoff_capped() {
let config = LlmRetryConfig {
initial_backoff: Duration::from_secs(10),
max_backoff: Duration::from_secs(30),
backoff_multiplier: 2.0,
jitter_factor: 0.0,
..Default::default()
};
// attempt 0: 10s
assert_eq!(config.calculate_backoff(0), Duration::from_secs(10));
// attempt 1: 20s
assert_eq!(config.calculate_backoff(1), Duration::from_secs(20));
// attempt 2: 40s -> capped to 30s
assert_eq!(config.calculate_backoff(2), Duration::from_secs(30));
// attempt 3: 80s -> capped to 30s
assert_eq!(config.calculate_backoff(3), Duration::from_secs(30));
}
#[test]
fn test_parse_duration_string() {
assert_eq!(parse_duration_string("1s"), Some(1));
assert_eq!(parse_duration_string("30s"), Some(30));
assert_eq!(parse_duration_string("1m"), Some(60));
assert_eq!(parse_duration_string("6m0s"), Some(360));
assert_eq!(parse_duration_string("1h"), Some(3600));
assert_eq!(parse_duration_string("1h30m"), Some(5400));
assert_eq!(parse_duration_string("1h30m45s"), Some(5445));
assert_eq!(parse_duration_string(""), None);
assert_eq!(parse_duration_string("invalid"), None);
}
#[test]
fn test_rate_limit_info_recommended_wait_with_retry_after() {
let config = LlmRetryConfig::default();
let info = RateLimitInfo {
retry_after_secs: Some(10),
..Default::default()
};
// Should use retry-after, not exponential backoff
assert_eq!(info.recommended_wait(&config, 0), Duration::from_secs(10));
assert_eq!(info.recommended_wait(&config, 5), Duration::from_secs(10));
}
#[test]
fn test_rate_limit_info_recommended_wait_capped_at_60s() {
// Like official SDKs, if retry-after > 60s, use backoff instead
let config = LlmRetryConfig {
jitter_factor: 0.0, // No jitter for predictable test
..Default::default()
};
let info = RateLimitInfo {
retry_after_secs: Some(120), // 2 minutes - too long
..Default::default()
};
// Should fall back to exponential backoff, not use 120s
assert_eq!(info.recommended_wait(&config, 0), Duration::from_secs(1));
}
#[test]
fn test_rate_limit_info_recommended_wait_fallback() {
let config = LlmRetryConfig {
initial_backoff: Duration::from_secs(1),
backoff_multiplier: 2.0,
jitter_factor: 0.0,
..Default::default()
};
let info = RateLimitInfo::default(); // No retry-after
// Should use exponential backoff
assert_eq!(info.recommended_wait(&config, 0), Duration::from_secs(1));
assert_eq!(info.recommended_wait(&config, 1), Duration::from_secs(2));
}
#[test]
fn test_retry_metadata_record() {
let mut meta = RetryMetadata::default();
assert!(!meta.had_retries());
assert_eq!(meta.attempts, 0);
meta.record_retry(Duration::from_secs(1), None);
assert!(meta.had_retries());
assert_eq!(meta.attempts, 1);
assert_eq!(meta.total_retry_wait, Duration::from_secs(1));
meta.record_retry(Duration::from_secs(2), None);
assert_eq!(meta.attempts, 2);
assert_eq!(meta.total_retry_wait, Duration::from_secs(3));
}
#[test]
fn test_is_transient_error_matches_official_sdks() {
// Official SDKs retry on: 408, 409, 429, 5xx (except 501)
assert!(is_transient_error(reqwest::StatusCode::REQUEST_TIMEOUT)); // 408
assert!(is_transient_error(reqwest::StatusCode::CONFLICT)); // 409
assert!(is_transient_error(reqwest::StatusCode::TOO_MANY_REQUESTS)); // 429
assert!(is_transient_error(
reqwest::StatusCode::INTERNAL_SERVER_ERROR
)); // 500
assert!(is_transient_error(reqwest::StatusCode::BAD_GATEWAY)); // 502
assert!(is_transient_error(reqwest::StatusCode::SERVICE_UNAVAILABLE)); // 503
assert!(is_transient_error(reqwest::StatusCode::GATEWAY_TIMEOUT)); // 504
// Not transient
assert!(!is_transient_error(reqwest::StatusCode::OK));
assert!(!is_transient_error(reqwest::StatusCode::BAD_REQUEST)); // 400
assert!(!is_transient_error(reqwest::StatusCode::UNAUTHORIZED)); // 401
assert!(!is_transient_error(reqwest::StatusCode::FORBIDDEN)); // 403
assert!(!is_transient_error(reqwest::StatusCode::NOT_FOUND)); // 404
assert!(!is_transient_error(reqwest::StatusCode::NOT_IMPLEMENTED)); // 501
}
#[test]
fn test_is_transient_error_message_detects_provider_server_errors() {
assert!(is_transient_error_message(
"server_error: An error occurred while processing your request."
));
assert!(is_transient_error_message("Rate limit exceeded"));
assert!(is_transient_error_message(
"Service temporarily unavailable"
));
}
#[test]
fn test_is_transient_error_message_rejects_non_retryable_messages() {
assert!(!is_transient_error_message(
"invalid_request_error: bad tool schema"
));
assert!(!is_transient_error_message("Model not available: gpt-99"));
}
#[test]
fn test_max_retry_after_constant() {
// Verify the constant matches SDK behavior
assert_eq!(MAX_RETRY_AFTER_SECS, 60);
}
}