oxi-ai 0.20.0

Unified LLM API — multi-provider streaming interface for AI coding assistants
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
//! Per-provider circuit breaker implementation.
//!
//! This module provides a thread-safe circuit breaker pattern for managing
//! provider failures in the oxi-ai library. Each provider can have its own
//! circuit breaker instance that prevents cascading failures by temporarily
//! blocking requests to unhealthy providers.
//!
//! # Circuit States
//!
//! - **Closed**: Normal operation. All requests are allowed through.
//!   Failures are counted, and the circuit opens after reaching the threshold.
//!
//! - **Open**: The provider is considered unhealthy. Requests are blocked
//!   for a configurable duration, then the circuit transitions to half-open
//!   to test recovery.
//!
//! - **Half-Open**: Recovery testing mode. A limited number of requests
//!   are allowed to test if the provider has recovered. If enough succeed,
//!   the circuit closes; if any fail, the circuit reopens.
//!
//! # Example
//!
//! ```rust
//! use std::time::Duration;
//! use oxi_ai::circuit_breaker::{CircuitBreakerConfig, ProviderCircuitBreaker};
//!
//! let config = CircuitBreakerConfig::default();
//! let breaker = ProviderCircuitBreaker::new("openai".to_string(), config);
//!
//! // Check if request is allowed
//! match breaker.allow_request() {
//!     Ok(()) => { /* proceed with request */ }
//!     Err(e) => { /* circuit is open, retry after e.remaining */ }
//! }
//! ```
//!
//! # Thread Safety
//!
//! All state is managed using atomic operations and parking_lot mutex,
//! making this implementation safe for concurrent access from multiple
//! async tasks or threads.

use parking_lot::Mutex;
use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
use std::time::{Duration, Instant};
use thiserror::Error;

// ============================================================================
// Circuit State
// ============================================================================

/// Circuit breaker states.
///
/// The state is stored as a `u8` in an atomic, so these values correspond
/// to the numeric representation (0, 1, 2) for efficient atomic operations.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CircuitState {
    /// Normal operation. All requests are allowed through.
    /// Failures increment the consecutive failure counter.
    Closed = 0,

    /// Provider is unhealthy. Requests are blocked for a configured duration.
    /// After the duration elapses, transitions to `HalfOpen`.
    Open = 1,

    /// Recovery testing mode. Limited requests are allowed.
    /// Successes are counted; circuit closes after `half_open_successes` succeed.
    /// Any failure reopens the circuit.
    HalfOpen = 2,
}

impl CircuitState {
    /// Convert a raw u8 value to a `CircuitState`.
    ///
    /// Returns `CircuitState::HalfOpen` for any value >= 2 to handle
    /// potential future state additions gracefully.
    #[inline]
    fn from_u8(value: u8) -> Self {
        match value {
            0 => Self::Closed,
            1 => Self::Open,
            _ => Self::HalfOpen,
        }
    }

    /// Convert `CircuitState` to its numeric representation.
    #[inline]
    fn as_u8(&self) -> u8 {
        *self as u8
    }
}

// ============================================================================
// Circuit Breaker Configuration
// ============================================================================

/// Configuration parameters for a provider circuit breaker.
///
/// All parameters can be tuned based on the provider's reliability and
/// the acceptable impact of failures on your application.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CircuitBreakerConfig {
    /// Number of consecutive failures required to open the circuit.
    ///
    /// Default: 5
    ///
    /// A lower value makes the circuit more sensitive to failures,
    /// while a higher value requires more failures before opening.
    pub failure_threshold: u32,

    /// Duration to keep the circuit open before transitioning to half-open.
    ///
    /// Default: 30 seconds
    ///
    /// This should be long enough for the provider to recover from
    /// whatever caused the failures (e.g., rate limits, temporary outages).
    pub open_duration: Duration,

    /// Number of successful requests required in half-open state to close the circuit.
    ///
    /// Default: 1
    ///
    /// Setting this higher makes recovery testing more conservative,
    /// requiring multiple successful requests before fully trusting the provider.
    pub half_open_successes: u32,
}

impl Default for CircuitBreakerConfig {
    /// Creates a default circuit breaker configuration.
    ///
    /// The defaults are tuned for general-purpose use:
    /// - 5 failures before opening (reasonable for most APIs)
    /// - 30 second cooldown (enough for temporary issues to resolve)
    /// - 1 success to close (fast recovery testing)
    fn default() -> Self {
        Self {
            failure_threshold: 5,
            open_duration: Duration::from_secs(30),
            half_open_successes: 1,
        }
    }
}

impl CircuitBreakerConfig {
    /// Creates a new configuration with all values explicitly set.
    ///
    /// # Arguments
    ///
    /// * `failure_threshold` - Consecutive failures to trigger circuit opening
    /// * `open_duration` - Time to wait before testing recovery
    /// * `half_open_successes` - Successes needed in half-open to close circuit
    ///
    /// # Panics
    ///
    /// Panics if `failure_threshold` or `half_open_successes` are zero,
    /// as this would create an immediately opening circuit.
    #[inline]
    pub fn new(failure_threshold: u32, open_duration: Duration, half_open_successes: u32) -> Self {
        if failure_threshold == 0 {
            panic!("failure_threshold cannot be zero");
        }
        if half_open_successes == 0 {
            panic!("half_open_successes cannot be zero");
        }
        Self {
            failure_threshold,
            open_duration,
            half_open_successes,
        }
    }

    /// Sets the failure threshold.
    ///
    /// Returns a new configuration with the updated value.
    #[inline]
    #[must_use]
    pub fn with_failure_threshold(mut self, threshold: u32) -> Self {
        self.failure_threshold = threshold;
        self
    }

    /// Sets the open duration.
    ///
    /// Returns a new configuration with the updated value.
    #[inline]
    #[must_use]
    pub fn with_open_duration(mut self, duration: Duration) -> Self {
        self.open_duration = duration;
        self
    }

    /// Sets the half-open successes required.
    ///
    /// Returns a new configuration with the updated value.
    #[inline]
    #[must_use]
    pub fn with_half_open_successes(mut self, successes: u32) -> Self {
        self.half_open_successes = successes;
        self
    }
}

// ============================================================================
// Circuit Open Error
// ============================================================================

/// Error returned when attempting to make a request while the circuit is open.
///
/// This error indicates that the circuit breaker has blocked the request
/// because the provider is considered unhealthy. The `remaining` field
/// indicates how long you should wait before attempting another request.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[error("Circuit breaker open for provider '{provider}': retry after {remaining:?}")]
pub struct CircuitOpenError {
    /// The name of the provider whose circuit is open.
    pub provider: String,
    /// Time remaining before the circuit transitions to half-open.
    pub remaining: Duration,
}

impl CircuitOpenError {
    /// Creates a new circuit open error for the given provider and duration.
    #[inline]
    pub fn new(provider: impl Into<String>, remaining: Duration) -> Self {
        Self {
            provider: provider.into(),
            remaining,
        }
    }
}

// ============================================================================
// Provider Circuit Breaker
// ============================================================================

/// A per-provider circuit breaker for preventing cascading failures.
///
/// This struct manages the state machine for a single provider's circuit breaker.
/// It tracks consecutive failures and successes, manages state transitions,
/// and determines whether requests should be allowed.
///
/// # Thread Safety
///
/// All operations are thread-safe and can be called concurrently from
/// multiple async tasks or threads. The implementation uses atomic
/// operations for the fast path (checking state) and a mutex only for
/// the timestamp update when opening the circuit.
///
/// # State Machine
///
/// ```text
/// ┌─────────┐  failure_threshold reached   ┌────────┐
/// │ Closed  │ ───────────────────────────►  │  Open  │
/// └────┬────┘                               └───┬────┘
///      │                                         │
///      │ record_success()                         │ open_duration elapsed
///      │ (reset failures to 0)                    ▼
///      │                                   ┌───────────┐
///      │                                   │ Half-Open │
///      │                                   └─────┬─────┘
///      │                                         │
///      │                              half_open_successes reached
///      └─────────────────────────────────────────┘
///      │                                         ▲
///      │         any failure                     │
///      └─────────────────────────────────────────┘
/// ```
///
/// # Example
///
/// ```rust
/// use std::time::Duration;
/// use oxi_ai::circuit_breaker::{CircuitBreakerConfig, ProviderCircuitBreaker};
///
/// let config = CircuitBreakerConfig::default();
/// let breaker = ProviderCircuitBreaker::new("anthropic".to_string(), config);
///
/// // Check if a request is allowed
/// match breaker.allow_request() {
///     Ok(()) => {
///         // Proceed with the request
///     }
///     Err(e) => {
///         println!("Circuit open: {}", e);
///     }
/// }
/// ```
#[derive(Debug)]
pub struct ProviderCircuitBreaker {
    /// Identifier for the provider this breaker protects.
    provider_name: String,

    /// Configuration parameters for this circuit breaker.
    config: CircuitBreakerConfig,

    /// Current circuit state (0=Closed, 1=Open, 2=HalfOpen).
    /// Stored as atomic for lock-free reads.
    state: AtomicU8,

    /// Count of consecutive failures since last success in closed state.
    consecutive_failures: AtomicU64,

    /// Count of consecutive successes in half-open state.
    consecutive_successes: AtomicU64,

    /// Timestamp when the circuit was opened.
    /// Protected by mutex because it's rarely accessed (only in Open state).
    opened_at: Mutex<Option<Instant>>,
}

impl ProviderCircuitBreaker {
    /// Creates a new circuit breaker for the specified provider.
    ///
    /// # Arguments
    ///
    /// * `provider_name` - Identifier for the provider (e.g., "openai", "anthropic")
    /// * `config` - Circuit breaker configuration parameters
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxi_ai::circuit_breaker::{CircuitBreakerConfig, ProviderCircuitBreaker};
    ///
    /// let breaker = ProviderCircuitBreaker::new(
    ///     "openai".to_string(),
    ///     CircuitBreakerConfig::default(),
    /// );
    /// ```
    #[inline]
    pub fn new(provider_name: String, config: CircuitBreakerConfig) -> Self {
        Self {
            provider_name,
            config,
            state: AtomicU8::new(CircuitState::Closed.as_u8()),
            consecutive_failures: AtomicU64::new(0),
            consecutive_successes: AtomicU64::new(0),
            opened_at: Mutex::new(None),
        }
    }

    /// Creates a new circuit breaker with default configuration.
    ///
    /// # Arguments
    ///
    /// * `provider_name` - Identifier for the provider
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxi_ai::circuit_breaker::ProviderCircuitBreaker;
    ///
    /// let breaker = ProviderCircuitBreaker::with_defaults("openai".to_string());
    /// assert!(breaker.allow_request().is_ok());
    /// ```
    #[inline]
    pub fn with_defaults(provider_name: String) -> Self {
        Self::new(provider_name, CircuitBreakerConfig::default())
    }

    /// Checks whether a request should be allowed to proceed.
    ///
    /// Returns `Ok(())` if the request is allowed, or `Err(CircuitOpenError)`
    /// if the circuit is open and requests are blocked.
    ///
    /// # State Transitions
    ///
    /// - **Closed**: Always allows, but first call in Open state with elapsed
    ///   duration transitions to HalfOpen.
    ///
    /// - **Open**: Blocks requests. If `open_duration` has elapsed since
    ///   opening, transitions to HalfOpen and allows this request.
    ///
    /// - **HalfOpen**: Always allows (limited probe requests).
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxi_ai::circuit_breaker::{CircuitBreakerConfig, ProviderCircuitBreaker};
    ///
    /// let breaker = ProviderCircuitBreaker::new(
    ///     "openai".to_string(),
    ///     CircuitBreakerConfig::default(),
    /// );
    ///
    /// match breaker.allow_request() {
    ///     Ok(()) => {
    ///         // Proceed with the request
    ///     }
    ///     Err(e) => {
    ///         eprintln!("Circuit open: {}", e);
    ///     }
    /// }
    /// ```
    pub fn allow_request(&self) -> Result<(), CircuitOpenError> {
        let state = self.load_state();

        match state {
            CircuitState::Closed => {
                // Closed: always allow requests
                Ok(())
            }

            CircuitState::Open => {
                // Open: check if duration has elapsed
                let opened_at = self.opened_at.lock();

                if let Some(timestamp) = *opened_at {
                    let elapsed = timestamp.elapsed();

                    if elapsed >= self.config.open_duration {
                        // Duration elapsed: transition to half-open
                        drop(opened_at);
                        self.state
                            .store(CircuitState::HalfOpen.as_u8(), Ordering::SeqCst);
                        self.consecutive_successes.store(0, Ordering::SeqCst);
                        return Ok(());
                    }

                    // Still in cooldown period
                    let remaining = self.config.open_duration.saturating_sub(elapsed);
                    return Err(CircuitOpenError::new(&self.provider_name, remaining));
                }

                // No timestamp recorded somehow; treat as half-open
                drop(opened_at);
                self.state
                    .store(CircuitState::HalfOpen.as_u8(), Ordering::SeqCst);
                Ok(())
            }

            CircuitState::HalfOpen => {
                // HalfOpen: allow probe requests
                Ok(())
            }
        }
    }

    /// Records a successful request.
    ///
    /// Updates internal counters based on current state:
    ///
    /// - **Closed**: Resets failure counter to zero.
    ///
    /// - **HalfOpen**: Increments success counter. If threshold reached,
    ///   closes the circuit (transitions to Closed).
    ///
    /// - **Open**: No effect (successes don't matter while waiting for cooldown).
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxi_ai::circuit_breaker::{CircuitBreakerConfig, ProviderCircuitBreaker};
    ///
    /// let breaker = ProviderCircuitBreaker::new(
    ///     "openai".to_string(),
    ///     CircuitBreakerConfig::default(),
    /// );
    ///
    /// // Simulate a successful request
    /// breaker.record_success();
    /// ```
    pub fn record_success(&self) {
        let state = self.load_state();

        match state {
            CircuitState::Closed => {
                // Reset failure counter on success in closed state
                self.consecutive_failures.store(0, Ordering::SeqCst);
            }

            CircuitState::HalfOpen => {
                // Count successes in half-open state
                let prev = self.consecutive_successes.fetch_add(1, Ordering::SeqCst);
                let new_count = prev + 1;

                if new_count >= self.config.half_open_successes as u64 {
                    // Enough successes: close the circuit
                    self.state
                        .store(CircuitState::Closed.as_u8(), Ordering::SeqCst);
                    self.consecutive_failures.store(0, Ordering::SeqCst);
                    self.consecutive_successes.store(0, Ordering::SeqCst);
                    // Clear the opened_at timestamp
                    *self.opened_at.lock() = None;
                }
            }

            CircuitState::Open => {
                // No action needed while circuit is open
            }
        }
    }

    /// Records a failed request.
    ///
    /// Updates internal counters and may trigger state transitions:
    ///
    /// - **Closed**: Increments failure counter. If threshold reached,
    ///   opens the circuit (records `Instant::now()` as opening time).
    ///
    /// - **HalfOpen**: Any failure reopens the circuit immediately.
    ///
    /// - **Open**: No additional effect (already tracking the failure).
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxi_ai::circuit_breaker::{CircuitBreakerConfig, ProviderCircuitBreaker};
    ///
    /// let breaker = ProviderCircuitBreaker::new(
    ///     "openai".to_string(),
    ///     CircuitBreakerConfig::default(),
    /// );
    ///
    /// // Simulate a failed request
    /// breaker.record_failure();
    /// ```
    pub fn record_failure(&self) {
        let state = self.load_state();

        match state {
            CircuitState::Closed => {
                // Increment failure counter
                let prev = self.consecutive_failures.fetch_add(1, Ordering::SeqCst);
                let new_count = prev + 1;

                if new_count >= self.config.failure_threshold as u64 {
                    // Threshold reached: open the circuit
                    self.state
                        .store(CircuitState::Open.as_u8(), Ordering::SeqCst);
                    *self.opened_at.lock() = Some(Instant::now());
                }
            }

            CircuitState::HalfOpen => {
                // Any failure in half-open reopens the circuit
                self.state
                    .store(CircuitState::Open.as_u8(), Ordering::SeqCst);
                *self.opened_at.lock() = Some(Instant::now());
            }

            CircuitState::Open => {
                // Already open; no additional action needed
            }
        }
    }

    /// Manually resets the circuit breaker to the closed state.
    ///
    /// This is useful for:
    /// - Administrative intervention after fixing provider issues
    /// - Testing and development
    /// - Implementing custom reset logic
    ///
    /// After reset:
    /// - State becomes Closed
    /// - Consecutive failures reset to 0
    /// - Consecutive successes reset to 0
    /// - Opening timestamp is cleared
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxi_ai::circuit_breaker::{CircuitBreakerConfig, ProviderCircuitBreaker};
    ///
    /// let breaker = ProviderCircuitBreaker::new(
    ///     "openai".to_string(),
    ///     CircuitBreakerConfig::default(),
    /// );
    ///
    /// // Manually reset the circuit
    /// breaker.reset();
    /// ```
    pub fn reset(&self) {
        self.state
            .store(CircuitState::Closed.as_u8(), Ordering::SeqCst);
        self.consecutive_failures.store(0, Ordering::SeqCst);
        self.consecutive_successes.store(0, Ordering::SeqCst);
        *self.opened_at.lock() = None;
    }

    /// Returns the current circuit state.
    ///
    /// This is a snapshot and may change immediately after being read.
    /// For decision-making, prefer `allow_request()` which handles state
    /// transitions atomically.
    #[inline]
    pub fn state(&self) -> CircuitState {
        self.load_state()
    }

    /// Returns the provider name this circuit breaker protects.
    #[inline]
    pub fn provider_name(&self) -> &str {
        &self.provider_name
    }

    /// Returns a reference to the configuration.
    #[inline]
    pub fn config(&self) -> &CircuitBreakerConfig {
        &self.config
    }

    /// Returns the number of consecutive failures.
    ///
    /// This is useful for monitoring and debugging.
    #[inline]
    pub fn consecutive_failures(&self) -> u64 {
        self.consecutive_failures.load(Ordering::SeqCst)
    }

    /// Returns the number of consecutive successes (in half-open state).
    ///
    /// This is useful for monitoring and debugging.
    #[inline]
    pub fn consecutive_successes(&self) -> u64 {
        self.consecutive_successes.load(Ordering::SeqCst)
    }

    /// Returns the time remaining before the circuit transitions to half-open.
    ///
    /// Returns `None` if the circuit is not in the open state.
    #[inline]
    pub fn remaining_open_time(&self) -> Option<Duration> {
        if self.load_state() == CircuitState::Open {
            let opened_at = self.opened_at.lock();
            opened_at.map(|t| {
                let elapsed = t.elapsed();
                self.config.open_duration.saturating_sub(elapsed)
            })
        } else {
            None
        }
    }

    /// Loads the current state from the atomic value.
    #[inline]
    fn load_state(&self) -> CircuitState {
        CircuitState::from_u8(self.state.load(Ordering::SeqCst))
    }
}

// ============================================================================
// Diagnostic Info
// ============================================================================

/// Provides diagnostic information about a circuit breaker's current state.
///
/// This struct is useful for monitoring dashboards, logging, and debugging.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CircuitBreakerDiagnostics {
    /// The provider this breaker protects.
    pub provider: String,
    /// Current state.
    pub state: CircuitState,
    /// Number of consecutive failures.
    pub consecutive_failures: u64,
    /// Number of consecutive successes (in half-open).
    pub consecutive_successes: u64,
    /// Whether the circuit is currently open.
    pub is_open: bool,
    /// Time remaining in open state, if applicable.
    pub remaining_open_time: Option<Duration>,
}

impl ProviderCircuitBreaker {
    /// Returns diagnostic information about this circuit breaker.
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxi_ai::circuit_breaker::{CircuitBreakerConfig, ProviderCircuitBreaker};
    ///
    /// let breaker = ProviderCircuitBreaker::new(
    ///     "openai".to_string(),
    ///     CircuitBreakerConfig::default(),
    /// );
    ///
    /// let diagnostics = breaker.diagnostics();
    /// println!("Provider: {}", diagnostics.provider);
    /// ```
    pub fn diagnostics(&self) -> CircuitBreakerDiagnostics {
        let state = self.load_state();
        CircuitBreakerDiagnostics {
            provider: self.provider_name.clone(),
            state,
            consecutive_failures: self.consecutive_failures(),
            consecutive_successes: self.consecutive_successes(),
            is_open: state == CircuitState::Open,
            remaining_open_time: self.remaining_open_time(),
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    // ========================================================================
    // CircuitState Tests
    // ========================================================================

    #[test]
    fn circuit_state_from_u8() {
        assert_eq!(CircuitState::from_u8(0), CircuitState::Closed);
        assert_eq!(CircuitState::from_u8(1), CircuitState::Open);
        assert_eq!(CircuitState::from_u8(2), CircuitState::HalfOpen);
        assert_eq!(CircuitState::from_u8(255), CircuitState::HalfOpen); // Unknown values map to HalfOpen
    }

    #[test]
    fn circuit_state_as_u8() {
        assert_eq!(CircuitState::Closed.as_u8(), 0);
        assert_eq!(CircuitState::Open.as_u8(), 1);
        assert_eq!(CircuitState::HalfOpen.as_u8(), 2);
    }

    // ========================================================================
    // CircuitBreakerConfig Tests
    // ========================================================================

    #[test]
    fn config_default() {
        let config = CircuitBreakerConfig::default();
        assert_eq!(config.failure_threshold, 5);
        assert_eq!(config.open_duration, Duration::from_secs(30));
        assert_eq!(config.half_open_successes, 1);
    }

    #[test]
    fn config_new_valid() {
        let config = CircuitBreakerConfig::new(3, Duration::from_secs(10), 2);
        assert_eq!(config.failure_threshold, 3);
        assert_eq!(config.open_duration, Duration::from_secs(10));
        assert_eq!(config.half_open_successes, 2);
    }

    #[test]
    #[should_panic(expected = "failure_threshold cannot be zero")]
    fn config_new_zero_failure_threshold() {
        CircuitBreakerConfig::new(0, Duration::from_secs(10), 1);
    }

    #[test]
    #[should_panic(expected = "half_open_successes cannot be zero")]
    fn config_new_zero_half_open_successes() {
        CircuitBreakerConfig::new(3, Duration::from_secs(10), 0);
    }

    #[test]
    fn config_builder_methods() {
        let config = CircuitBreakerConfig::default()
            .with_failure_threshold(10)
            .with_open_duration(Duration::from_secs(60))
            .with_half_open_successes(2);

        assert_eq!(config.failure_threshold, 10);
        assert_eq!(config.open_duration, Duration::from_secs(60));
        assert_eq!(config.half_open_successes, 2);
    }

    // ========================================================================
    // ProviderCircuitBreaker Tests
    // ========================================================================

    #[test]
    fn breaker_allows_when_closed() {
        let breaker = ProviderCircuitBreaker::with_defaults("test".to_string());
        assert!(breaker.allow_request().is_ok());
        assert_eq!(breaker.state(), CircuitState::Closed);
    }

    #[test]
    fn breaker_success_in_closed_state() {
        let breaker = ProviderCircuitBreaker::with_defaults("test".to_string());
        breaker.record_success();
        assert_eq!(breaker.consecutive_failures(), 0);
    }

    #[test]
    fn breaker_opens_after_threshold() {
        let config = CircuitBreakerConfig::new(3, Duration::from_secs(30), 1);
        let breaker = ProviderCircuitBreaker::new("test".to_string(), config);

        // Record failures up to threshold
        breaker.record_failure();
        assert_eq!(breaker.state(), CircuitState::Closed);
        breaker.record_failure();
        assert_eq!(breaker.state(), CircuitState::Closed);
        breaker.record_failure();
        assert_eq!(breaker.state(), CircuitState::Open);

        // Should be blocked now
        assert!(breaker.allow_request().is_err());
    }

    #[test]
    fn breaker_success_resets_failure_count() {
        let config = CircuitBreakerConfig::new(3, Duration::from_secs(30), 1);
        let breaker = ProviderCircuitBreaker::new("test".to_string(), config);

        breaker.record_failure();
        breaker.record_failure();
        assert_eq!(breaker.consecutive_failures(), 2);

        breaker.record_success();
        assert_eq!(breaker.consecutive_failures(), 0);
    }

    #[test]
    fn breaker_reset() {
        let config = CircuitBreakerConfig::new(1, Duration::from_secs(30), 1);
        let breaker = ProviderCircuitBreaker::new("test".to_string(), config);

        // Open the circuit
        breaker.record_failure();
        assert_eq!(breaker.state(), CircuitState::Open);

        // Reset
        breaker.reset();
        assert_eq!(breaker.state(), CircuitState::Closed);
        assert!(breaker.allow_request().is_ok());
    }

    #[test]
    fn breaker_half_open_on_duration_elapsed() {
        let config = CircuitBreakerConfig::new(1, Duration::from_millis(50), 1);
        let breaker = ProviderCircuitBreaker::new("test".to_string(), config);

        // Open the circuit
        breaker.record_failure();
        assert_eq!(breaker.state(), CircuitState::Open);

        // Wait for duration to elapse
        std::thread::sleep(Duration::from_millis(60));

        // Should transition to half-open on allow_request
        assert!(breaker.allow_request().is_ok());
        assert_eq!(breaker.state(), CircuitState::HalfOpen);
    }

    #[test]
    fn breaker_half_open_success_closes_circuit() {
        let config = CircuitBreakerConfig::new(1, Duration::from_secs(30), 1);
        let breaker = ProviderCircuitBreaker::new("test".to_string(), config);

        // Force to half-open
        breaker.reset();
        breaker
            .state
            .store(CircuitState::HalfOpen.as_u8(), Ordering::SeqCst);

        // Record success
        breaker.record_success();
        assert_eq!(breaker.state(), CircuitState::Closed);
    }

    #[test]
    fn breaker_half_open_failure_reopens() {
        let config = CircuitBreakerConfig::new(1, Duration::from_secs(30), 1);
        let breaker = ProviderCircuitBreaker::new("test".to_string(), config);

        // Force to half-open
        breaker.reset();
        breaker
            .state
            .store(CircuitState::HalfOpen.as_u8(), Ordering::SeqCst);

        // Record failure
        breaker.record_failure();
        assert_eq!(breaker.state(), CircuitState::Open);
    }

    #[test]
    fn breaker_multiple_half_open_successes() {
        let config = CircuitBreakerConfig::new(1, Duration::from_secs(30), 3);
        let breaker = ProviderCircuitBreaker::new("test".to_string(), config);

        // Force to half-open
        breaker.reset();
        breaker
            .state
            .store(CircuitState::HalfOpen.as_u8(), Ordering::SeqCst);

        // Partial successes should not close
        breaker.record_success();
        assert_eq!(breaker.state(), CircuitState::HalfOpen);
        breaker.record_success();
        assert_eq!(breaker.state(), CircuitState::HalfOpen);

        // Third success closes
        breaker.record_success();
        assert_eq!(breaker.state(), CircuitState::Closed);
    }

    #[test]
    fn breaker_diagnostics() {
        let config = CircuitBreakerConfig::new(2, Duration::from_secs(30), 1);
        let breaker = ProviderCircuitBreaker::new("openai".to_string(), config);

        breaker.record_failure();
        let diag = breaker.diagnostics();

        assert_eq!(diag.provider, "openai");
        assert_eq!(diag.state, CircuitState::Closed);
        assert_eq!(diag.consecutive_failures, 1);
        assert!(!diag.is_open);
    }

    #[test]
    fn breaker_diagnostics_when_open() {
        let config = CircuitBreakerConfig::new(1, Duration::from_secs(30), 1);
        let breaker = ProviderCircuitBreaker::new("anthropic".to_string(), config);

        breaker.record_failure();
        let diag = breaker.diagnostics();

        assert!(diag.is_open);
        assert!(diag.remaining_open_time.is_some());
    }

    // ========================================================================
    // CircuitOpenError Tests
    // ========================================================================

    #[test]
    fn circuit_open_error_display() {
        let error = CircuitOpenError::new("openai", Duration::from_secs(10));
        let msg = error.to_string();
        assert!(msg.contains("openai"));
        assert!(msg.contains("10"));
    }

    #[test]
    fn circuit_open_error_clone() {
        let error = CircuitOpenError::new("test", Duration::from_secs(5));
        let cloned = error.clone();
        assert_eq!(error, cloned);
    }
}