atomic-circuit-breaker 11.2.0

Zero-dependency, lock-free atomic sliding-window circuit breaker with CAS probe gating, monotonic clock support, and RAII guards.
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
use super::*;

/// Lock-free state machine, sliding-window recording, and RAII call execution for `CircuitBreaker`.
impl CircuitBreaker {
    /// Creates a new `CircuitBreaker` after validating `config`.
    ///
    /// # Arguments
    ///
    /// - `CircuitBreakerConfig` - Configuration to validate and apply.
    ///
    /// # Returns
    ///
    /// - `Result<Self, CircuitBreakerError>` - Constructed breaker or validation error.
    pub fn new(config: CircuitBreakerConfig) -> Result<Self, CircuitBreakerError> {
        Self::with_clock(config, CircuitClock::new())
    }

    /// Creates a new `CircuitBreaker` anchored at `clock` after validating `config`.
    ///
    /// # Arguments
    ///
    /// - `CircuitBreakerConfig` - Configuration to validate and apply.
    /// - `CircuitClock` - Monotonic clock origin.
    ///
    /// # Returns
    ///
    /// - `Result<Self, CircuitBreakerError>` - Constructed breaker or validation error.
    pub fn with_clock(
        config: CircuitBreakerConfig,
        clock: CircuitClock,
    ) -> Result<Self, CircuitBreakerError> {
        config.validate()?;
        let window: SlidingWindow = SlidingWindow::new(config.get_window_ns());
        let opened_at_slots: [AtomicU64; OPENED_AT_SLOTS] = [
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
        ];
        Ok(Self {
            config,
            clock,
            state_word: CachePadded::new(AtomicU64::new(Self::pack_state(STATE_CLOSED, 0, 0, 0))),
            opened_at_slots: CachePadded::new(opened_at_slots),
            window,
        })
    }

    /// Returns a reference to the immutable configuration.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    ///
    /// # Returns
    ///
    /// - `&CircuitBreakerConfig` - Reference to the configuration.
    #[inline(always)]
    pub fn get_config(&self) -> &CircuitBreakerConfig {
        &self.config
    }

    /// Returns a reference to the embedded monotonic clock.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    ///
    /// # Returns
    ///
    /// - `&CircuitClock` - Reference to the clock.
    #[inline(always)]
    pub fn get_clock(&self) -> &CircuitClock {
        &self.clock
    }

    /// Returns a reference to the packed atomic state word.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    ///
    /// # Returns
    ///
    /// - `&AtomicU64` - Reference to the atomic state word.
    #[inline(always)]
    pub(crate) fn get_state_word(&self) -> &AtomicU64 {
        self.state_word.get_value()
    }

    /// Returns the slice of generation-indexed open-timestamp slots.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    ///
    /// # Returns
    ///
    /// - `&[AtomicU64]` - Slice of 8 timestamp slots.
    #[inline(always)]
    pub(crate) fn get_opened_at_slots(&self) -> &[AtomicU64] {
        self.opened_at_slots.get_value()
    }

    /// Returns a reference to the inline sliding window.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    ///
    /// # Returns
    ///
    /// - `&SlidingWindow` - Reference to the sliding window.
    #[inline(always)]
    pub(crate) fn get_window(&self) -> &SlidingWindow {
        &self.window
    }

    /// Returns the current circuit state without mutating transitions.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    ///
    /// # Returns
    ///
    /// - `CircuitState` - Current state (`Closed`, `Open`, or `HalfOpen`).
    #[inline(always)]
    pub fn state(&self) -> CircuitState {
        Self::decode_state(self.get_state_word().load(Ordering::Acquire))
    }

    /// Checks whether a call is currently permitted using the embedded monotonic clock.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if admitted (including half-open probe permits), `false` if rejected.
    #[inline(always)]
    pub fn allow(&self) -> bool {
        let current: u64 = self.get_state_word().load(Ordering::Relaxed);
        if (current >> STATE_SHIFT) == STATE_CLOSED {
            return true;
        }
        self.try_acquire_at_ns(self.get_clock().now_ns())
            .is_allowed()
    }

    /// Checks whether a call is permitted at monotonic timestamp `now_ns`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if admitted, `false` if rejected.
    #[inline(always)]
    pub fn allow_at_ns(&self, now_ns: u64) -> bool {
        let current: u64 = self.get_state_word().load(Ordering::Relaxed);
        if (current >> STATE_SHIFT) == STATE_CLOSED {
            return true;
        }
        self.try_acquire_at_ns(now_ns).is_allowed()
    }

    /// Evaluates admission using the embedded clock, returning a detailed `CircuitDecision`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    ///
    /// # Returns
    ///
    /// - `CircuitDecision` - Decision including state, generation, probe status, and retry wait.
    #[inline(always)]
    pub fn try_acquire(&self) -> CircuitDecision {
        let current: u64 = self.get_state_word().load(Ordering::Relaxed);
        if (current >> STATE_SHIFT) == STATE_CLOSED {
            let generation: u32 = ((current >> GEN_SHIFT) & GEN_MASK) as u32;
            return CircuitDecision::new(true, CircuitState::Closed, generation, 0, false);
        }
        self.try_acquire_at_ns(self.get_clock().now_ns())
    }

    /// Evaluates admission at monotonic timestamp `now_ns` with atomic CAS probe gating.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `CircuitDecision` - Admission decision and metadata.
    #[inline(always)]
    pub fn try_acquire_at_ns(&self, now_ns: u64) -> CircuitDecision {
        let initial: u64 = self.get_state_word().load(Ordering::Relaxed);
        if (initial >> STATE_SHIFT) == STATE_CLOSED {
            let generation: u32 = ((initial >> GEN_SHIFT) & GEN_MASK) as u32;
            return CircuitDecision::new(true, CircuitState::Closed, generation, 0, false);
        }
        self.try_acquire_slow_at_ns(now_ns)
    }

    /// Cold admission path handling `Open` cooldown expiry and `HalfOpen` probe gating.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `CircuitDecision` - Admission decision and metadata.
    #[cold]
    #[inline(never)]
    fn try_acquire_slow_at_ns(&self, now_ns: u64) -> CircuitDecision {
        let state_atomic: &AtomicU64 = self.get_state_word();
        let mut current: u64 = state_atomic.load(Ordering::Acquire);
        let cooldown_ns: u64 = self.get_config().get_cooldown_ns();
        let max_probes: u16 = self.get_config().get_half_open_max_probes();
        loop {
            let tag: u64 = current >> STATE_SHIFT;
            let generation: u32 = ((current >> GEN_SHIFT) & GEN_MASK) as u32;
            if tag == STATE_CLOSED {
                return CircuitDecision::new(true, CircuitState::Closed, generation, 0, false);
            }
            if tag == STATE_OPEN {
                let opened_at: u64 = self.load_opened_at_relaxed(generation);
                let elapsed: u64 = now_ns.saturating_sub(opened_at);
                if elapsed < cooldown_ns {
                    return CircuitDecision::new(
                        false,
                        CircuitState::Open,
                        generation,
                        cooldown_ns - elapsed,
                        false,
                    );
                }
                let next_gen: u32 = Self::next_generation(generation);
                let half_open_word: u64 = Self::pack_state(STATE_HALF_OPEN, next_gen, 1, 0);
                match state_atomic.compare_exchange_weak(
                    current,
                    half_open_word,
                    Ordering::AcqRel,
                    Ordering::Acquire,
                ) {
                    Ok(_) => {
                        return CircuitDecision::new(
                            true,
                            CircuitState::HalfOpen,
                            next_gen,
                            0,
                            true,
                        );
                    }
                    Err(observed) => {
                        current = observed;
                        continue;
                    }
                }
            }
            let dispatched: u16 = ((current >> HI_AUX_SHIFT) & AUX_MASK) as u16;
            let succeeded: u16 = (current & AUX_MASK) as u16;
            if dispatched >= max_probes {
                return CircuitDecision::new(false, CircuitState::HalfOpen, generation, 0, false);
            }
            let next_word: u64 =
                Self::pack_state(STATE_HALF_OPEN, generation, dispatched + 1, succeeded);
            match state_atomic.compare_exchange_weak(
                current,
                next_word,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => {
                    return CircuitDecision::new(true, CircuitState::HalfOpen, generation, 0, true);
                }
                Err(observed) => {
                    current = observed;
                }
            }
        }
    }

    /// Acquires an RAII `CircuitGuard` using the embedded clock, returning `Err` when rejected.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    ///
    /// # Returns
    ///
    /// - `Result<CircuitGuard<'_>, CircuitDecision>` - Active guard on admission or rejection decision.
    #[inline(always)]
    pub fn acquire_guard(&self) -> Result<CircuitGuard<'_>, CircuitDecision> {
        let decision: CircuitDecision = self.try_acquire();
        if decision.is_allowed() {
            Ok(CircuitGuard::new(self, decision))
        } else {
            Err(decision)
        }
    }

    /// Executes `operation` protected by the circuit breaker, automatically recording its outcome.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `F` - Fallible operation closure returning `Result<T, E>`.
    ///
    /// # Returns
    ///
    /// - `Result<T, CallError<E>>` - Operation result or `CallError::Rejected` / `CallError::Inner`.
    #[inline(always)]
    pub fn call<T, E, F>(&self, operation: F) -> Result<T, CallError<E>>
    where
        F: FnOnce() -> Result<T, E>,
    {
        let guard: CircuitGuard<'_> = match self.acquire_guard() {
            Ok(g) => g,
            Err(rejected) => {
                return Err(CallError::Rejected {
                    state: rejected.get_state(),
                    retry_after_ns: rejected.get_retry_after_ns(),
                });
            }
        };
        match operation() {
            Ok(value) => {
                guard.mark_success();
                Ok(value)
            }
            Err(err) => {
                guard.mark_failure();
                Err(CallError::Inner(err))
            }
        }
    }

    /// Records a successful call outcome using the embedded monotonic clock.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    #[inline(always)]
    pub fn record_success(&self) {
        self.record_success_at_ns(self.get_clock().now_ns());
    }

    /// Records a successful call outcome at monotonic timestamp `now_ns`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    #[inline(always)]
    pub fn record_success_at_ns(&self, now_ns: u64) {
        self.record_success_internal(None, now_ns);
    }

    /// Records a successful outcome tied to a prior `CircuitDecision`, ignoring stale generations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `CircuitDecision` - The decision obtained before executing the call.
    #[inline(always)]
    pub fn record_success_for(&self, decision: CircuitDecision) {
        self.record_success_for_at_ns(decision, self.get_clock().now_ns());
    }

    /// Records a successful outcome for `decision` at `now_ns`, ignoring stale generations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `CircuitDecision` - The decision obtained before executing the call.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    #[inline(always)]
    pub fn record_success_for_at_ns(&self, decision: CircuitDecision, now_ns: u64) {
        if !decision.is_allowed() {
            return;
        }
        self.record_success_internal(Some(decision.get_generation()), now_ns);
    }

    /// Records a failed call outcome using the embedded monotonic clock.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    #[inline(always)]
    pub fn record_failure(&self) {
        self.record_failure_at_ns(self.get_clock().now_ns());
    }

    /// Records a failed call outcome at monotonic timestamp `now_ns`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    #[inline(always)]
    pub fn record_failure_at_ns(&self, now_ns: u64) {
        self.record_failure_internal(None, now_ns);
    }

    /// Records a failed outcome tied to a prior `CircuitDecision`, ignoring stale generations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `CircuitDecision` - The decision obtained before executing the call.
    #[inline(always)]
    pub fn record_failure_for(&self, decision: CircuitDecision) {
        self.record_failure_for_at_ns(decision, self.get_clock().now_ns());
    }

    /// Records a failed outcome for `decision` at `now_ns`, ignoring stale generations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `CircuitDecision` - The decision obtained before executing the call.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    #[inline(always)]
    pub fn record_failure_for_at_ns(&self, decision: CircuitDecision, now_ns: u64) {
        if !decision.is_allowed() {
            return;
        }
        self.record_failure_internal(Some(decision.get_generation()), now_ns);
    }

    /// Captures a point-in-time diagnostic snapshot using the embedded monotonic clock.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    ///
    /// # Returns
    ///
    /// - `CircuitSnapshot` - Snapshot of state, window counters, and cooldown timing.
    #[inline(always)]
    pub fn snapshot(&self) -> CircuitSnapshot {
        self.snapshot_at_ns(self.get_clock().now_ns())
    }

    /// Captures a point-in-time diagnostic snapshot at monotonic timestamp `now_ns`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `CircuitSnapshot` - Snapshot of state, window counters, and cooldown timing.
    #[inline(always)]
    pub fn snapshot_at_ns(&self, now_ns: u64) -> CircuitSnapshot {
        let mut word: u64 = self.get_state_word().load(Ordering::Relaxed);
        let mut tag: u64 = word >> STATE_SHIFT;
        if tag == STATE_OPEN {
            word = self.get_state_word().load(Ordering::Acquire);
            tag = word >> STATE_SHIFT;
        }
        let generation: u32 = ((word >> GEN_SHIFT) & GEN_MASK) as u32;
        let hi_aux: u16 = ((word >> HI_AUX_SHIFT) & AUX_MASK) as u16;
        if tag == STATE_CLOSED {
            let (window_successes, window_failures): (u64, u64) =
                self.get_window().sum(generation, now_ns);
            return CircuitSnapshot {
                state: CircuitState::Closed,
                generation,
                window_successes,
                window_failures,
                consecutive_failures: hi_aux,
                half_open_dispatched: 0,
                half_open_succeeded: 0,
                retry_after_ns: 0,
            };
        }
        if tag == STATE_OPEN {
            let opened_at: u64 = self.load_opened_at_relaxed(generation);
            let elapsed: u64 = now_ns.saturating_sub(opened_at);
            let retry_after_ns: u64 = self.get_config().get_cooldown_ns().saturating_sub(elapsed);
            return CircuitSnapshot {
                state: CircuitState::Open,
                generation,
                window_successes: 0,
                window_failures: 0,
                consecutive_failures: 0,
                half_open_dispatched: 0,
                half_open_succeeded: 0,
                retry_after_ns,
            };
        }
        let lo_aux: u16 = (word & AUX_MASK) as u16;
        CircuitSnapshot {
            state: CircuitState::HalfOpen,
            generation,
            window_successes: 0,
            window_failures: 0,
            consecutive_failures: 0,
            half_open_dispatched: hi_aux,
            half_open_succeeded: lo_aux,
            retry_after_ns: 0,
        }
    }

    /// Resets the breaker to `Closed`, clears all window buckets, and advances generation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    pub fn reset(&self) {
        let state_atomic: &AtomicU64 = self.get_state_word();
        let mut current: u64 = state_atomic.load(Ordering::Acquire);
        loop {
            let generation: u32 = ((current >> GEN_SHIFT) & GEN_MASK) as u32;
            let next_gen: u32 = Self::next_generation(generation);
            let closed_word: u64 = Self::pack_state(STATE_CLOSED, next_gen, 0, 0);
            match state_atomic.compare_exchange_weak(
                current,
                closed_word,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => {
                    self.get_window().clear();
                    return;
                }
                Err(observed) => {
                    current = observed;
                }
            }
        }
    }

    /// Forces the breaker into `Open` starting cooldown at the current monotonic time.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    #[inline(always)]
    pub fn force_open(&self) {
        self.force_open_at_ns(self.get_clock().now_ns());
    }

    /// Forces the breaker into `Open` starting cooldown at monotonic timestamp `now_ns`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    pub fn force_open_at_ns(&self, now_ns: u64) {
        let state_atomic: &AtomicU64 = self.get_state_word();
        let mut current: u64 = state_atomic.load(Ordering::Acquire);
        loop {
            let generation: u32 = ((current >> GEN_SHIFT) & GEN_MASK) as u32;
            let next_gen: u32 = Self::next_generation(generation);
            self.store_opened_at(next_gen, now_ns);
            let open_word: u64 = Self::pack_state(STATE_OPEN, next_gen, 0, 0);
            match state_atomic.compare_exchange_weak(
                current,
                open_word,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return,
                Err(observed) => {
                    current = observed;
                }
            }
        }
    }

    /// Releases a cancelled `HalfOpen` probe slot if the breaker is still in the same generation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `CircuitDecision` - The decision whose probe slot should be returned.
    pub(crate) fn release_probe_for(&self, decision: CircuitDecision) {
        if !decision.is_probe() {
            return;
        }
        let target_gen: u32 = decision.get_generation();
        let state_atomic: &AtomicU64 = self.get_state_word();
        let mut current: u64 = state_atomic.load(Ordering::Acquire);
        loop {
            let tag: u64 = current >> STATE_SHIFT;
            let generation: u32 = ((current >> GEN_SHIFT) & GEN_MASK) as u32;
            if tag != STATE_HALF_OPEN || generation != target_gen {
                return;
            }
            let dispatched: u16 = ((current >> HI_AUX_SHIFT) & AUX_MASK) as u16;
            let succeeded: u16 = (current & AUX_MASK) as u16;
            if dispatched == 0 {
                return;
            }
            let next_word: u64 =
                Self::pack_state(STATE_HALF_OPEN, generation, dispatched - 1, succeeded);
            match state_atomic.compare_exchange_weak(
                current,
                next_word,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return,
                Err(observed) => {
                    current = observed;
                }
            }
        }
    }

    /// Internal lock-free success recording with optional generation matching.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `Option<u32>` - Optional generation guard from a `CircuitDecision`.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    #[inline(always)]
    pub(crate) fn record_success_internal(&self, expected_gen: Option<u32>, now_ns: u64) {
        let current: u64 = self.get_state_word().load(Ordering::Relaxed);
        let generation: u32 = ((current >> GEN_SHIFT) & GEN_MASK) as u32;
        if let Some(req_gen) = expected_gen
            && req_gen != generation
        {
            return;
        }
        if (current & !(GEN_MASK << GEN_SHIFT)) == 0 {
            self.get_window().record_success(generation, now_ns);
            return;
        }
        let tag: u64 = current >> STATE_SHIFT;
        if tag == STATE_CLOSED {
            self.get_window().record_success(generation, now_ns);
            self.clear_closed_consecutive_slow(current, generation);
            return;
        }
        if tag == STATE_HALF_OPEN {
            self.record_success_half_open(expected_gen);
        }
    }

    /// Cold path clearing a non-zero consecutive failure streak after a closed success.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u64` - Observed packed state word with non-zero streak.
    /// - `u32` - Active closed generation.
    #[cold]
    #[inline(never)]
    fn clear_closed_consecutive_slow(&self, current: u64, generation: u32) {
        let cleared: u64 = Self::pack_state(STATE_CLOSED, generation, 0, 0);
        let _: Result<u64, u64> = self.get_state_word().compare_exchange(
            current,
            cleared,
            Ordering::Relaxed,
            Ordering::Relaxed,
        );
    }

    /// Cold path advancing `HalfOpen` probe successes toward `Closed`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `Option<u32>` - Optional generation guard from a `CircuitDecision`.
    #[cold]
    #[inline(never)]
    fn record_success_half_open(&self, expected_gen: Option<u32>) {
        let state_atomic: &AtomicU64 = self.get_state_word();
        let success_threshold: u16 = self.get_config().get_half_open_success_threshold();
        let mut current: u64 = state_atomic.load(Ordering::Acquire);
        loop {
            let tag: u64 = current >> STATE_SHIFT;
            let generation: u32 = ((current >> GEN_SHIFT) & GEN_MASK) as u32;
            if let Some(req_gen) = expected_gen
                && req_gen != generation
            {
                return;
            }
            if tag != STATE_HALF_OPEN {
                return;
            }
            let dispatched: u16 = ((current >> HI_AUX_SHIFT) & AUX_MASK) as u16;
            let succeeded: u16 = (current & AUX_MASK) as u16;
            let next_succeeded: u16 = succeeded.saturating_add(1);
            let next_word: u64 = if next_succeeded >= success_threshold {
                Self::pack_state(STATE_CLOSED, Self::next_generation(generation), 0, 0)
            } else {
                Self::pack_state(STATE_HALF_OPEN, generation, dispatched, next_succeeded)
            };
            match state_atomic.compare_exchange_weak(
                current,
                next_word,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return,
                Err(observed) => {
                    current = observed;
                }
            }
        }
    }

    /// Internal lock-free failure recording and threshold evaluation with optional generation matching.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `Option<u32>` - Optional generation guard from a `CircuitDecision`.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    #[inline(always)]
    pub(crate) fn record_failure_internal(&self, expected_gen: Option<u32>, now_ns: u64) {
        let current: u64 = self.get_state_word().load(Ordering::Relaxed);
        let tag: u64 = current >> STATE_SHIFT;
        let generation: u32 = ((current >> GEN_SHIFT) & GEN_MASK) as u32;
        if let Some(req_gen) = expected_gen
            && req_gen != generation
        {
            return;
        }
        if tag == STATE_CLOSED {
            let epoch: u64 = self.get_window().epoch_of(now_ns);
            self.get_window().record_failure_at_epoch(generation, epoch);
            let new_consec: u16 = self.increment_closed_consecutive(generation, current);
            if self.should_trip_closed_at_epoch(generation, new_consec, epoch) {
                self.try_trip_to_open(generation, now_ns);
            }
            return;
        }
        if tag == STATE_HALF_OPEN {
            self.try_trip_to_open(generation, now_ns);
        }
    }

    /// Atomically increments the consecutive failure streak while staying in `Closed(generation)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u32` - Active closed generation.
    /// - `u64` - Most recently observed packed state word.
    ///
    /// # Returns
    ///
    /// - `u16` - Updated consecutive failure count (`0` if state transitioned away).
    #[inline(always)]
    pub(crate) fn increment_closed_consecutive(&self, target_gen: u32, initial_word: u64) -> u16 {
        let state_atomic: &AtomicU64 = self.get_state_word();
        let mut current: u64 = initial_word;
        loop {
            let tag: u64 = current >> STATE_SHIFT;
            let generation: u32 = ((current >> GEN_SHIFT) & GEN_MASK) as u32;
            if tag != STATE_CLOSED || generation != target_gen {
                return 0;
            }
            let consec: u16 = ((current >> HI_AUX_SHIFT) & AUX_MASK) as u16;
            if consec == u16::MAX {
                return u16::MAX;
            }
            let next_consec: u16 = consec + 1;
            let next_word: u64 = Self::pack_state(STATE_CLOSED, generation, next_consec, 0);
            match state_atomic.compare_exchange_weak(
                current,
                next_word,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => return next_consec,
                Err(observed) => {
                    current = observed;
                }
            }
        }
    }

    /// Evaluates configured consecutive-failure, window-count, and window-rate trip predicates.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u32` - Active closed generation.
    /// - `u16` - Updated consecutive failure count.
    /// - `u64` - Precomputed current bucket epoch.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when any configured tripping condition is satisfied.
    #[inline(always)]
    pub(crate) fn should_trip_closed_at_epoch(
        &self,
        generation: u32,
        consecutive: u16,
        cur_epoch: u64,
    ) -> bool {
        let cfg: &CircuitBreakerConfig = self.get_config();
        if let Some(consec_limit) = cfg.get_consecutive_failure_threshold()
            && consecutive >= consec_limit
        {
            return true;
        }
        let fail_limit_opt: Option<u64> = cfg.get_failure_threshold();
        let bps_opt: Option<u32> = cfg.get_failure_rate_bps();
        if fail_limit_opt.is_none() && bps_opt.is_none() {
            return false;
        }
        let min_calls: u64 = cfg.get_minimum_calls();
        if bps_opt.is_none()
            && let Some(fail_limit) = fail_limit_opt
        {
            let failures: u64 = self
                .get_window()
                .sum_failures_at_epoch(generation, cur_epoch);
            if failures < fail_limit {
                return false;
            }
            if failures >= min_calls {
                return true;
            }
            let successes: u64 = self
                .get_window()
                .sum_successes_at_epoch(generation, cur_epoch);
            return successes.saturating_add(failures) >= min_calls;
        }
        let (successes, failures): (u64, u64) =
            self.get_window().sum_at_epoch(generation, cur_epoch);
        let total: u64 = successes.saturating_add(failures);
        if total < min_calls {
            return false;
        }
        if let Some(fail_limit) = fail_limit_opt
            && failures >= fail_limit
        {
            return true;
        }
        if let Some(bps) = bps_opt {
            let lhs: u64 = failures.wrapping_mul(FAILURE_RATE_BPS_SCALE as u64);
            let rhs: u64 = total.wrapping_mul(bps as u64);
            if lhs >= rhs {
                return true;
            }
        }
        false
    }

    /// Atomically transitions the breaker from `target_gen` into `Open(target_gen + 1)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u32` - Expected current generation.
    /// - `u64` - Monotonic open timestamp in nanoseconds.
    #[inline(always)]
    pub(crate) fn try_trip_to_open(&self, target_gen: u32, now_ns: u64) {
        let next_gen: u32 = Self::next_generation(target_gen);
        let open_word: u64 = Self::pack_state(STATE_OPEN, next_gen, 0, 0);
        let state_atomic: &AtomicU64 = self.get_state_word();
        let mut current: u64 = state_atomic.load(Ordering::Acquire);
        loop {
            let tag: u64 = current >> STATE_SHIFT;
            let generation: u32 = ((current >> GEN_SHIFT) & GEN_MASK) as u32;
            if generation != target_gen || tag == STATE_OPEN {
                return;
            }
            self.store_opened_at(next_gen, now_ns);
            match state_atomic.compare_exchange_weak(
                current,
                open_word,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return,
                Err(observed) => {
                    current = observed;
                }
            }
        }
    }

    /// Stores the open timestamp into the slot assigned to `generation`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u32` - Target `Open` generation.
    /// - `u64` - Monotonic open timestamp in nanoseconds.
    #[inline(always)]
    pub(crate) fn store_opened_at(&self, generation: u32, now_ns: u64) {
        let slot: usize = (generation as usize) & OPENED_AT_SLOT_MASK;
        self.get_opened_at_slots()[slot].store(now_ns, Ordering::Release);
    }

    /// Loads the open timestamp for `generation` after an established `Acquire` synchronization.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The circuit breaker.
    /// - `u32` - Active `Open` generation.
    ///
    /// # Returns
    ///
    /// - `u64` - Monotonic timestamp when the circuit entered `Open`.
    #[inline(always)]
    pub(crate) fn load_opened_at_relaxed(&self, generation: u32) -> u64 {
        let slot: usize = (generation as usize) & OPENED_AT_SLOT_MASK;
        self.get_opened_at_slots()[slot].load(Ordering::Relaxed)
    }

    /// Packs state tag, 30-bit generation, and two 16-bit counters into one `u64`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Encoded 2-bit state tag.
    /// - `u32` - 30-bit generation counter.
    /// - `u16` - Upper 16-bit counter.
    /// - `u16` - Lower 16-bit counter.
    ///
    /// # Returns
    ///
    /// - `u64` - Packed state word.
    #[inline(always)]
    pub(crate) fn pack_state(tag: u64, generation: u32, hi_aux: u16, lo_aux: u16) -> u64 {
        (tag << STATE_SHIFT)
            | (((generation as u64) & GEN_MASK) << GEN_SHIFT)
            | ((hi_aux as u64) << HI_AUX_SHIFT)
            | (lo_aux as u64)
    }

    /// Advances the 30-bit generation counter with wraparound.
    ///
    /// # Arguments
    ///
    /// - `u32` - Current generation.
    ///
    /// # Returns
    ///
    /// - `u32` - Next generation in `0..2^30`.
    #[inline(always)]
    pub(crate) fn next_generation(generation: u32) -> u32 {
        (((generation as u64).wrapping_add(1)) & GEN_MASK) as u32
    }

    /// Decodes the 2-bit state tag from a packed state word.
    ///
    /// # Arguments
    ///
    /// - `u64` - Packed state word.
    ///
    /// # Returns
    ///
    /// - `CircuitState` - Decoded lifecycle state.
    #[inline(always)]
    pub(crate) fn decode_state(word: u64) -> CircuitState {
        match word >> STATE_SHIFT {
            STATE_OPEN => CircuitState::Open,
            STATE_HALF_OPEN => CircuitState::HalfOpen,
            _ => CircuitState::Closed,
        }
    }
}