trueno 0.18.0

High-performance SIMD compute library with GPU support, LLM inference engine, and GGUF model loading
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
//! Circuit Breaker Pattern
//!
//! AWP-02: Protect against cascading failures with three-state circuit breaker.

use std::time::{Duration, Instant};

// ----------------------------------------------------------------------------
// AWP-02: Circuit Breaker
// ----------------------------------------------------------------------------

/// Circuit breaker states.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CircuitState {
    /// Circuit is closed (normal operation)
    Closed,
    /// Circuit is open (failing fast)
    Open,
    /// Circuit is half-open (testing recovery)
    HalfOpen,
}

/// Circuit breaker for protecting against cascading failures.
///
/// # Example
/// ```rust
/// use trueno::brick::CircuitBreaker;
/// use std::time::Duration;
///
/// let mut breaker = CircuitBreaker::new(3, Duration::from_secs(30));
///
/// // Record failures
/// breaker.record_failure();
/// breaker.record_failure();
/// assert!(breaker.allow_request()); // Still closed
///
/// breaker.record_failure();
/// assert!(!breaker.allow_request()); // Now open
/// ```
pub struct CircuitBreaker {
    /// Current state
    state: CircuitState,
    /// Failure count in current window
    failure_count: usize,
    /// Failure threshold to trip the circuit
    failure_threshold: usize,
    /// Time when circuit opened
    opened_at: Option<Instant>,
    /// Duration to stay open before trying half-open
    open_duration: Duration,
    /// Success count in half-open state
    half_open_successes: usize,
    /// Successes needed to close from half-open
    half_open_threshold: usize,
}

impl CircuitBreaker {
    /// Create a new circuit breaker.
    pub fn new(failure_threshold: usize, open_duration: Duration) -> Self {
        Self {
            state: CircuitState::Closed,
            failure_count: 0,
            failure_threshold,
            opened_at: None,
            open_duration,
            half_open_successes: 0,
            half_open_threshold: 1,
        }
    }

    /// Get current state.
    #[must_use]
    pub fn state(&self) -> CircuitState {
        self.state
    }

    /// Check if a request should be allowed.
    #[must_use]
    pub fn allow_request(&mut self) -> bool {
        match self.state {
            CircuitState::Closed => true,
            CircuitState::Open => {
                // Check if we should transition to half-open
                if let Some(opened_at) = self.opened_at {
                    if opened_at.elapsed() >= self.open_duration {
                        self.state = CircuitState::HalfOpen;
                        self.half_open_successes = 0;
                        return true; // Allow one request to test
                    }
                }
                false
            }
            CircuitState::HalfOpen => true, // Allow requests in half-open
        }
    }

    /// Record a successful operation.
    pub fn record_success(&mut self) {
        match self.state {
            CircuitState::Closed => {
                // Reset failure count on success
                self.failure_count = 0;
            }
            CircuitState::HalfOpen => {
                self.half_open_successes += 1;
                if self.half_open_successes >= self.half_open_threshold {
                    // Recovered - close the circuit
                    self.state = CircuitState::Closed;
                    self.failure_count = 0;
                    self.opened_at = None;
                }
            }
            CircuitState::Open => {}
        }
    }

    /// Record a failed operation.
    pub fn record_failure(&mut self) {
        match self.state {
            CircuitState::Closed => {
                self.failure_count += 1;
                if self.failure_count >= self.failure_threshold {
                    // Trip the circuit
                    self.state = CircuitState::Open;
                    self.opened_at = Some(Instant::now());
                }
            }
            CircuitState::HalfOpen => {
                // Failed during recovery - reopen
                self.state = CircuitState::Open;
                self.opened_at = Some(Instant::now());
            }
            CircuitState::Open => {}
        }
    }

    /// Reset the circuit breaker to closed state.
    pub fn reset(&mut self) {
        self.state = CircuitState::Closed;
        self.failure_count = 0;
        self.opened_at = None;
        self.half_open_successes = 0;
    }
}

impl Default for CircuitBreaker {
    fn default() -> Self {
        Self::new(5, Duration::from_secs(30))
    }
}

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

    #[test]
    fn test_circuit_state_eq() {
        assert_eq!(CircuitState::Closed, CircuitState::Closed);
        assert_eq!(CircuitState::Open, CircuitState::Open);
        assert_eq!(CircuitState::HalfOpen, CircuitState::HalfOpen);
        assert_ne!(CircuitState::Closed, CircuitState::Open);
    }

    #[test]
    fn test_circuit_breaker_new() {
        let cb = CircuitBreaker::new(5, Duration::from_secs(30));
        assert_eq!(cb.state(), CircuitState::Closed);
        assert_eq!(cb.failure_count, 0);
        assert_eq!(cb.failure_threshold, 5);
    }

    #[test]
    fn test_circuit_breaker_default() {
        let cb = CircuitBreaker::default();
        assert_eq!(cb.state(), CircuitState::Closed);
        assert_eq!(cb.failure_threshold, 5);
        assert_eq!(cb.open_duration, Duration::from_secs(30));
    }

    #[test]
    fn test_circuit_breaker_closed_allows_requests() {
        let mut cb = CircuitBreaker::new(3, Duration::from_secs(30));
        assert!(cb.allow_request());
        assert!(cb.allow_request());
        assert!(cb.allow_request());
    }

    #[test]
    fn test_circuit_breaker_trips_on_failures() {
        let mut cb = CircuitBreaker::new(3, Duration::from_secs(30));

        cb.record_failure();
        assert_eq!(cb.state(), CircuitState::Closed);

        cb.record_failure();
        assert_eq!(cb.state(), CircuitState::Closed);

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

    #[test]
    fn test_circuit_breaker_open_blocks_requests() {
        let mut cb = CircuitBreaker::new(2, Duration::from_secs(30));

        cb.record_failure();
        cb.record_failure();
        assert_eq!(cb.state(), CircuitState::Open);

        assert!(!cb.allow_request());
    }

    #[test]
    fn test_circuit_breaker_success_resets_failures() {
        let mut cb = CircuitBreaker::new(3, Duration::from_secs(30));

        cb.record_failure();
        cb.record_failure();
        assert_eq!(cb.failure_count, 2);

        cb.record_success();
        assert_eq!(cb.failure_count, 0);
    }

    #[test]
    fn test_circuit_breaker_half_open_transition() {
        let mut cb = CircuitBreaker::new(2, Duration::from_millis(10));

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

        // Wait for open duration
        std::thread::sleep(Duration::from_millis(15));

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

    #[test]
    fn test_circuit_breaker_half_open_success_closes() {
        let mut cb = CircuitBreaker::new(2, Duration::from_millis(10));

        // Trip and wait for half-open
        cb.record_failure();
        cb.record_failure();
        std::thread::sleep(Duration::from_millis(15));
        let _ = cb.allow_request(); // Transition to half-open

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

        // Success should close the circuit
        cb.record_success();
        assert_eq!(cb.state(), CircuitState::Closed);
    }

    #[test]
    fn test_circuit_breaker_half_open_failure_reopens() {
        let mut cb = CircuitBreaker::new(2, Duration::from_millis(10));

        // Trip and wait for half-open
        cb.record_failure();
        cb.record_failure();
        std::thread::sleep(Duration::from_millis(15));
        let _ = cb.allow_request(); // Transition to half-open

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

        // Failure should reopen
        cb.record_failure();
        assert_eq!(cb.state(), CircuitState::Open);
    }

    #[test]
    fn test_circuit_breaker_reset() {
        let mut cb = CircuitBreaker::new(2, Duration::from_secs(30));

        cb.record_failure();
        cb.record_failure();
        assert_eq!(cb.state(), CircuitState::Open);

        cb.reset();
        assert_eq!(cb.state(), CircuitState::Closed);
        assert_eq!(cb.failure_count, 0);
    }

    /// FALSIFICATION TEST: Circuit MUST trip at exact threshold
    ///
    /// The circuit breaker must trip at exactly failure_threshold failures,
    /// not before and not after. Off-by-one errors are common.
    #[test]
    fn test_falsify_exact_threshold_trip() {
        for threshold in 1..=10 {
            let mut cb = CircuitBreaker::new(threshold, Duration::from_secs(30));

            // Record threshold-1 failures - should NOT trip
            for i in 0..(threshold - 1) {
                cb.record_failure();
                assert_eq!(
                    cb.state(),
                    CircuitState::Closed,
                    "FALSIFICATION FAILED: Circuit tripped after {} failures (threshold={})",
                    i + 1,
                    threshold
                );
            }

            // The threshold-th failure MUST trip the circuit
            cb.record_failure();
            assert_eq!(
                cb.state(),
                CircuitState::Open,
                "FALSIFICATION FAILED: Circuit did NOT trip at exact threshold={}",
                threshold
            );
        }
    }

    /// FALSIFICATION TEST: Open circuit MUST block all requests
    ///
    /// While open (and before timeout), the circuit MUST block 100% of requests.
    /// Any leak would cause cascading failures.
    #[test]
    fn test_falsify_open_blocks_all() {
        let mut cb = CircuitBreaker::new(1, Duration::from_secs(30));

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

        // Try many requests - ALL must be blocked
        let mut allowed = 0;
        for _ in 0..1000 {
            if cb.allow_request() {
                allowed += 1;
            }
        }

        assert_eq!(
            allowed, 0,
            "FALSIFICATION FAILED: {} requests leaked through open circuit",
            allowed
        );
    }

    /// FALSIFICATION TEST: Half-open failure MUST immediately reopen
    ///
    /// A single failure in half-open state must immediately reopen the circuit.
    /// If it doesn't, the system could repeatedly hammer a failing service.
    #[test]
    fn test_falsify_half_open_single_failure_reopens() {
        let mut cb = CircuitBreaker::new(1, Duration::from_millis(5));

        // Trip and wait for half-open
        cb.record_failure();
        std::thread::sleep(Duration::from_millis(10));
        let _ = cb.allow_request(); // Transition to half-open

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

        // Single failure MUST reopen
        cb.record_failure();

        assert_eq!(
            cb.state(),
            CircuitState::Open,
            "FALSIFICATION FAILED: Half-open did not reopen after failure"
        );

        // Verify opened_at was updated (circuit should wait again)
        assert!(cb.opened_at.is_some(), "FALSIFICATION FAILED: opened_at not set after reopen");
    }

    /// FALSIFICATION TEST: State machine must be deterministic
    ///
    /// Same sequence of events must always produce same state.
    /// Non-determinism would make the system unpredictable.
    #[test]
    fn test_falsify_state_machine_determinism() {
        // Run the same sequence multiple times
        for _ in 0..10 {
            let mut cb = CircuitBreaker::new(3, Duration::from_millis(5));

            // Sequence: F, S, F, F, F, wait, S
            cb.record_failure();
            assert_eq!(cb.state(), CircuitState::Closed);

            cb.record_success();
            assert_eq!(cb.failure_count, 0); // Reset

            cb.record_failure();
            cb.record_failure();
            cb.record_failure();
            assert_eq!(cb.state(), CircuitState::Open);

            std::thread::sleep(Duration::from_millis(10));
            let _ = cb.allow_request();
            assert_eq!(cb.state(), CircuitState::HalfOpen);

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

    /// FALSIFICATION TEST: Failures in Open state are no-ops
    ///
    /// Recording failures while Open should not affect anything.
    /// This prevents "double-counting" failures.
    #[test]
    fn test_falsify_open_ignores_failures() {
        let mut cb = CircuitBreaker::new(2, Duration::from_secs(30));

        // Trip the circuit
        cb.record_failure();
        cb.record_failure();
        let opened_at = cb.opened_at;

        // Record more failures while open
        for _ in 0..100 {
            cb.record_failure();
        }

        // State should still be Open, opened_at unchanged
        assert_eq!(cb.state(), CircuitState::Open);
        assert_eq!(
            cb.opened_at, opened_at,
            "FALSIFICATION FAILED: opened_at changed while in Open state"
        );
    }
}