litellm-rs 0.6.0

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
Documentation
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
use super::{ContextualError, ProviderError, ProviderHttpErrorFacts, provider_http_error_facts};
use crate::core::providers::failure::ProviderFailureFacts;
use crate::utils::error::{CanonicalError, ErrorCode};
use regex::Regex;
use std::sync::OnceLock;
use url::Url;

const REDACTED: &str = "[REDACTED]";

fn compiled_regex<'a>(cell: &'a OnceLock<Option<Regex>>, pattern: &str) -> Option<&'a Regex> {
    cell.get_or_init(|| Regex::new(pattern).ok()).as_ref()
}

fn redact_sensitive_text(value: &str) -> String {
    static URL_PATTERN: OnceLock<Option<Regex>> = OnceLock::new();
    static HEADER_PATTERN: OnceLock<Option<Regex>> = OnceLock::new();
    static AUTH_SCHEME_PATTERN: OnceLock<Option<Regex>> = OnceLock::new();
    static SECRET_PAIR_PATTERN: OnceLock<Option<Regex>> = OnceLock::new();
    static KNOWN_CREDENTIAL_PATTERN: OnceLock<Option<Regex>> = OnceLock::new();
    static JWT_PATTERN: OnceLock<Option<Regex>> = OnceLock::new();

    let Some(url_pattern) = compiled_regex(&URL_PATTERN, r#"(?i)https?://[^\s<>"']+"#) else {
        return REDACTED.to_string();
    };
    let Some(header_pattern) = compiled_regex(
        &HEADER_PATTERN,
        r#"(?im)\b(authorization|proxy-authorization|cookie|set-cookie)["']?\s*[:=]\s*[^\r\n]+"#,
    ) else {
        return REDACTED.to_string();
    };
    let Some(auth_scheme_pattern) = compiled_regex(
        &AUTH_SCHEME_PATTERN,
        r"(?i)\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+",
    ) else {
        return REDACTED.to_string();
    };
    let Some(secret_pair_pattern) = compiled_regex(
        &SECRET_PAIR_PATTERN,
        r#"(?i)(["']?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|client[_-]?secret|secret[_-]?access[_-]?key|private[_-]?key|credential|password|passwd|token|secret|signature|sig)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)"#,
    ) else {
        return REDACTED.to_string();
    };
    let Some(known_credential_pattern) = compiled_regex(
        &KNOWN_CREDENTIAL_PATTERN,
        r"\b(?:sk-[A-Za-z0-9_-]{8,}|AIza[A-Za-z0-9_-]{16,}|AKIA[A-Z0-9]{12,}|gh[pousr]_[A-Za-z0-9]{12,}|xox[baprs]-[A-Za-z0-9-]{8,})\b",
    ) else {
        return REDACTED.to_string();
    };
    let Some(jwt_pattern) = compiled_regex(
        &JWT_PATTERN,
        r"\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\b",
    ) else {
        return REDACTED.to_string();
    };

    let value = url_pattern
        .replace_all(value, |captures: &regex::Captures<'_>| {
            redact_url(&captures[0])
        })
        .into_owned();
    let value = header_pattern
        .replace_all(&value, |captures: &regex::Captures<'_>| {
            format!("{}: {REDACTED}", &captures[1])
        })
        .into_owned();
    let value = auth_scheme_pattern
        .replace_all(&value, |captures: &regex::Captures<'_>| {
            format!("{} {REDACTED}", &captures[1])
        })
        .into_owned();
    let value = secret_pair_pattern
        .replace_all(&value, |captures: &regex::Captures<'_>| {
            format!("{}{REDACTED}", &captures[1])
        })
        .into_owned();
    let value = known_credential_pattern
        .replace_all(&value, REDACTED)
        .into_owned();
    jwt_pattern.replace_all(&value, REDACTED).into_owned()
}

fn redact_url(candidate: &str) -> String {
    let core = candidate.trim_end_matches(['.', ',', ';', ')', ']', '}']);
    let suffix = &candidate[core.len()..];
    let Ok(mut url) = Url::parse(core) else {
        return REDACTED.to_string();
    };

    if !url.username().is_empty() && url.set_username(REDACTED).is_err() {
        return REDACTED.to_string();
    }
    if url.password().is_some() && url.set_password(Some(REDACTED)).is_err() {
        return REDACTED.to_string();
    }
    if url.query().is_some() {
        let keys = url
            .query_pairs()
            .map(|(key, _)| key.into_owned())
            .collect::<Vec<_>>();
        url.set_query(None);
        let mut query = url.query_pairs_mut();
        for key in keys {
            query.append_pair(&key, REDACTED);
        }
    }
    if url.fragment().is_some() {
        url.set_fragment(Some(REDACTED));
    }

    format!("{url}{suffix}")
}

impl ProviderError {
    fn bedrock_modeled_retry_provider() -> &'static str {
        use std::sync::OnceLock;

        static PROVIDER: OnceLock<Box<str>> = OnceLock::new();
        PROVIDER.get_or_init(|| "bedrock".into()).as_ref()
    }

    /// Create authentication error
    pub fn authentication(provider: &'static str, message: impl Into<String>) -> Self {
        Self::Authentication {
            provider,
            message: message.into(),
        }
    }

    /// Create rate limit error
    pub fn rate_limit(provider: &'static str, retry_after: Option<u64>) -> Self {
        Self::RateLimit {
            provider,
            message: match retry_after {
                Some(seconds) => format!("Rate limit exceeded. Retry after {} seconds", seconds),
                None => "Rate limit exceeded".to_string(),
            },
            retry_after,
            rpm_limit: None,
            tpm_limit: None,
            current_usage: None,
        }
    }

    /// Create enhanced rate limit error with usage details
    pub fn rate_limit_with_limits(
        provider: &'static str,
        retry_after: Option<u64>,
        rpm_limit: Option<u32>,
        tpm_limit: Option<u32>,
        current_usage: Option<f64>,
    ) -> Self {
        let message = match (rpm_limit, tpm_limit) {
            (Some(rpm), Some(tpm)) => {
                format!("Rate limit exceeded: {}RPM, {}TPM limits reached", rpm, tpm)
            }
            (Some(rpm), None) => format!("Rate limit exceeded: {}RPM limit reached", rpm),
            (None, Some(tpm)) => format!("Rate limit exceeded: {}TPM limit reached", tpm),
            (None, None) => "Rate limit exceeded".to_string(),
        };

        Self::RateLimit {
            provider,
            message,
            retry_after,
            rpm_limit,
            tpm_limit,
            current_usage,
        }
    }

    /// Create quota exceeded error
    pub fn quota_exceeded(provider: &'static str, message: impl Into<String>) -> Self {
        Self::QuotaExceeded {
            provider,
            message: message.into(),
        }
    }

    /// Create simple rate limit error (convenience method)
    pub fn rate_limit_simple(provider: &'static str, message: impl Into<String>) -> Self {
        Self::RateLimit {
            provider,
            message: message.into(),
            retry_after: None,
            rpm_limit: None,
            tpm_limit: None,
            current_usage: None,
        }
    }

    /// Create rate limit error with retry_after only
    pub fn rate_limit_with_retry(
        provider: &'static str,
        message: impl Into<String>,
        retry_after: Option<u64>,
    ) -> Self {
        Self::RateLimit {
            provider,
            message: message.into(),
            retry_after,
            rpm_limit: None,
            tpm_limit: None,
            current_usage: None,
        }
    }

    /// Create model not found error
    pub fn model_not_found(provider: &'static str, model: impl Into<String>) -> Self {
        Self::ModelNotFound {
            provider,
            model: model.into(),
        }
    }

    /// Create invalid request error
    pub fn invalid_request(provider: &'static str, message: impl Into<String>) -> Self {
        Self::InvalidRequest {
            provider,
            message: message.into(),
        }
    }

    /// Create network error
    pub fn network(provider: &'static str, message: impl Into<String>) -> Self {
        Self::Network {
            provider,
            message: message.into(),
        }
    }

    /// Create provider unavailable error
    pub fn provider_unavailable(provider: &'static str, message: impl Into<String>) -> Self {
        Self::ProviderUnavailable {
            provider,
            message: message.into(),
        }
    }

    /// Create not supported error
    pub fn not_supported(provider: &'static str, feature: impl Into<String>) -> Self {
        Self::NotSupported {
            provider,
            feature: feature.into(),
        }
    }

    /// Create not implemented error
    pub fn not_implemented(provider: &'static str, feature: impl Into<String>) -> Self {
        Self::NotImplemented {
            provider,
            feature: feature.into(),
        }
    }

    /// Create configuration error
    pub fn configuration(provider: &'static str, message: impl Into<String>) -> Self {
        Self::Configuration {
            provider,
            message: message.into(),
        }
    }

    /// Create serialization error
    pub fn serialization(provider: &'static str, message: impl Into<String>) -> Self {
        Self::Serialization {
            provider,
            message: message.into(),
        }
    }

    /// Create timeout error
    pub fn timeout(provider: &'static str, message: impl Into<String>) -> Self {
        Self::Timeout {
            provider,
            message: message.into(),
        }
    }

    /// Create initialization error (provider failed to start)
    pub fn initialization(provider: &'static str, message: impl Into<String>) -> Self {
        Self::Network {
            provider,
            message: format!("Initialization failed: {}", message.into()),
        }
    }

    // Enhanced factory methods for new error variants

    /// Create context length exceeded error with structured data
    pub fn context_length_exceeded(provider: &'static str, max: usize, actual: usize) -> Self {
        Self::ContextLengthExceeded {
            provider,
            max,
            actual,
        }
    }

    /// Create API error with status code
    pub fn api_error(provider: &'static str, status: u16, message: impl Into<String>) -> Self {
        // Never propagate the internal Bedrock provenance token through a public constructor.
        let provider = if provider == "bedrock" {
            "bedrock"
        } else {
            provider
        };
        Self::ApiError {
            provider,
            status,
            message: message.into(),
        }
    }

    /// Create a Bedrock 424 whose retry provenance came from a structured AWS error code.
    pub(crate) fn bedrock_modeled_retry_error(message: impl Into<String>) -> Self {
        Self::ApiError {
            provider: Self::bedrock_modeled_retry_provider(),
            status: 424,
            message: message.into(),
        }
    }

    /// Whether this API error carries the internal Bedrock modeled-error identity.
    pub(crate) fn is_bedrock_modeled_retry_error(&self) -> bool {
        matches!(
            self,
            Self::ApiError {
                provider,
                status: 424,
                ..
            } if std::ptr::eq(*provider, Self::bedrock_modeled_retry_provider())
        )
    }

    /// Create token limit exceeded error
    pub fn token_limit_exceeded(provider: &'static str, message: impl Into<String>) -> Self {
        Self::TokenLimitExceeded {
            provider,
            message: message.into(),
        }
    }

    /// Create feature disabled error
    pub fn feature_disabled(provider: &'static str, feature: impl Into<String>) -> Self {
        Self::FeatureDisabled {
            provider,
            feature: feature.into(),
        }
    }

    /// Create Azure deployment error
    pub fn deployment_error(deployment: impl Into<String>, message: impl Into<String>) -> Self {
        Self::DeploymentError {
            provider: "azure",
            deployment: deployment.into(),
            message: message.into(),
        }
    }

    /// Create response parsing error
    pub fn response_parsing(provider: &'static str, message: impl Into<String>) -> Self {
        Self::ResponseParsing {
            provider,
            message: message.into(),
        }
    }

    /// Create routing error
    pub fn routing_error(
        provider: &'static str,
        attempted_providers: Vec<String>,
        message: impl Into<String>,
    ) -> Self {
        Self::RoutingError {
            provider,
            attempted_providers,
            message: message.into(),
        }
    }

    /// Create transformation error
    pub fn transformation_error(
        provider: &'static str,
        from_format: impl Into<String>,
        to_format: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self::TransformationError {
            provider,
            from_format: from_format.into(),
            to_format: to_format.into(),
            message: message.into(),
        }
    }

    /// Create content filtered error
    pub fn content_filtered(
        provider: &'static str,
        reason: impl Into<String>,
        policy_violations: Option<Vec<String>>,
        potentially_retryable: Option<bool>,
    ) -> Self {
        Self::ContentFiltered {
            provider,
            reason: reason.into(),
            policy_violations,
            potentially_retryable,
        }
    }

    /// Create cancellation error
    pub fn cancelled(
        provider: &'static str,
        operation_type: impl Into<String>,
        cancellation_reason: Option<String>,
    ) -> Self {
        Self::Cancelled {
            provider,
            operation_type: operation_type.into(),
            cancellation_reason,
        }
    }

    /// Create streaming error
    pub fn streaming_error(
        provider: &'static str,
        stream_type: impl Into<String>,
        position: Option<u64>,
        last_chunk: Option<String>,
        message: impl Into<String>,
    ) -> Self {
        Self::Streaming {
            provider,
            stream_type: stream_type.into(),
            position,
            last_chunk,
            message: message.into(),
        }
    }

    /// Create other/generic error
    pub fn other(provider: &'static str, message: impl Into<String>) -> Self {
        Self::Other {
            provider,
            message: message.into(),
        }
    }

    /// Get the provider name that caused this error
    pub fn provider(&self) -> &'static str {
        match self {
            Self::Authentication { provider, .. }
            | Self::RateLimit { provider, .. }
            | Self::QuotaExceeded { provider, .. }
            | Self::ModelNotFound { provider, .. }
            | Self::InvalidRequest { provider, .. }
            | Self::Network { provider, .. }
            | Self::ProviderUnavailable { provider, .. }
            | Self::NotSupported { provider, .. }
            | Self::NotImplemented { provider, .. }
            | Self::Configuration { provider, .. }
            | Self::Serialization { provider, .. }
            | Self::Timeout { provider, .. }
            | Self::ContextLengthExceeded { provider, .. }
            | Self::ContentFiltered { provider, .. }
            | Self::TokenLimitExceeded { provider, .. }
            | Self::FeatureDisabled { provider, .. }
            | Self::DeploymentError { provider, .. }
            | Self::ResponseParsing { provider, .. }
            | Self::RoutingError { provider, .. }
            | Self::TransformationError { provider, .. }
            | Self::Cancelled { provider, .. }
            | Self::Streaming { provider, .. }
            | Self::Other { provider, .. } => provider,
            Self::ApiError { provider, .. }
                if std::ptr::eq(*provider, Self::bedrock_modeled_retry_provider()) =>
            {
                "bedrock"
            }
            Self::ApiError { provider, .. } => provider,
        }
    }

    /// Check if this error is retryable
    #[deprecated(
        since = "0.6.0",
        note = "use RetryPolicy::decide with ProviderFailureFacts for provider routing/retry; removal tracked in 0.7.0 follow-up (SP965-T010)"
    )]
    pub fn is_retryable(&self) -> bool {
        ProviderFailureFacts::from_error(self).legacy_retryable
    }

    /// Get retry delay in seconds
    pub fn retry_delay(&self) -> Option<u64> {
        ProviderFailureFacts::from_error(self)
            .legacy_retry_delay
            .map(|delay| delay.as_secs())
    }

    /// Canonical closed-set classification for protocol adapters.
    pub fn canonical_code(&self) -> ErrorCode {
        CanonicalError::canonical_code(self)
    }

    /// Return a typed copy safe for logs, protocol adapters, and public errors.
    ///
    /// The original variant and non-secret identity/limit fields are preserved.
    pub fn redacted(&self) -> Self {
        let mut redacted = self.clone();
        match &mut redacted {
            Self::Authentication { message, .. }
            | Self::QuotaExceeded { message, .. }
            | Self::InvalidRequest { message, .. }
            | Self::Network { message, .. }
            | Self::ProviderUnavailable { message, .. }
            | Self::Configuration { message, .. }
            | Self::Serialization { message, .. }
            | Self::Timeout { message, .. }
            | Self::ApiError { message, .. }
            | Self::TokenLimitExceeded { message, .. }
            | Self::ResponseParsing { message, .. }
            | Self::Other { message, .. } => {
                *message = redact_sensitive_text(message);
            }
            Self::RateLimit { message, .. } => {
                *message = redact_sensitive_text(message);
            }
            Self::ContentFiltered {
                reason,
                policy_violations,
                ..
            } => {
                *reason = redact_sensitive_text(reason);
                if let Some(violations) = policy_violations {
                    for violation in violations {
                        *violation = redact_sensitive_text(violation);
                    }
                }
            }
            Self::DeploymentError { message, .. }
            | Self::RoutingError { message, .. }
            | Self::TransformationError { message, .. } => {
                *message = redact_sensitive_text(message);
            }
            Self::Cancelled {
                cancellation_reason,
                ..
            } => {
                if let Some(reason) = cancellation_reason {
                    *reason = redact_sensitive_text(reason);
                }
            }
            Self::Streaming {
                last_chunk,
                message,
                ..
            } => {
                if let Some(chunk) = last_chunk {
                    *chunk = redact_sensitive_text(chunk);
                }
                *message = redact_sensitive_text(message);
            }
            Self::ModelNotFound { model, .. } => *model = redact_sensitive_text(model),
            Self::NotSupported { feature, .. }
            | Self::NotImplemented { feature, .. }
            | Self::FeatureDisabled { feature, .. } => {
                *feature = redact_sensitive_text(feature);
            }
            Self::ContextLengthExceeded { .. } => {}
        }
        redacted
    }

    /// Canonical HTTP facts for protocol adapters.
    pub fn http_facts(&self) -> ProviderHttpErrorFacts {
        provider_http_error_facts(self)
    }

    /// Create an error with request context for better debugging.
    ///
    /// Returns a `ContextualError` that wraps this error with additional request information.
    ///
    /// # Example
    /// ```rust
    /// # use litellm_rs::ProviderError;
    /// let err = ProviderError::network("openai", "Connection refused")
    ///     .with_context("req-123", Some("gpt-4"));
    /// ```
    pub fn with_context(
        self,
        request_id: impl Into<String>,
        model: Option<&str>,
    ) -> ContextualError {
        ContextualError::new(self, request_id, model)
    }

    /// Get HTTP status code for this error
    pub fn http_status(&self) -> u16 {
        super::provider_http_error_facts(self).status
    }
}

#[cfg(test)]
mod redaction_tests {
    use super::*;

    const RAW_KEY: &str = "sk-raw-secret-123456789";
    const RAW_SIGNATURE: &str = "signed-value-123";

    fn assert_secret_absent(error: &ProviderError) {
        let display = error.to_string();
        let debug = format!("{error:?}");
        for raw in [RAW_KEY, RAW_SIGNATURE, "cookie-value", "password-value"] {
            assert!(!display.contains(raw), "Display leaked {raw}: {display}");
            assert!(!debug.contains(raw), "Debug leaked {raw}: {debug}");
        }
        assert!(display.contains(REDACTED) || debug.contains(REDACTED));
    }

    #[test]
    fn redacted_preserves_variant_provider_and_limits() {
        let error = ProviderError::RateLimit {
            provider: "openai",
            message: format!("Authorization: Bearer {RAW_KEY}"),
            retry_after: Some(7),
            rpm_limit: Some(60),
            tpm_limit: Some(1_000),
            current_usage: Some(0.75),
        };

        let redacted = error.redacted();

        assert!(matches!(
            redacted,
            ProviderError::RateLimit {
                provider: "openai",
                retry_after: Some(7),
                rpm_limit: Some(60),
                tpm_limit: Some(1_000),
                current_usage: Some(0.75),
                ..
            }
        ));
        assert_eq!(redacted.canonical_code(), error.canonical_code());
        assert_secret_absent(&redacted);
    }

    #[test]
    fn redacted_covers_url_userinfo_signed_query_and_known_patterns() {
        let error = ProviderError::authentication(
            "openai",
            format!(
                r#"request HTTPS://user:password-value@example.com/v1?X-Amz-Signature={RAW_SIGNATURE} debug={{"Cookie":"session=cookie-value","Authorization":"ApiKey password-value"}}"#
            ),
        );
        let malformed = ProviderError::authentication(
            "openai",
            format!("request https://user:password-value@[::1?X-Amz-Signature={RAW_SIGNATURE}"),
        );

        for redacted in [error.redacted(), malformed.redacted()] {
            assert!(matches!(
                redacted,
                ProviderError::Authentication {
                    provider: "openai",
                    ..
                }
            ));
            assert_secret_absent(&redacted);
        }
    }

    #[test]
    fn redacted_covers_reason_and_optional_body_fields() {
        let content = ProviderError::content_filtered(
            "vertex_ai",
            format!("client_secret={RAW_KEY}"),
            Some(vec![format!("password=password-value; token={RAW_KEY}")]),
            Some(true),
        )
        .redacted();
        let streaming = ProviderError::streaming_error(
            "openai",
            "chat",
            Some(9),
            Some(format!(r#"{{"access_token":"{RAW_KEY}"}}"#)),
            format!("Bearer {RAW_KEY}"),
        )
        .redacted();
        let cancelled =
            ProviderError::cancelled("openai", "chat", Some(format!("signature={RAW_SIGNATURE}")))
                .redacted();

        for error in [&content, &streaming, &cancelled] {
            assert_secret_absent(error);
        }
        assert!(matches!(
            content,
            ProviderError::ContentFiltered {
                provider: "vertex_ai",
                potentially_retryable: Some(true),
                ..
            }
        ));
        assert!(matches!(
            streaming,
            ProviderError::Streaming {
                provider: "openai",
                stream_type,
                position: Some(9),
                ..
            } if stream_type == "chat"
        ));
    }

    #[test]
    fn redacted_preserves_model_and_deployment_identity() {
        let identities = [
            ProviderError::model_not_found(
                "openai",
                format!("gpt-safe https://example.com?signature={RAW_SIGNATURE}"),
            ),
            ProviderError::not_supported("openai", format!("audio-safe Authorization: {RAW_KEY}")),
            ProviderError::not_implemented("openai", "batch-safe Cookie: session=cookie-value"),
            ProviderError::feature_disabled("vertex_ai", "vision-safe password=password-value"),
        ];
        let redacted = identities.map(|error| error.redacted());
        let combined = ProviderError::other("identity", format!("{redacted:?}"));
        let deployment =
            ProviderError::deployment_error("deployment-safe", format!("api_key={RAW_KEY}"))
                .redacted();

        for safe in ["gpt-safe", "audio-safe", "batch-safe", "vision-safe"] {
            assert!(combined.to_string().contains(safe));
        }
        assert!(matches!(
            deployment,
            ProviderError::DeploymentError {
                provider: "azure",
                ref deployment,
                ..
            } if deployment == "deployment-safe"
        ));
        assert_secret_absent(&combined);
        assert_secret_absent(&deployment);
    }
}