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
use super::*;

/// Accessors for `CachePadded`.
impl<T> CachePadded<T> {
    /// Wraps `value` on an isolated 128-byte cache-line boundary.
    ///
    /// # Arguments
    ///
    /// - `T` - Value to pad and align.
    ///
    /// # Returns
    ///
    /// - `Self` - Aligned wrapper.
    #[inline(always)]
    pub(crate) const fn new(value: T) -> Self {
        Self { value }
    }

    /// Returns a shared reference to the aligned inner value.
    ///
    /// # Returns
    ///
    /// - `&T` - Reference to the wrapped value.
    #[inline(always)]
    pub(crate) fn get_value(&self) -> &T {
        &self.value
    }
}

/// Construction and branchless quotient evaluation for `FastDivU64`.
impl FastDivU64 {
    /// Precomputes Granlund-Montgomery reciprocal parameters for any `divisor >= 1`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Positive divisor (`0` is clamped to `1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Precomputed exact divider.
    #[inline(always)]
    pub(crate) const fn new(divisor: u64) -> Self {
        let d: u64 = if divisor == 0 { 1 } else { divisor };
        if d.is_power_of_two() {
            return Self {
                mul: 0,
                sh1: 0,
                sh2: d.trailing_zeros(),
                mode: 0,
            };
        }
        let sh: u32 = 63 - d.leading_zeros();
        let p: u128 = 1u128 << (64 + sh);
        let d_u128: u128 = d as u128;
        let rem: u128 = p % d_u128;
        let r: u128 = d_u128 - rem;
        if (u64::MAX as u128) * r < p {
            let simple_mul: u64 = ((p / d_u128) as u64) + 1;
            return Self {
                mul: simple_mul,
                sh1: 0,
                sh2: sh,
                mode: 1,
            };
        }
        let l: u32 = 64 - (d - 1).leading_zeros();
        let sh1: u32 = 1;
        let sh2: u32 = l - 1;
        let num: u128 = (1u128 << 64) * ((1u128 << l) - d_u128);
        let mul: u64 = ((num / d_u128) as u64) + 1;
        Self {
            mul,
            sh1,
            sh2,
            mode: 2,
        }
    }

    /// Returns the reciprocal multiplier.
    ///
    /// # Returns
    ///
    /// - `u64` - Magic multiplier.
    #[inline(always)]
    pub(crate) fn get_mul(&self) -> u64 {
        self.mul
    }

    /// Returns the first right shift amount.
    ///
    /// # Returns
    ///
    /// - `u32` - First shift count.
    #[inline(always)]
    pub(crate) fn get_sh1(&self) -> u32 {
        self.sh1
    }

    /// Returns the final right shift amount.
    ///
    /// # Returns
    ///
    /// - `u32` - Final shift count.
    #[inline(always)]
    pub(crate) fn get_sh2(&self) -> u32 {
        self.sh2
    }

    /// Returns the division dispatch mode.
    ///
    /// # Returns
    ///
    /// - `u8` - Mode (`0` pow2, `1` simple `umulh`, `2` general 65-bit).
    #[inline(always)]
    pub(crate) fn get_mode(&self) -> u8 {
        self.mode
    }

    /// Computes exact `n / divisor` without hardware integer division.
    ///
    /// # Arguments
    ///
    /// - `u64` - Dividend.
    ///
    /// # Returns
    ///
    /// - `u64` - Exact unsigned quotient.
    #[inline(always)]
    pub(crate) fn div(&self, n: u64) -> u64 {
        let mode: u8 = self.get_mode();
        if mode == 1 {
            return ((((self.get_mul() as u128).wrapping_mul(n as u128)) >> 64) as u64)
                >> self.get_sh2();
        }
        if mode == 0 {
            return n >> self.get_sh2();
        }
        let t1: u64 = (((self.get_mul() as u128).wrapping_mul(n as u128)) >> 64) as u64;
        (((n.wrapping_sub(t1)) >> self.get_sh1()).wrapping_add(t1)) >> self.get_sh2()
    }
}

/// Lock-free recording, aggregation, and clearing operations for `SlidingWindow`.
impl SlidingWindow {
    /// Creates a zeroed 16-slot atomic counter array.
    ///
    /// # Returns
    ///
    /// - `[AtomicU64; SLIDING_WINDOW_BUCKETS]` - Array of 16 zeroed atomic counters.
    #[inline(always)]
    fn new_counter_array() -> [AtomicU64; SLIDING_WINDOW_BUCKETS] {
        [
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
            AtomicU64::new(0),
        ]
    }

    /// Creates a new `SlidingWindow` covering at least `window_ns` across 16 ring buckets.
    ///
    /// # Arguments
    ///
    /// - `u64` - Sliding-window duration in nanoseconds (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Zeroed sliding window with precomputed epoch divider.
    #[inline(always)]
    pub(crate) fn new(window_ns: u64) -> Self {
        let bucket_ns: u64 = window_ns.div_ceil(SLIDING_WINDOW_BUCKETS as u64).max(1);
        let fast_div: FastDivU64 = FastDivU64::new(bucket_ns);
        Self {
            fast_div,
            bucket_ns,
            successes: [
                CachePadded::new(Self::new_counter_array()),
                CachePadded::new(Self::new_counter_array()),
                CachePadded::new(Self::new_counter_array()),
                CachePadded::new(Self::new_counter_array()),
            ],
            failures: CachePadded::new(Self::new_counter_array()),
        }
    }

    /// Returns the precomputed reciprocal epoch divider.
    ///
    /// # Returns
    ///
    /// - `&FastDivU64` - Reference to the fast divider.
    #[inline(always)]
    pub(crate) fn get_fast_div(&self) -> &FastDivU64 {
        &self.fast_div
    }

    /// Returns the single-bucket width in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `u64` - Bucket duration in nanoseconds.
    #[inline(always)]
    pub(crate) fn get_bucket_ns(&self) -> u64 {
        self.bucket_ns
    }

    /// Returns the striped 16-slot atomic success counter arrays.
    ///
    /// # Returns
    ///
    /// - `&[CachePadded<[AtomicU64; SLIDING_WINDOW_BUCKETS]>; SUCCESS_STRIPE_COUNT]` - Reference to all success stripes.
    #[inline(always)]
    pub(crate) fn get_successes(
        &self,
    ) -> &[CachePadded<[AtomicU64; SLIDING_WINDOW_BUCKETS]>; SUCCESS_STRIPE_COUNT] {
        &self.successes
    }

    /// Returns the 16-slot atomic failure counter array.
    ///
    /// # Returns
    ///
    /// - `&[AtomicU64; SLIDING_WINDOW_BUCKETS]` - Reference to all 16 failure counters.
    #[inline(always)]
    pub(crate) fn get_failures(&self) -> &[AtomicU64; SLIDING_WINDOW_BUCKETS] {
        self.failures.get_value()
    }

    /// Converts a nanosecond timestamp into its ring-bucket epoch.
    ///
    /// # Arguments
    ///
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `u64` - Bucket epoch (`now_ns / bucket_ns`).
    #[inline(always)]
    pub(crate) fn epoch_of(&self, now_ns: u64) -> u64 {
        let _: u64 = self.get_bucket_ns();
        self.get_fast_div().div(now_ns)
    }

    /// Explicitly clears all 16 ring buckets for both successes and failures.
    #[inline(always)]
    pub(crate) fn clear(&self) {
        for stripe in self.get_successes() {
            for counter in stripe.get_value() {
                counter.store(0, Ordering::Release);
            }
        }
        for counter in self.get_failures() {
            counter.store(0, Ordering::Release);
        }
    }

    /// Records a single success for `(generation, now_ns)` on a wait-free striped bucket counter.
    ///
    /// # Arguments
    ///
    /// - `u32` - Current circuit breaker generation.
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    #[inline(always)]
    pub(crate) fn record_success(&self, generation: u32, now_ns: u64) {
        let epoch: u64 = self.epoch_of(now_ns);
        let lane: usize = ((now_ns >> 2) as usize) & SUCCESS_STRIPE_MASK;
        let slot: usize = (epoch as usize) & SLIDING_WINDOW_MASK;
        let cycle: u64 = (epoch >> SLIDING_WINDOW_SHIFT) & BUCKET_CYCLE_MASK;
        Self::increment_counter(
            &self.get_successes()[lane].get_value()[slot],
            generation,
            cycle,
        );
    }

    /// Records a single failure for `(generation, epoch)` using one lock-free CAS.
    ///
    /// # Arguments
    ///
    /// - `u32` - Current circuit breaker generation.
    /// - `u64` - Precomputed bucket epoch.
    #[inline(always)]
    pub(crate) fn record_failure_at_epoch(&self, generation: u32, epoch: u64) {
        let slot: usize = (epoch as usize) & SLIDING_WINDOW_MASK;
        let cycle: u64 = (epoch >> SLIDING_WINDOW_SHIFT) & BUCKET_CYCLE_MASK;
        Self::increment_counter(&self.get_failures()[slot], generation, cycle);
    }

    /// Sums active counts from one contiguous 16-slot atomic array at `(generation, cur_epoch)`.
    ///
    /// # Arguments
    ///
    /// - `&[AtomicU64; SLIDING_WINDOW_BUCKETS]` - Contiguous 16-slot atomic counter array.
    /// - `u32` - Active circuit breaker generation.
    /// - `u64` - Current bucket epoch.
    ///
    /// # Returns
    ///
    /// - `u64` - Sum of active counts matching `(generation, cur_epoch)`.
    #[inline(always)]
    fn sum_array_at_epoch(
        counters: &[AtomicU64; SLIDING_WINDOW_BUCKETS],
        generation: u32,
        cur_epoch: u64,
    ) -> u64 {
        let cur_slot: usize = (cur_epoch as usize) & SLIDING_WINDOW_MASK;
        let cur_cycle: u64 = (cur_epoch >> SLIDING_WINDOW_SHIFT) & BUCKET_CYCLE_MASK;
        let gen_shifted: u64 = ((generation as u64) & BUCKET_GEN_MASK) << BUCKET_CYCLE_BITS;
        let tag_cur: u64 = gen_shifted | cur_cycle;
        if cur_epoch < SLIDING_WINDOW_LAST_SLOT {
            let mut total: u64 = 0;
            let mut idx: usize = 0;
            while idx <= cur_slot {
                let word: u64 = counters[idx].load(Ordering::Relaxed);
                let mask: u64 = u64::from((word >> BUCKET_COUNT_BITS) == tag_cur).wrapping_neg();
                total += (word & BUCKET_COUNT_MASK) & mask;
                idx += 1;
            }
            return total;
        }
        let prev_cycle: u64 = cur_cycle.wrapping_sub(1) & BUCKET_CYCLE_MASK;
        let tag_prev: u64 = gen_shifted | prev_cycle;
        let mut total: u64 = 0;
        let mut idx: usize = 0;
        while idx < SLIDING_WINDOW_BUCKETS {
            let expected_tag: u64 = if idx <= cur_slot { tag_cur } else { tag_prev };
            let word: u64 = counters[idx].load(Ordering::Relaxed);
            let mask: u64 = u64::from((word >> BUCKET_COUNT_BITS) == expected_tag).wrapping_neg();
            total += (word & BUCKET_COUNT_MASK) & mask;
            idx += 1;
        }
        total
    }

    /// Sums active successes across all stripes and 16 ring buckets at `(generation, cur_epoch)`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Active circuit breaker generation.
    /// - `u64` - Current bucket epoch.
    ///
    /// # Returns
    ///
    /// - `u64` - Total window successes.
    #[inline(always)]
    pub(crate) fn sum_successes_at_epoch(&self, generation: u32, cur_epoch: u64) -> u64 {
        let mut total: u64 = 0;
        for stripe in self.get_successes() {
            total += Self::sum_array_at_epoch(stripe.get_value(), generation, cur_epoch);
        }
        total
    }

    /// Sums active failures across the 16 ring buckets at `(generation, cur_epoch)`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Active circuit breaker generation.
    /// - `u64` - Current bucket epoch.
    ///
    /// # Returns
    ///
    /// - `u64` - Total window failures.
    #[inline(always)]
    pub(crate) fn sum_failures_at_epoch(&self, generation: u32, cur_epoch: u64) -> u64 {
        Self::sum_array_at_epoch(self.get_failures(), generation, cur_epoch)
    }

    /// Sums active `(successes, failures)` across the 16 ring buckets at `(generation, cur_epoch)`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Active circuit breaker generation.
    /// - `u64` - Current bucket epoch.
    ///
    /// # Returns
    ///
    /// - `(u64, u64)` - Tuple of `(window_successes, window_failures)`.
    #[inline(always)]
    pub(crate) fn sum_at_epoch(&self, generation: u32, cur_epoch: u64) -> (u64, u64) {
        (
            self.sum_successes_at_epoch(generation, cur_epoch),
            self.sum_failures_at_epoch(generation, cur_epoch),
        )
    }

    /// Sums active `(successes, failures)` across the 16 ring buckets at `(generation, now_ns)`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Active circuit breaker generation.
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `(u64, u64)` - Tuple of `(window_successes, window_failures)`.
    #[inline(always)]
    pub(crate) fn sum(&self, generation: u32, now_ns: u64) -> (u64, u64) {
        let cur_epoch: u64 = self.epoch_of(now_ns);
        self.sum_at_epoch(generation, cur_epoch)
    }

    /// Handles cold tag transitions or saturation when incrementing a packed bucket word.
    ///
    /// # Arguments
    ///
    /// - `u64` - Current observed atomic word.
    /// - `u64` - Active 10-bit generation tag.
    /// - `u64` - Active 28-bit ring cycle.
    /// - `u64` - Shifted `(gen | cycle) << BUCKET_COUNT_BITS` target tag.
    ///
    /// # Returns
    ///
    /// - `Option<u64>` - Next packed word to CAS, or `None` when saturated or stale.
    #[cold]
    #[inline(never)]
    fn next_word_slow(
        current: u64,
        cur_gen: u64,
        cur_cycle: u64,
        cur_shifted_tag: u64,
    ) -> Option<u64> {
        let stored_tag: u64 = current >> BUCKET_COUNT_BITS;
        let cur_tag: u64 = cur_shifted_tag >> BUCKET_COUNT_BITS;
        if stored_tag == cur_tag {
            return None;
        }
        let stored_gen: u64 = stored_tag >> BUCKET_CYCLE_BITS;
        if stored_gen == cur_gen {
            let stored_cycle: u64 = stored_tag & BUCKET_CYCLE_MASK;
            let cycle_diff: u64 = cur_cycle.wrapping_sub(stored_cycle) & BUCKET_CYCLE_MASK;
            if cycle_diff >= BUCKET_CYCLE_HALF {
                return None;
            }
        } else if current != 0 {
            let gen_diff: u64 = cur_gen.wrapping_sub(stored_gen) & BUCKET_GEN_MASK;
            if gen_diff >= BUCKET_GEN_HALF {
                return None;
            }
        }
        Some(cur_shifted_tag | 1)
    }

    /// Atomically increments a single tagged bucket counter while guarding against stale rewinds.
    ///
    /// # Arguments
    ///
    /// - `&AtomicU64` - Target packed atomic counter.
    /// - `u32` - Active generation.
    /// - `u64` - Wrapped 28-bit ring cycle.
    #[inline(always)]
    pub(crate) fn increment_counter(atomic: &AtomicU64, generation: u32, cur_cycle: u64) {
        let cur_gen: u64 = (generation as u64) & BUCKET_GEN_MASK;
        let cur_shifted_tag: u64 =
            ((cur_gen << BUCKET_CYCLE_BITS) | cur_cycle) << BUCKET_COUNT_BITS;
        let current: u64 = atomic.load(Ordering::Relaxed);
        if (current ^ cur_shifted_tag) < BUCKET_COUNT_SAFE_MAX {
            let _: u64 = atomic.fetch_add(1, Ordering::Relaxed);
            return;
        }
        Self::increment_counter_slow(atomic, current, cur_gen, cur_cycle, cur_shifted_tag);
    }

    /// Cold CAS loop handling tag transitions, wraparound rewinds, and near-saturation counts.
    ///
    /// # Arguments
    ///
    /// - `&AtomicU64` - Target packed atomic counter.
    /// - `u64` - Initially observed atomic word.
    /// - `u64` - Active 10-bit generation tag.
    /// - `u64` - Active 28-bit ring cycle.
    /// - `u64` - Shifted `(gen | cycle) << BUCKET_COUNT_BITS` target tag.
    #[cold]
    #[inline(never)]
    fn increment_counter_slow(
        atomic: &AtomicU64,
        mut current: u64,
        cur_gen: u64,
        cur_cycle: u64,
        cur_shifted_tag: u64,
    ) {
        loop {
            let next: u64 = if (current ^ cur_shifted_tag) < BUCKET_COUNT_MASK {
                current + 1
            } else {
                match Self::next_word_slow(current, cur_gen, cur_cycle, cur_shifted_tag) {
                    Some(word) => word,
                    None => return,
                }
            };
            match atomic.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed)
            {
                Ok(_) => return,
                Err(observed) => {
                    current = observed;
                }
            }
        }
    }
}