nexus-stats 2.0.0

Fixed-memory, zero-allocation streaming statistics for real-time systems
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
use crate::math::MulAdd;
macro_rules! impl_liveness_float {
    ($name:ident, $builder:ident, $ty:ty) => {
        /// Liveness detector — EMA of inter-arrival times with deadline threshold.
        ///
        /// Detects when a source goes quiet by tracking the smoothed interval
        /// between events and comparing against a deadline.
        ///
        /// # Use Cases
        /// - Stale quote detection
        /// - Heartbeat monitoring
        /// - Feed health checking
        #[derive(Debug, Clone)]
        pub struct $name {
            alpha: $ty,
            one_minus_alpha: $ty,
            interval: $ty,
            last_timestamp: $ty,
            deadline_multiple: Option<$ty>,
            deadline_absolute: Option<$ty>,
            count: u64,
            min_samples: u64,
        }

        /// Builder for [`
        #[doc = stringify!($name)]
        /// `].
        #[derive(Debug, Clone)]
        pub struct $builder {
            alpha: Option<$ty>,
            deadline_multiple: Option<$ty>,
            deadline_absolute: Option<$ty>,
            min_samples: u64,
        }

        impl $name {
            /// Creates a builder.
            #[inline]
            #[must_use]
            pub fn builder() -> $builder {
                $builder {
                    alpha: Option::None,
                    deadline_multiple: Option::None,
                    deadline_absolute: Option::None,
                    min_samples: 2,
                }
            }

            /// Records an event at the given timestamp. Returns `true` if alive.
            ///
            /// The first event only records the timestamp. The second event
            /// computes the first interval. Returns `true` until primed, then
            /// checks against the deadline.
            #[inline]
            #[must_use]
            pub fn record(&mut self, timestamp: $ty) -> bool {
                self.count += 1;

                if self.count == 1 {
                    self.last_timestamp = timestamp;
                    return true;
                }

                let dt = timestamp - self.last_timestamp;
                self.last_timestamp = timestamp;

                if self.count == 2 {
                    self.interval = dt;
                } else {
                    self.interval = self.alpha.fma(dt, self.one_minus_alpha * self.interval);
                }

                if self.count < self.min_samples {
                    return true;
                }

                self.is_alive_at_interval(dt)
            }

            /// Checks liveness at the given timestamp without recording an event.
            ///
            /// Returns `true` if the time since the last event is within the deadline.
            /// Returns `true` if not yet primed.
            #[inline]
            #[must_use]
            pub fn check(&self, now: $ty) -> bool {
                if self.count < self.min_samples {
                    return true;
                }

                let dt = now - self.last_timestamp;
                self.is_alive_at_interval(dt)
            }

            #[inline]
            fn is_alive_at_interval(&self, dt: $ty) -> bool {
                if let Some(multiple) = self.deadline_multiple {
                    return dt <= self.interval * multiple;
                }
                if let Some(absolute) = self.deadline_absolute {
                    return dt <= absolute;
                }
                true
            }

            /// Current smoothed inter-arrival time, or `None` if < 2 events.
            #[inline]
            #[must_use]
            pub fn interval(&self) -> Option<$ty> {
                if self.count >= 2 {
                    Option::Some(self.interval)
                } else {
                    Option::None
                }
            }

            /// Number of events recorded.
            #[inline]
            #[must_use]
            pub fn count(&self) -> u64 {
                self.count
            }

            /// Whether the detector has reached `min_samples`.
            #[inline]
            #[must_use]
            pub fn is_primed(&self) -> bool {
                self.count >= self.min_samples
            }

            /// Resets to uninitialized state.
            #[inline]
            pub fn reset(&mut self) {
                self.interval = 0.0 as $ty;
                self.last_timestamp = 0.0 as $ty;
                self.count = 0;
            }

            /// Switches to a deadline-multiple threshold, clearing any absolute deadline.
            #[inline]
            pub fn reconfigure_deadline_multiple(&mut self, n: $ty) {
                self.deadline_multiple = Option::Some(n);
                self.deadline_absolute = Option::None;
            }

            /// Switches to an absolute deadline threshold, clearing any multiple deadline.
            #[inline]
            pub fn reconfigure_deadline_absolute(&mut self, t: $ty) {
                self.deadline_absolute = Option::Some(t);
                self.deadline_multiple = Option::None;
            }
        }

        impl $builder {
            /// Direct smoothing factor for interval EMA.
            #[inline]
            #[must_use]
            pub fn alpha(mut self, alpha: $ty) -> Self {
                self.alpha = Option::Some(alpha);
                self
            }

            /// Halflife for interval smoothing.
            #[inline]
            #[must_use]
            #[cfg(any(feature = "std", feature = "libm"))]
            pub fn halflife(mut self, halflife: $ty) -> Self {
                let ln2 = core::f64::consts::LN_2 as $ty;
                let alpha = 1.0 as $ty - crate::math::exp((-ln2 / halflife) as f64) as $ty;
                self.alpha = Option::Some(alpha);
                self
            }

            /// Span for interval smoothing.
            #[inline]
            #[must_use]
            pub fn span(mut self, n: u64) -> Self {
                let alpha = 2.0 as $ty / (n as $ty + 1.0 as $ty);
                self.alpha = Option::Some(alpha);
                self
            }

            /// Alert when interval exceeds `n * smoothed_interval`.
            ///
            /// Typical values: 2.0-5.0.
            #[inline]
            #[must_use]
            pub fn deadline_multiple(mut self, n: $ty) -> Self {
                self.deadline_multiple = Option::Some(n);
                self
            }

            /// Alert when interval exceeds a fixed deadline.
            #[inline]
            #[must_use]
            pub fn deadline_absolute(mut self, t: $ty) -> Self {
                self.deadline_absolute = Option::Some(t);
                self
            }

            /// Minimum events before liveness checking activates. Default: 2.
            #[inline]
            #[must_use]
            pub fn min_samples(mut self, min: u64) -> Self {
                self.min_samples = min;
                self
            }

            /// Builds the liveness detector.
            ///
            /// # Errors
            ///
            /// - Alpha must have been set.
            /// - Alpha must be in (0, 1) exclusive.
            /// - At least one deadline (multiple or absolute) must be set.
            #[inline]
            pub fn build(self) -> Result<$name, crate::ConfigError> {
                let alpha = self.alpha.ok_or(crate::ConfigError::Missing("alpha"))?;
                if !(alpha > 0.0 as $ty && alpha < 1.0 as $ty) {
                    return Err(crate::ConfigError::Invalid("Liveness alpha must be in (0, 1)"));
                }
                if self.deadline_multiple.is_none() && self.deadline_absolute.is_none() {
                    return Err(crate::ConfigError::Invalid("Liveness requires a deadline (use .deadline_multiple() or .deadline_absolute())"));
                }

                Ok($name {
                    alpha,
                    one_minus_alpha: 1.0 as $ty - alpha,
                    interval: 0.0 as $ty,
                    last_timestamp: 0.0 as $ty,
                    deadline_multiple: self.deadline_multiple,
                    deadline_absolute: self.deadline_absolute,
                    count: 0,
                    min_samples: self.min_samples,
                })
            }
        }
    };
}

impl_liveness_float!(LivenessF64, LivenessF64Builder, f64);
impl_liveness_float!(LivenessF32, LivenessF32Builder, f32);

macro_rules! impl_liveness_int {
    ($name:ident, $builder:ident, $ty:ty, $acc_ty:ty) => {
        /// Liveness detector (integer variant) — fixed-point EMA of inter-arrival ticks.
        ///
        /// Uses kernel-style bit-shift arithmetic for the interval smoothing.
        /// Timestamps are integer ticks.
        #[derive(Debug, Clone)]
        pub struct $name {
            acc: $acc_ty,
            shift: u32,
            span: u64,
            last_timestamp: $ty,
            deadline_multiple: Option<u64>,
            deadline_absolute: Option<$ty>,
            count: u64,
            min_samples: u64,
            initialized: bool,
        }

        /// Builder for [`
        #[doc = stringify!($name)]
        /// `].
        #[derive(Debug, Clone)]
        pub struct $builder {
            span: Option<u64>,
            deadline_multiple: Option<u64>,
            deadline_absolute: Option<$ty>,
            min_samples: u64,
        }

        impl $name {
            /// Creates a builder.
            #[inline]
            #[must_use]
            pub fn builder() -> $builder {
                $builder {
                    span: Option::None,
                    deadline_multiple: Option::None,
                    deadline_absolute: Option::None,
                    min_samples: 2,
                }
            }

            /// Records an event at the given tick. Returns `true` if alive.
            #[inline]
            #[must_use]
            pub fn record(&mut self, timestamp: $ty) -> bool {
                self.count += 1;

                if self.count == 1 {
                    self.last_timestamp = timestamp;
                    return true;
                }

                let dt = timestamp - self.last_timestamp;
                self.last_timestamp = timestamp;

                if !self.initialized {
                    self.acc = (dt as $acc_ty) << self.shift;
                    self.initialized = true;
                } else {
                    let dt_shifted = (dt as $acc_ty) << self.shift;
                    self.acc += (dt_shifted - self.acc) >> self.shift;
                }

                if self.count < self.min_samples {
                    return true;
                }

                let smoothed = (self.acc >> self.shift) as $ty;
                self.is_alive_with(dt, smoothed)
            }

            /// Checks liveness at the given tick without recording.
            #[inline]
            #[must_use]
            pub fn check(&self, now: $ty) -> bool {
                if self.count < self.min_samples || !self.initialized {
                    return true;
                }

                let dt = now - self.last_timestamp;
                let smoothed = (self.acc >> self.shift) as $ty;
                self.is_alive_with(dt, smoothed)
            }

            #[inline]
            fn is_alive_with(&self, dt: $ty, smoothed: $ty) -> bool {
                if let Some(multiple) = self.deadline_multiple {
                    return dt <= smoothed * (multiple as $ty);
                }
                if let Some(absolute) = self.deadline_absolute {
                    return dt <= absolute;
                }
                true
            }

            /// Current smoothed inter-arrival interval, or `None` if < 2 events.
            #[inline]
            #[must_use]
            pub fn interval(&self) -> Option<$ty> {
                if self.count >= 2 && self.initialized {
                    Option::Some((self.acc >> self.shift) as $ty)
                } else {
                    Option::None
                }
            }

            /// Effective span after rounding.
            #[inline]
            #[must_use]
            pub fn effective_span(&self) -> u64 {
                self.span
            }

            /// Number of events recorded.
            #[inline]
            #[must_use]
            pub fn count(&self) -> u64 {
                self.count
            }

            /// Whether the detector has reached `min_samples`.
            #[inline]
            #[must_use]
            pub fn is_primed(&self) -> bool {
                self.count >= self.min_samples
            }

            /// Resets to uninitialized state.
            #[inline]
            pub fn reset(&mut self) {
                self.acc = 0;
                self.last_timestamp = 0;
                self.count = 0;
                self.initialized = false;
            }
        }

        impl $builder {
            /// Smoothing span. Rounded up to next `2^k - 1`.
            #[inline]
            #[must_use]
            pub fn span(mut self, n: u64) -> Self {
                self.span = Option::Some(n);
                self
            }

            /// Alert when interval exceeds `n * smoothed_interval`.
            #[inline]
            #[must_use]
            pub fn deadline_multiple(mut self, n: u64) -> Self {
                self.deadline_multiple = Option::Some(n);
                self
            }

            /// Alert when interval exceeds a fixed deadline (in ticks).
            #[inline]
            #[must_use]
            pub fn deadline_absolute(mut self, t: $ty) -> Self {
                self.deadline_absolute = Option::Some(t);
                self
            }

            /// Minimum events before liveness checking activates. Default: 2.
            #[inline]
            #[must_use]
            pub fn min_samples(mut self, min: u64) -> Self {
                self.min_samples = min;
                self
            }

            /// Builds the liveness detector.
            ///
            /// # Errors
            ///
            /// - Span must have been set and >= 1.
            /// - At least one deadline must be set.
            #[inline]
            pub fn build(self) -> Result<$name, crate::ConfigError> {
                let requested = self.span.ok_or(crate::ConfigError::Missing("span"))?;
                if requested < 1 {
                    return Err(crate::ConfigError::Invalid("Liveness span must be >= 1"));
                }
                if self.deadline_multiple.is_none() && self.deadline_absolute.is_none() {
                    return Err(crate::ConfigError::Invalid("Liveness requires a deadline"));
                }

                let effective = crate::ema::next_power_of_two_minus_one(requested);
                let shift = crate::ema::log2_of_span_plus_one(effective);

                Ok($name {
                    acc: 0,
                    shift,
                    span: effective,
                    last_timestamp: 0,
                    deadline_multiple: self.deadline_multiple,
                    deadline_absolute: self.deadline_absolute,
                    count: 0,
                    min_samples: self.min_samples,
                    initialized: false,
                })
            }
        }
    };
}

impl_liveness_int!(LivenessI64, LivenessI64Builder, i64, i128);
impl_liveness_int!(LivenessI32, LivenessI32Builder, i32, i64);

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

    #[test]
    fn alive_while_events_arrive() {
        let mut lv = LivenessF64::builder()
            .alpha(0.3)
            .deadline_multiple(3.0)
            .build()
            .unwrap();

        // Regular events every 10 units
        for i in 0..20 {
            assert!(lv.record(i as f64 * 10.0), "should be alive at event {i}");
        }
    }

    #[test]
    fn dead_after_silence() {
        let mut lv = LivenessF64::builder()
            .alpha(0.3)
            .deadline_multiple(3.0)
            .build()
            .unwrap();

        // Regular events every 10 units
        for i in 0..10 {
            let _ = lv.record(i as f64 * 10.0);
        }

        // Check after long silence — should be dead
        // Smoothed interval ≈ 10, deadline = 3 * 10 = 30, silence = 100
        assert!(!lv.check(190.0), "should be dead after long silence");
    }

    #[test]
    fn recovery_after_resume() {
        let mut lv = LivenessF64::builder()
            .alpha(0.3)
            .deadline_multiple(3.0)
            .build()
            .unwrap();

        for i in 0..10 {
            let _ = lv.record(i as f64 * 10.0);
        }

        // Dead check
        assert!(!lv.check(200.0));

        // Resume events — should recover
        assert!(lv.record(200.0)); // records, interval updates
        assert!(lv.record(210.0));
    }

    #[test]
    fn absolute_deadline() {
        let mut lv = LivenessF64::builder()
            .alpha(0.3)
            .deadline_absolute(50.0)
            .build()
            .unwrap();

        let _ = lv.record(0.0);
        let _ = lv.record(10.0);

        // Within deadline
        assert!(lv.check(55.0));
        // Exceeds deadline
        assert!(!lv.check(65.0));
    }

    #[test]
    fn not_primed_always_alive() {
        let mut lv = LivenessF64::builder()
            .alpha(0.3)
            .deadline_multiple(3.0)
            .min_samples(5)
            .build()
            .unwrap();

        // Even with huge gaps, returns true before primed
        assert!(lv.record(0.0));
        assert!(lv.record(1000.0));
        assert!(!lv.is_primed());
    }

    #[test]
    fn i64_basic() {
        let mut lv = LivenessI64::builder()
            .span(7)
            .deadline_multiple(3)
            .build()
            .unwrap();

        for i in 0..10 {
            assert!(lv.record(i * 100));
        }

        // Long silence
        assert!(!lv.check(2000));
    }

    #[test]
    fn i32_basic() {
        let mut lv = LivenessI32::builder()
            .span(3)
            .deadline_absolute(500)
            .build()
            .unwrap();

        let _ = lv.record(0);
        let _ = lv.record(100);
        assert!(lv.check(400));
        assert!(!lv.check(700));
    }

    #[test]
    fn reset_clears_state() {
        let mut lv = LivenessF64::builder()
            .alpha(0.3)
            .deadline_multiple(3.0)
            .build()
            .unwrap();

        for i in 0..10 {
            let _ = lv.record(i as f64 * 10.0);
        }

        lv.reset();
        assert_eq!(lv.count(), 0);
        assert!(lv.interval().is_none());
    }

    #[test]
    fn reconfigure_deadline_multiple() {
        let mut lv = LivenessF64::builder()
            .alpha(0.3)
            .deadline_absolute(50.0)
            .build()
            .unwrap();

        let _ = lv.record(0.0);
        let _ = lv.record(10.0);

        // With absolute 50, check at 55 is alive
        assert!(lv.check(55.0));

        // Switch to multiple=2 — smoothed interval ~10, deadline=20
        lv.reconfigure_deadline_multiple(2.0);
        // 55 - 10 = 45 > 20, should be dead
        assert!(!lv.check(55.0));
    }

    #[test]
    fn reconfigure_deadline_absolute() {
        let mut lv = LivenessF64::builder()
            .alpha(0.3)
            .deadline_multiple(3.0)
            .build()
            .unwrap();

        for i in 0..10 {
            let _ = lv.record(i as f64 * 10.0);
        }

        // Switch to absolute deadline
        lv.reconfigure_deadline_absolute(5.0);
        // Last event at 90, check at 100 => dt=10 > 5
        assert!(!lv.check(100.0));
    }

    #[test]
    fn errors_without_alpha() {
        let result = LivenessF64::builder().deadline_multiple(3.0).build();
        assert!(matches!(result, Err(crate::ConfigError::Missing("alpha"))));
    }

    #[test]
    fn errors_without_deadline() {
        let result = LivenessF64::builder().alpha(0.3).build();
        assert!(matches!(result, Err(crate::ConfigError::Invalid(_))));
    }
}