zeptoclaw 0.8.2

Ultra-lightweight personal AI assistant
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
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
//! Fallback LLM provider for ZeptoClaw
//!
//! This module provides a [`FallbackProvider`] that chains two LLM providers:
//! if the primary provider fails, the request is automatically retried against
//! a secondary (fallback) provider. This is useful for high-availability
//! configurations where one provider may experience intermittent outages.
//!
//! # Example
//!
//! ```rust,ignore
//! use zeptoclaw::providers::fallback::FallbackProvider;
//! use zeptoclaw::providers::claude::ClaudeProvider;
//! use zeptoclaw::providers::openai::OpenAIProvider;
//!
//! let primary = Box::new(ClaudeProvider::new("claude-key"));
//! let fallback = Box::new(OpenAIProvider::new("openai-key"));
//! let provider = FallbackProvider::new(primary, fallback);
//! // If Claude fails, the request is automatically retried against OpenAI.
//! ```

use std::fmt;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use async_trait::async_trait;
use tracing::{info, warn};

use crate::error::Result;
use crate::session::Message;

use super::cooldown::{CooldownTracker, FailoverReason};
use super::{ChatOptions, LLMProvider, LLMResponse, StreamEvent, ToolDefinition};

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

/// Circuit breaker states for the primary provider.
#[derive(Debug, Clone, Copy, PartialEq)]
enum CircuitState {
    /// Normal operation -- primary provider is tried first.
    Closed,
    /// Primary provider is unhealthy -- skip directly to fallback.
    Open,
    /// Probing -- allow one request to primary to test recovery.
    HalfOpen,
}

/// Lock-free circuit breaker for tracking primary provider health.
///
/// Uses atomic counters to avoid mutex overhead. The circuit transitions
/// through three states:
///
/// - **Closed**: Normal operation, primary is tried first.
/// - **Open**: Primary is unhealthy after `failure_threshold` consecutive
///   failures. Requests go directly to the fallback provider.
/// - **HalfOpen**: After `cooldown_secs` have elapsed since the last failure,
///   one probe request is sent to the primary. On success the circuit closes;
///   on failure it reopens.
struct CircuitBreaker {
    /// Consecutive failure count.
    failure_count: AtomicU32,
    /// Timestamp (epoch secs) of last failure.
    last_failure_epoch: AtomicU64,
    /// Number of consecutive failures before opening the circuit.
    failure_threshold: u32,
    /// Seconds to wait before transitioning from Open to HalfOpen.
    cooldown_secs: u64,
}

impl CircuitBreaker {
    /// Create a new circuit breaker.
    ///
    /// # Arguments
    /// * `failure_threshold` - Number of consecutive failures before opening
    /// * `cooldown_secs` - Seconds to wait in Open state before probing
    fn new(failure_threshold: u32, cooldown_secs: u64) -> Self {
        Self {
            failure_count: AtomicU32::new(0),
            last_failure_epoch: AtomicU64::new(0),
            failure_threshold,
            cooldown_secs,
        }
    }

    /// Compute the current circuit state from atomic counters.
    fn state(&self) -> CircuitState {
        let failures = self.failure_count.load(Ordering::Relaxed);
        if failures < self.failure_threshold {
            return CircuitState::Closed;
        }

        // Circuit has tripped -- check if cooldown has elapsed.
        let last_failure = self.last_failure_epoch.load(Ordering::Relaxed);
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        if now.saturating_sub(last_failure) >= self.cooldown_secs {
            CircuitState::HalfOpen
        } else {
            CircuitState::Open
        }
    }

    /// Record a successful request -- resets the failure counter.
    fn record_success(&self) {
        let prev = self.failure_count.swap(0, Ordering::Relaxed);
        if prev >= self.failure_threshold {
            info!(
                previous_failures = prev,
                "Circuit breaker closed: primary provider recovered"
            );
        }
    }

    /// Record a failed request -- increments the failure counter and updates
    /// the last-failure timestamp.
    fn record_failure(&self) {
        let prev = self.failure_count.fetch_add(1, Ordering::Relaxed);
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        self.last_failure_epoch.store(now, Ordering::Relaxed);

        // Log the transition to Open when we cross the threshold.
        if prev + 1 == self.failure_threshold {
            info!(
                threshold = self.failure_threshold,
                "Circuit breaker opened: primary provider marked unhealthy"
            );
        }
    }
}

impl fmt::Debug for CircuitBreaker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CircuitBreaker")
            .field("state", &self.state())
            .field("failure_count", &self.failure_count.load(Ordering::Relaxed))
            .field("failure_threshold", &self.failure_threshold)
            .field("cooldown_secs", &self.cooldown_secs)
            .finish()
    }
}

/// A provider that chains a primary and a fallback LLM provider.
///
/// When a request to the primary provider fails, the error is logged and the
/// same request is forwarded to the fallback provider. If both providers fail,
/// the fallback provider's error is returned (as the more recent failure).
pub struct FallbackProvider {
    primary: Box<dyn LLMProvider>,
    fallback: Box<dyn LLMProvider>,
    /// Pre-computed composite name in the form `"primary -> fallback"`.
    composite_name: String,
    /// Circuit breaker tracking primary provider health.
    circuit_breaker: CircuitBreaker,
    /// Per-reason cooldown tracker for smarter provider skipping.
    cooldown: CooldownTracker,
    /// Optional model override for the fallback provider.
    /// When set, the fallback provider uses this model instead of the
    /// original request model. Enables cross-provider model mapping
    /// (e.g., primary uses "claude-sonnet-4-5-20250929", fallback uses "gpt-5.1").
    fallback_model: Option<String>,
}

impl fmt::Debug for FallbackProvider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FallbackProvider")
            .field("primary", &self.primary.name())
            .field("fallback", &self.fallback.name())
            .field("circuit_breaker", &self.circuit_breaker)
            .field("cooldown", &"CooldownTracker")
            .finish()
    }
}

impl FallbackProvider {
    /// Create a new fallback provider.
    ///
    /// # Arguments
    /// * `primary` - The preferred provider, tried first for every request.
    /// * `fallback` - The backup provider, used only when the primary fails.
    pub fn new(primary: Box<dyn LLMProvider>, fallback: Box<dyn LLMProvider>) -> Self {
        let composite_name = format!("{} -> {}", primary.name(), fallback.name());
        Self {
            primary,
            fallback,
            composite_name,
            circuit_breaker: CircuitBreaker::new(3, 30),
            cooldown: CooldownTracker::new(),
            fallback_model: None,
        }
    }

    /// Set an optional model override for the fallback provider.
    ///
    /// When set, the fallback provider will use this model instead of the
    /// original request model. This enables cross-provider model mapping
    /// (e.g., primary uses Claude, fallback uses OpenAI with a different model).
    pub fn with_fallback_model(mut self, model: Option<String>) -> Self {
        self.fallback_model = model;
        self
    }
}

#[async_trait]
impl LLMProvider for FallbackProvider {
    fn name(&self) -> &str {
        &self.composite_name
    }

    fn default_model(&self) -> &str {
        self.primary.default_model()
    }

    async fn chat(
        &self,
        messages: Vec<Message>,
        tools: Vec<ToolDefinition>,
        model: Option<&str>,
        options: ChatOptions,
    ) -> Result<LLMResponse> {
        let circuit_state = self.circuit_breaker.state();

        // When the circuit is Open or per-reason cooldown is active, skip the primary entirely.
        if circuit_state == CircuitState::Open || self.cooldown.is_in_cooldown(self.primary.name())
        {
            info!(
                primary = self.primary.name(),
                fallback = self.fallback.name(),
                "Circuit open or cooldown active: skipping primary, using fallback directly"
            );
            let effective_model = self.fallback_model.as_deref().or(model);
            return self
                .fallback
                .chat(messages, tools, effective_model, options)
                .await;
        }

        // Closed or HalfOpen -- try the primary provider.
        match self
            .primary
            .chat(messages.clone(), tools.clone(), model, options.clone())
            .await
        {
            Ok(response) => {
                self.circuit_breaker.record_success();
                self.cooldown.mark_success(self.primary.name());
                Ok(response)
            }
            Err(primary_err) => {
                // Don't fallback for auth/billing/invalid request errors
                let should_fallback = match &primary_err {
                    crate::error::ZeptoError::ProviderTyped(pe) => pe.should_fallback(),
                    crate::error::ZeptoError::QuotaRejected(_) => false,
                    _ => true, // Legacy errors always fallback
                };

                if should_fallback {
                    self.circuit_breaker.record_failure();
                    // Classify the error and apply per-reason cooldown.
                    let reason = match &primary_err {
                        crate::error::ZeptoError::ProviderTyped(pe) => {
                            FailoverReason::from_provider_error(pe)
                        }
                        _ => FailoverReason::Unknown,
                    };
                    self.cooldown.mark_failure(self.primary.name(), reason);
                    warn!(
                        primary = self.primary.name(),
                        fallback = self.fallback.name(),
                        error = %primary_err,
                        circuit_state = ?self.circuit_breaker.state(),
                        ?reason,
                        "Primary provider failed, falling back"
                    );
                    let effective_model = self.fallback_model.as_deref().or(model);
                    self.fallback
                        .chat(messages, tools, effective_model, options)
                        .await
                } else {
                    warn!(
                        primary = self.primary.name(),
                        error = %primary_err,
                        "Primary provider error is non-recoverable, skipping fallback"
                    );
                    Err(primary_err)
                }
            }
        }
    }

    async fn chat_stream(
        &self,
        messages: Vec<Message>,
        tools: Vec<ToolDefinition>,
        model: Option<&str>,
        options: ChatOptions,
    ) -> Result<tokio::sync::mpsc::Receiver<StreamEvent>> {
        let circuit_state = self.circuit_breaker.state();

        // When the circuit is Open or per-reason cooldown is active, skip the primary entirely.
        if circuit_state == CircuitState::Open || self.cooldown.is_in_cooldown(self.primary.name())
        {
            info!(
                primary = self.primary.name(),
                fallback = self.fallback.name(),
                "Circuit open or cooldown active: skipping primary streaming, using fallback directly"
            );
            let effective_model = self.fallback_model.as_deref().or(model);
            return self
                .fallback
                .chat_stream(messages, tools, effective_model, options)
                .await;
        }

        // Closed or HalfOpen -- try the primary provider.
        match self
            .primary
            .chat_stream(messages.clone(), tools.clone(), model, options.clone())
            .await
        {
            Ok(receiver) => {
                self.circuit_breaker.record_success();
                self.cooldown.mark_success(self.primary.name());
                Ok(receiver)
            }
            Err(primary_err) => {
                // Don't fallback for auth/billing/invalid request errors
                let should_fallback = match &primary_err {
                    crate::error::ZeptoError::ProviderTyped(pe) => pe.should_fallback(),
                    crate::error::ZeptoError::QuotaRejected(_) => false,
                    _ => true, // Legacy errors always fallback
                };

                if should_fallback {
                    self.circuit_breaker.record_failure();
                    // Classify the error and apply per-reason cooldown.
                    let reason = match &primary_err {
                        crate::error::ZeptoError::ProviderTyped(pe) => {
                            FailoverReason::from_provider_error(pe)
                        }
                        _ => FailoverReason::Unknown,
                    };
                    self.cooldown.mark_failure(self.primary.name(), reason);
                    warn!(
                        primary = self.primary.name(),
                        fallback = self.fallback.name(),
                        error = %primary_err,
                        circuit_state = ?self.circuit_breaker.state(),
                        ?reason,
                        "Primary provider streaming failed, falling back"
                    );
                    let effective_model = self.fallback_model.as_deref().or(model);
                    self.fallback
                        .chat_stream(messages, tools, effective_model, options)
                        .await
                } else {
                    warn!(
                        primary = self.primary.name(),
                        error = %primary_err,
                        "Primary provider streaming error is non-recoverable, skipping fallback"
                    );
                    Err(primary_err)
                }
            }
        }
    }

    /// Delegate embed() to the primary provider.
    ///
    /// Embeddings are not subject to fallback logic — the primary provider is
    /// the authoritative embedding source (its model is the one configured).
    async fn embed(&self, texts: &[String]) -> crate::error::Result<Vec<Vec<f32>>> {
        self.primary.embed(texts).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ZeptoError;
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::sync::Arc;

    // ---------------------------------------------------------------
    // Test helpers
    // ---------------------------------------------------------------

    /// A provider that always returns a successful response.
    struct SuccessProvider {
        name: &'static str,
    }

    impl fmt::Debug for SuccessProvider {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("SuccessProvider")
                .field("name", &self.name)
                .finish()
        }
    }

    #[async_trait]
    impl LLMProvider for SuccessProvider {
        fn name(&self) -> &str {
            self.name
        }

        fn default_model(&self) -> &str {
            "success-model-v1"
        }

        async fn chat(
            &self,
            _messages: Vec<Message>,
            _tools: Vec<ToolDefinition>,
            _model: Option<&str>,
            _options: ChatOptions,
        ) -> Result<LLMResponse> {
            Ok(LLMResponse::text(&format!("success from {}", self.name)))
        }
    }

    /// A provider that always returns an error.
    struct FailProvider {
        name: &'static str,
    }

    impl fmt::Debug for FailProvider {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("FailProvider")
                .field("name", &self.name)
                .finish()
        }
    }

    #[async_trait]
    impl LLMProvider for FailProvider {
        fn name(&self) -> &str {
            self.name
        }

        fn default_model(&self) -> &str {
            "fail-model-v1"
        }

        async fn chat(
            &self,
            _messages: Vec<Message>,
            _tools: Vec<ToolDefinition>,
            _model: Option<&str>,
            _options: ChatOptions,
        ) -> Result<LLMResponse> {
            Err(ZeptoError::Provider("provider failed".into()))
        }
    }

    /// A provider that counts how many times `chat()` is called and returns success.
    struct CountingProvider {
        name: &'static str,
        call_count: Arc<AtomicU32>,
    }

    impl fmt::Debug for CountingProvider {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("CountingProvider")
                .field("name", &self.name)
                .field("call_count", &self.call_count.load(Ordering::SeqCst))
                .finish()
        }
    }

    #[async_trait]
    impl LLMProvider for CountingProvider {
        fn name(&self) -> &str {
            self.name
        }

        fn default_model(&self) -> &str {
            "counting-model-v1"
        }

        async fn chat(
            &self,
            _messages: Vec<Message>,
            _tools: Vec<ToolDefinition>,
            _model: Option<&str>,
            _options: ChatOptions,
        ) -> Result<LLMResponse> {
            self.call_count.fetch_add(1, Ordering::SeqCst);
            Ok(LLMResponse::text(&format!("success from {}", self.name)))
        }
    }

    // ---------------------------------------------------------------
    // Tests
    // ---------------------------------------------------------------

    #[test]
    fn test_fallback_provider_name() {
        let provider = FallbackProvider::new(
            Box::new(SuccessProvider { name: "alpha" }),
            Box::new(SuccessProvider { name: "beta" }),
        );

        assert_eq!(provider.name(), "alpha -> beta");
    }

    #[test]
    fn test_fallback_provider_default_model() {
        let provider = FallbackProvider::new(
            Box::new(SuccessProvider { name: "primary" }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        // Should delegate to primary's default_model.
        assert_eq!(provider.default_model(), "success-model-v1");
    }

    #[tokio::test]
    async fn test_fallback_uses_primary_when_available() {
        let provider = FallbackProvider::new(
            Box::new(SuccessProvider { name: "primary" }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let response = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await
            .expect("primary should succeed");

        assert_eq!(response.content, "success from primary");
    }

    #[tokio::test]
    async fn test_fallback_uses_secondary_on_primary_failure() {
        let provider = FallbackProvider::new(
            Box::new(FailProvider { name: "primary" }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let response = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await
            .expect("fallback should succeed after primary failure");

        assert_eq!(response.content, "success from fallback");
    }

    #[tokio::test]
    async fn test_fallback_returns_error_when_both_fail() {
        let provider = FallbackProvider::new(
            Box::new(FailProvider { name: "primary" }),
            Box::new(FailProvider { name: "fallback" }),
        );

        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, ZeptoError::Provider(_)),
            "expected Provider error, got: {err}"
        );
    }

    #[tokio::test]
    async fn test_fallback_primary_not_called_twice() {
        let call_count = Arc::new(AtomicU32::new(0));

        let provider = FallbackProvider::new(
            Box::new(CountingProvider {
                name: "primary",
                call_count: Arc::clone(&call_count),
            }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let response = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await
            .expect("primary should succeed");

        assert_eq!(response.content, "success from primary");
        assert_eq!(
            call_count.load(Ordering::SeqCst),
            1,
            "primary should be called exactly once"
        );
    }

    // ====================================================================
    // ProviderTyped fallback behavior tests
    // ====================================================================

    /// A provider that fails with a specific ProviderTyped error.
    struct TypedFailProvider {
        name: &'static str,
        error: fn() -> ZeptoError,
    }

    #[async_trait]
    impl LLMProvider for TypedFailProvider {
        fn name(&self) -> &str {
            self.name
        }

        fn default_model(&self) -> &str {
            "typed-fail-model"
        }

        async fn chat(
            &self,
            _messages: Vec<Message>,
            _tools: Vec<ToolDefinition>,
            _model: Option<&str>,
            _options: ChatOptions,
        ) -> Result<LLMResponse> {
            Err((self.error)())
        }
    }

    #[tokio::test]
    async fn test_fallback_auth_error_does_not_trigger_fallback() {
        use crate::error::ProviderError;

        let provider = FallbackProvider::new(
            Box::new(TypedFailProvider {
                name: "primary",
                error: || ZeptoError::ProviderTyped(ProviderError::Auth("invalid key".into())),
            }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        // Auth error should NOT trigger fallback — request should fail
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Authentication error"));
    }

    #[tokio::test]
    async fn test_fallback_billing_error_does_not_trigger_fallback() {
        use crate::error::ProviderError;

        let provider = FallbackProvider::new(
            Box::new(TypedFailProvider {
                name: "primary",
                error: || ZeptoError::ProviderTyped(ProviderError::Billing("no funds".into())),
            }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Billing error"));
    }

    #[tokio::test]
    async fn test_fallback_invalid_request_does_not_trigger_fallback() {
        use crate::error::ProviderError;

        let provider = FallbackProvider::new(
            Box::new(TypedFailProvider {
                name: "primary",
                error: || {
                    ZeptoError::ProviderTyped(ProviderError::InvalidRequest("bad json".into()))
                },
            }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid request"));
    }

    #[tokio::test]
    async fn test_fallback_rate_limit_triggers_fallback() {
        use crate::error::ProviderError;

        let provider = FallbackProvider::new(
            Box::new(TypedFailProvider {
                name: "primary",
                error: || {
                    ZeptoError::ProviderTyped(ProviderError::RateLimit("quota exceeded".into()))
                },
            }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        // Rate limit SHOULD trigger fallback
        assert!(result.is_ok());
        assert_eq!(result.unwrap().content, "success from fallback");
    }

    #[tokio::test]
    async fn test_fallback_server_error_triggers_fallback() {
        use crate::error::ProviderError;

        let provider = FallbackProvider::new(
            Box::new(TypedFailProvider {
                name: "primary",
                error: || {
                    ZeptoError::ProviderTyped(ProviderError::ServerError("internal error".into()))
                },
            }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap().content, "success from fallback");
    }

    #[tokio::test]
    async fn test_fallback_timeout_triggers_fallback() {
        use crate::error::ProviderError;

        let provider = FallbackProvider::new(
            Box::new(TypedFailProvider {
                name: "primary",
                error: || ZeptoError::ProviderTyped(ProviderError::Timeout("timed out".into())),
            }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap().content, "success from fallback");
    }

    #[tokio::test]
    async fn test_fallback_model_not_found_triggers_fallback() {
        use crate::error::ProviderError;

        let provider = FallbackProvider::new(
            Box::new(TypedFailProvider {
                name: "primary",
                error: || ZeptoError::ProviderTyped(ProviderError::ModelNotFound("gpt-99".into())),
            }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        // ModelNotFound should trigger fallback (different provider may have the model)
        assert!(result.is_ok());
        assert_eq!(result.unwrap().content, "success from fallback");
    }

    #[tokio::test]
    async fn test_fallback_legacy_provider_error_triggers_fallback() {
        // Legacy Provider(String) errors should always trigger fallback (backward compat)
        let provider = FallbackProvider::new(
            Box::new(FailProvider { name: "primary" }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap().content, "success from fallback");
    }

    /// Documents that `ZeptoError::QuotaExceeded` is a legacy (non-ProviderTyped) error and
    /// therefore hits the `_ => true` branch in the `should_fallback` match, triggering
    /// automatic failover to the secondary provider.  No production code change is needed —
    /// this test exists solely to pin the behaviour and prevent accidental regression.
    #[tokio::test]
    async fn test_quota_exceeded_triggers_fallback() {
        let provider = FallbackProvider::new(
            Box::new(TypedFailProvider {
                name: "primary",
                error: || ZeptoError::QuotaExceeded("limit reached".into()),
            }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        // QuotaExceeded is not a ProviderTyped error, so the `_ => true` branch fires and
        // the request is transparently retried against the fallback provider.
        assert!(result.is_ok(), "expected fallback success, got: {result:?}");
        assert_eq!(result.unwrap().content, "success from fallback");
    }

    /// Documents that `ZeptoError::QuotaRejected` (action=reject) must NOT trigger
    /// fallback — the user explicitly chose a hard stop, so the error propagates.
    #[tokio::test]
    async fn test_quota_rejected_does_not_trigger_fallback() {
        let provider = FallbackProvider::new(
            Box::new(TypedFailProvider {
                name: "primary",
                error: || ZeptoError::QuotaRejected("hard reject".into()),
            }),
            Box::new(SuccessProvider { name: "fallback" }),
        );

        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        // QuotaRejected must NOT fall through to the fallback provider.
        assert!(result.is_err(), "expected Err, got Ok");
        assert!(
            result.unwrap_err().to_string().contains("Quota rejected"),
            "error should be QuotaRejected"
        );
    }

    // ====================================================================
    // Circuit breaker unit tests
    // ====================================================================

    #[test]
    fn test_circuit_breaker_starts_closed() {
        let cb = CircuitBreaker::new(3, 30);
        assert_eq!(cb.state(), CircuitState::Closed);
        assert_eq!(cb.failure_count.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn test_circuit_breaker_opens_after_threshold() {
        let cb = CircuitBreaker::new(3, 30);

        // Record 3 consecutive failures.
        cb.record_failure();
        assert_eq!(cb.state(), CircuitState::Closed);
        cb.record_failure();
        assert_eq!(cb.state(), CircuitState::Closed);
        cb.record_failure();

        // After 3 failures and with cooldown still active, circuit should be Open.
        // (last_failure_epoch is "now", so cooldown has NOT elapsed.)
        assert_eq!(cb.state(), CircuitState::Open);
    }

    #[test]
    fn test_circuit_breaker_resets_on_success() {
        let cb = CircuitBreaker::new(3, 30);

        // Record 2 failures (below threshold).
        cb.record_failure();
        cb.record_failure();
        assert_eq!(cb.state(), CircuitState::Closed);

        // Success resets counter.
        cb.record_success();
        assert_eq!(cb.failure_count.load(Ordering::Relaxed), 0);
        assert_eq!(cb.state(), CircuitState::Closed);

        // Even after 2 more failures it should still be Closed (need 3 total).
        cb.record_failure();
        cb.record_failure();
        assert_eq!(cb.state(), CircuitState::Closed);
    }

    #[test]
    fn test_circuit_breaker_halfopen_after_cooldown() {
        let cb = CircuitBreaker::new(3, 1); // 1 second cooldown for fast test

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

        // Simulate cooldown elapsed by back-dating the last failure timestamp.
        let past = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 2; // 2 seconds ago
        cb.last_failure_epoch.store(past, Ordering::Relaxed);

        assert_eq!(cb.state(), CircuitState::HalfOpen);
    }

    #[test]
    fn test_circuit_breaker_halfopen_success_closes() {
        let cb = CircuitBreaker::new(3, 1);

        // Trip the circuit and simulate cooldown elapsed.
        cb.record_failure();
        cb.record_failure();
        cb.record_failure();
        let past = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 2;
        cb.last_failure_epoch.store(past, Ordering::Relaxed);
        assert_eq!(cb.state(), CircuitState::HalfOpen);

        // Success in HalfOpen should close the circuit.
        cb.record_success();
        assert_eq!(cb.state(), CircuitState::Closed);
        assert_eq!(cb.failure_count.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn test_circuit_breaker_halfopen_failure_reopens() {
        let cb = CircuitBreaker::new(3, 30);

        // Trip the circuit and simulate cooldown elapsed.
        cb.record_failure();
        cb.record_failure();
        cb.record_failure();
        let past = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 31;
        cb.last_failure_epoch.store(past, Ordering::Relaxed);
        assert_eq!(cb.state(), CircuitState::HalfOpen);

        // Another failure in HalfOpen should reopen the circuit.
        cb.record_failure();
        // failure_count is now 4 (>= threshold) and last_failure_epoch is "now"
        // so cooldown has NOT elapsed → Open.
        assert_eq!(cb.state(), CircuitState::Open);
    }

    // ====================================================================
    // Circuit breaker integration tests (with FallbackProvider)
    // ====================================================================

    /// A provider that counts calls and always fails.
    struct CountingFailProvider {
        name: &'static str,
        call_count: Arc<AtomicU32>,
    }

    impl fmt::Debug for CountingFailProvider {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("CountingFailProvider")
                .field("name", &self.name)
                .field("call_count", &self.call_count.load(Ordering::SeqCst))
                .finish()
        }
    }

    #[async_trait]
    impl LLMProvider for CountingFailProvider {
        fn name(&self) -> &str {
            self.name
        }

        fn default_model(&self) -> &str {
            "counting-fail-model"
        }

        async fn chat(
            &self,
            _messages: Vec<Message>,
            _tools: Vec<ToolDefinition>,
            _model: Option<&str>,
            _options: ChatOptions,
        ) -> Result<LLMResponse> {
            self.call_count.fetch_add(1, Ordering::SeqCst);
            Err(ZeptoError::Provider("provider failed".into()))
        }
    }

    #[tokio::test]
    async fn test_fallback_skips_primary_when_circuit_open() {
        let primary_calls = Arc::new(AtomicU32::new(0));
        let fallback_calls = Arc::new(AtomicU32::new(0));

        let provider = FallbackProvider::new(
            Box::new(CountingFailProvider {
                name: "primary",
                call_count: Arc::clone(&primary_calls),
            }),
            Box::new(CountingProvider {
                name: "fallback",
                call_count: Arc::clone(&fallback_calls),
            }),
        );

        // One failure is enough: after primary fails, CooldownTracker puts it
        // in cooldown immediately, so subsequent calls bypass primary.
        let _ = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        // Primary was called once, fallback was called once.
        assert_eq!(primary_calls.load(Ordering::SeqCst), 1);
        assert_eq!(fallback_calls.load(Ordering::SeqCst), 1);

        // Now cooldown is active. Next call should NOT call primary.
        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap().content, "success from fallback");
        // Primary should NOT have been called again (cooldown active).
        assert_eq!(
            primary_calls.load(Ordering::SeqCst),
            1,
            "primary should be skipped while in cooldown"
        );
        assert_eq!(fallback_calls.load(Ordering::SeqCst), 2);
    }

    // ====================================================================
    // Fallback model override tests
    // ====================================================================

    /// A provider that captures the model parameter passed to `chat()`.
    struct ModelCapturingProvider {
        name: &'static str,
        captured_model: Arc<std::sync::Mutex<Option<String>>>,
    }

    impl fmt::Debug for ModelCapturingProvider {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("ModelCapturingProvider")
                .field("name", &self.name)
                .finish()
        }
    }

    #[async_trait]
    impl LLMProvider for ModelCapturingProvider {
        fn name(&self) -> &str {
            self.name
        }

        fn default_model(&self) -> &str {
            "capturing-model"
        }

        async fn chat(
            &self,
            _messages: Vec<Message>,
            _tools: Vec<ToolDefinition>,
            model: Option<&str>,
            _options: ChatOptions,
        ) -> Result<LLMResponse> {
            *self.captured_model.lock().unwrap() = model.map(String::from);
            Ok(LLMResponse::text(&format!("success from {}", self.name)))
        }
    }

    #[tokio::test]
    async fn test_fallback_uses_fallback_model_when_set() {
        let captured = Arc::new(std::sync::Mutex::new(None));

        let provider = FallbackProvider::new(
            Box::new(FailProvider { name: "primary" }),
            Box::new(ModelCapturingProvider {
                name: "fallback",
                captured_model: Arc::clone(&captured),
            }),
        )
        .with_fallback_model(Some("nvidia/llama-3.3-70b".into()));

        let result = provider
            .chat(
                vec![],
                vec![],
                Some("gemini-2.5-pro"),
                ChatOptions::default(),
            )
            .await;

        assert!(result.is_ok());
        let model = captured.lock().unwrap().clone();
        assert_eq!(
            model,
            Some("nvidia/llama-3.3-70b".to_string()),
            "fallback should receive the fallback_model, not the original model"
        );
    }

    #[tokio::test]
    async fn test_fallback_uses_original_model_when_no_override() {
        let captured = Arc::new(std::sync::Mutex::new(None));

        let provider = FallbackProvider::new(
            Box::new(FailProvider { name: "primary" }),
            Box::new(ModelCapturingProvider {
                name: "fallback",
                captured_model: Arc::clone(&captured),
            }),
        );

        let result = provider
            .chat(
                vec![],
                vec![],
                Some("gemini-2.5-pro"),
                ChatOptions::default(),
            )
            .await;

        assert!(result.is_ok());
        let model = captured.lock().unwrap().clone();
        assert_eq!(
            model,
            Some("gemini-2.5-pro".to_string()),
            "fallback should receive the original model when no fallback_model is set"
        );
    }

    #[tokio::test]
    async fn test_fallback_model_used_on_circuit_open() {
        let primary_calls = Arc::new(AtomicU32::new(0));
        let captured = Arc::new(std::sync::Mutex::new(None));

        let provider = FallbackProvider::new(
            Box::new(CountingFailProvider {
                name: "primary",
                call_count: Arc::clone(&primary_calls),
            }),
            Box::new(ModelCapturingProvider {
                name: "fallback",
                captured_model: Arc::clone(&captured),
            }),
        )
        .with_fallback_model(Some("fallback-model".into()));

        // First call: primary fails, triggers cooldown, falls back
        let _ = provider
            .chat(vec![], vec![], Some("original"), ChatOptions::default())
            .await;

        assert_eq!(primary_calls.load(Ordering::SeqCst), 1);

        // Second call: primary is in cooldown, goes directly to fallback
        let result = provider
            .chat(vec![], vec![], Some("original"), ChatOptions::default())
            .await;

        assert!(result.is_ok());
        // Primary should NOT have been called again (cooldown active)
        assert_eq!(
            primary_calls.load(Ordering::SeqCst),
            1,
            "primary should be skipped while in cooldown"
        );
        let model = captured.lock().unwrap().clone();
        assert_eq!(
            model,
            Some("fallback-model".to_string()),
            "fallback should receive fallback_model on circuit-open path"
        );
    }

    #[tokio::test]
    async fn test_fallback_probes_primary_when_halfopen() {
        let primary_calls = Arc::new(AtomicU32::new(0));
        let fallback_calls = Arc::new(AtomicU32::new(0));

        let provider = FallbackProvider::new(
            Box::new(CountingFailProvider {
                name: "primary",
                call_count: Arc::clone(&primary_calls),
            }),
            Box::new(CountingProvider {
                name: "fallback",
                call_count: Arc::clone(&fallback_calls),
            }),
        );

        // With CooldownTracker, after the first failure primary is in cooldown.
        // To trip the circuit breaker (needs 3 failures), directly manipulate
        // the atomic counter — this simulates 3 consecutive circuit failures.
        provider
            .circuit_breaker
            .failure_count
            .store(3, Ordering::Relaxed);
        let now_epoch = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        provider
            .circuit_breaker
            .last_failure_epoch
            .store(now_epoch, Ordering::Relaxed);

        assert_eq!(provider.circuit_breaker.state(), CircuitState::Open);

        // Also make sure the CooldownTracker is clear (no cooldown active)
        // so that the HalfOpen probe path is exercised, not the cooldown bypass.
        provider.cooldown.mark_success("primary");

        // Simulate circuit cooldown elapsed by back-dating the last failure timestamp.
        let past = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 31; // 31 seconds ago (> default 30s cooldown)
        provider
            .circuit_breaker
            .last_failure_epoch
            .store(past, Ordering::Relaxed);

        assert_eq!(provider.circuit_breaker.state(), CircuitState::HalfOpen);
        assert!(!provider.cooldown.is_in_cooldown("primary"));

        // Next call should probe the primary (HalfOpen allows one request, cooldown is clear).
        let result = provider
            .chat(vec![], vec![], None, ChatOptions::default())
            .await;

        // Primary was called (probe) but failed, so fallback was used.
        assert!(result.is_ok());
        assert_eq!(result.unwrap().content, "success from fallback");
        assert_eq!(
            primary_calls.load(Ordering::SeqCst),
            1,
            "primary should be probed once in HalfOpen state"
        );
    }
}