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
//! Circuit Breaker — per-provider failure protection for LLM API calls.
//!
//! State machine with three states:
//! - **Closed**: Normal operation. Failures increment a counter.
//! After `failure_threshold` consecutive failures → transitions to Open.
//! - **Open**: All calls are immediately rejected (fail fast).
//! After `cooldown` duration → transitions to HalfOpen.
//! - **HalfOpen**: Allows a limited number of probe calls.
//! If `success_threshold` successes → transitions to Closed.
//! Any failure → transitions back to Open.
//!
//! Each LLM provider gets its own `CircuitBreaker` instance.
use std::time::{Duration, Instant};
/// Circuit breaker state.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CircuitState {
/// Normal operation — calls pass through.
Closed,
/// Calls are rejected — too many recent failures.
Open,
/// Probing — allowing limited calls to test recovery.
HalfOpen,
}
impl std::fmt::Display for CircuitState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CircuitState::Closed => write!(f, "closed"),
CircuitState::Open => write!(f, "open"),
CircuitState::HalfOpen => write!(f, "half_open"),
}
}
}
/// Per-provider circuit breaker.
#[derive(Debug)]
pub struct CircuitBreaker {
state: CircuitState,
/// Consecutive failure count.
failure_count: u32,
/// Consecutive success count in half-open state.
success_count: u32,
/// Number of failures to trigger open state.
failure_threshold: u32,
/// Number of successes in half-open to close the circuit.
success_threshold: u32,
/// How long to wait in open state before probing.
cooldown: Duration,
/// When the circuit was last opened.
last_opened_at: Option<Instant>,
/// Provider name for logging.
provider: String,
/// Total number of times the circuit has opened.
total_opens: u64,
}
impl CircuitBreaker {
/// Create a new circuit breaker with the given thresholds.
pub fn new(provider: &str, failure_threshold: u32, success_threshold: u32, cooldown: Duration) -> Self {
CircuitBreaker {
state: CircuitState::Closed,
failure_count: 0,
success_count: 0,
failure_threshold,
success_threshold,
cooldown,
last_opened_at: None,
provider: provider.to_string(),
total_opens: 0,
}
}
/// Create a circuit breaker with sensible defaults.
pub fn with_defaults(provider: &str) -> Self {
Self::new(provider, 5, 2, Duration::from_secs(30))
}
/// Check if a call is allowed. Transitions Open→HalfOpen if cooldown elapsed.
pub fn can_execute(&mut self) -> bool {
match self.state {
CircuitState::Closed => true,
CircuitState::HalfOpen => true,
CircuitState::Open => {
// Check if cooldown has elapsed
if let Some(opened_at) = self.last_opened_at {
if opened_at.elapsed() >= self.cooldown {
self.state = CircuitState::HalfOpen;
self.success_count = 0;
tracing::info!(
provider = %self.provider,
state = "half_open",
"circuit_breaker_transition"
);
true
} else {
false
}
} else {
false
}
}
}
}
/// Record a successful call.
pub fn record_success(&mut self) {
match self.state {
CircuitState::Closed => {
// Reset failure count on success
self.failure_count = 0;
}
CircuitState::HalfOpen => {
self.success_count += 1;
if self.success_count >= self.success_threshold {
self.state = CircuitState::Closed;
self.failure_count = 0;
self.success_count = 0;
tracing::info!(
provider = %self.provider,
state = "closed",
"circuit_breaker_transition"
);
}
}
CircuitState::Open => {
// Should not happen — calls are rejected when open
}
}
}
/// Record a failed call.
pub fn record_failure(&mut self) {
match self.state {
CircuitState::Closed => {
self.failure_count += 1;
if self.failure_count >= self.failure_threshold {
self.state = CircuitState::Open;
self.last_opened_at = Some(Instant::now());
self.total_opens += 1;
tracing::warn!(
provider = %self.provider,
state = "open",
failure_count = self.failure_count,
total_opens = self.total_opens,
"circuit_breaker_transition"
);
}
}
CircuitState::HalfOpen => {
// Any failure in half-open → back to open
self.state = CircuitState::Open;
self.last_opened_at = Some(Instant::now());
self.success_count = 0;
self.total_opens += 1;
tracing::warn!(
provider = %self.provider,
state = "open",
reason = "half_open_failure",
total_opens = self.total_opens,
"circuit_breaker_transition"
);
}
CircuitState::Open => {
// Already open — no-op
}
}
}
/// Current state.
pub fn state(&self) -> CircuitState {
self.state
}
/// Provider name.
pub fn provider(&self) -> &str {
&self.provider
}
/// Manually reset the circuit to closed state.
pub fn reset(&mut self) {
self.state = CircuitState::Closed;
self.failure_count = 0;
self.success_count = 0;
self.last_opened_at = None;
}
/// Total number of times this circuit has opened.
pub fn total_opens(&self) -> u64 {
self.total_opens
}
}
// ── Tests ──────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_initial_state_is_closed() {
let cb = CircuitBreaker::with_defaults("test");
assert_eq!(cb.state(), CircuitState::Closed);
assert_eq!(cb.total_opens(), 0);
}
#[test]
fn test_success_resets_failure_count() {
let mut cb = CircuitBreaker::with_defaults("test");
cb.record_failure();
cb.record_failure();
cb.record_success();
// After success, failure count resets — 5 more failures needed
for _ in 0..4 {
cb.record_failure();
}
assert_eq!(cb.state(), CircuitState::Closed);
}
#[test]
fn test_opens_after_threshold() {
let mut cb = CircuitBreaker::new("test", 3, 2, Duration::from_secs(30));
assert!(cb.can_execute());
cb.record_failure();
cb.record_failure();
assert_eq!(cb.state(), CircuitState::Closed);
cb.record_failure();
assert_eq!(cb.state(), CircuitState::Open);
assert_eq!(cb.total_opens(), 1);
}
#[test]
fn test_open_rejects_calls() {
let mut cb = CircuitBreaker::new("test", 2, 1, Duration::from_secs(60));
cb.record_failure();
cb.record_failure();
assert_eq!(cb.state(), CircuitState::Open);
assert!(!cb.can_execute());
}
#[test]
fn test_half_open_after_cooldown() {
let mut cb = CircuitBreaker::new("test", 2, 1, Duration::from_millis(10));
cb.record_failure();
cb.record_failure();
assert_eq!(cb.state(), CircuitState::Open);
// Wait for cooldown
std::thread::sleep(Duration::from_millis(15));
assert!(cb.can_execute());
assert_eq!(cb.state(), CircuitState::HalfOpen);
}
#[test]
fn test_half_open_to_closed_on_success() {
let mut cb = CircuitBreaker::new("test", 2, 2, Duration::from_millis(10));
cb.record_failure();
cb.record_failure();
std::thread::sleep(Duration::from_millis(15));
cb.can_execute(); // Transition to HalfOpen
cb.record_success();
assert_eq!(cb.state(), CircuitState::HalfOpen);
cb.record_success();
assert_eq!(cb.state(), CircuitState::Closed);
}
#[test]
fn test_half_open_to_open_on_failure() {
let mut cb = CircuitBreaker::new("test", 2, 2, Duration::from_millis(10));
cb.record_failure();
cb.record_failure();
std::thread::sleep(Duration::from_millis(15));
cb.can_execute(); // Transition to HalfOpen
cb.record_failure();
assert_eq!(cb.state(), CircuitState::Open);
assert_eq!(cb.total_opens(), 2);
}
#[test]
fn test_reset() {
let mut cb = CircuitBreaker::new("test", 2, 1, Duration::from_secs(60));
cb.record_failure();
cb.record_failure();
assert_eq!(cb.state(), CircuitState::Open);
cb.reset();
assert_eq!(cb.state(), CircuitState::Closed);
assert!(cb.can_execute());
}
#[test]
fn test_can_execute_closed() {
let mut cb = CircuitBreaker::with_defaults("test");
assert!(cb.can_execute());
}
#[test]
fn test_display_state() {
assert_eq!(format!("{}", CircuitState::Closed), "closed");
assert_eq!(format!("{}", CircuitState::Open), "open");
assert_eq!(format!("{}", CircuitState::HalfOpen), "half_open");
}
}