nexus-stats 3.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
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
use crate::math::MulAdd;
macro_rules! impl_event_rate_float {
    ($name:ident, $builder:ident, $ty:ty) => {
        /// Smoothed event rate tracker.
        ///
        /// Uses an EMA of inter-arrival times, inverted on query to produce
        /// a rate (events per unit time). The rate adapts smoothly to changes
        /// in event frequency.
        ///
        /// # Use Cases
        /// - Message throughput monitoring
        /// - Order rate tracking
        /// - Adaptive rate limiting input
        #[derive(Debug, Clone)]
        pub struct $name {
            alpha: $ty,
            one_minus_alpha: $ty,
            interval: $ty,
            last_timestamp: $ty,
            count: u64,
            min_samples: u64,
        }

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

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

            /// Updates with an event at the given timestamp.
            ///
            /// If two events share a timestamp, the interval is zero and
            /// `rate()` returns `None` until a non-zero interval is observed.
            ///
            /// # Errors
            ///
            /// Returns `DataError::NotANumber` if the timestamp is NaN, or
            /// `DataError::Infinite` if the timestamp is infinite.
            #[inline]
            pub fn update(&mut self, timestamp: $ty) -> Result<(), crate::DataError> {
                check_finite!(timestamp);
                self.count += 1;

                if self.count == 1 {
                    self.last_timestamp = timestamp;
                    return Ok(());
                }

                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);
                }
                Ok(())
            }

            /// Current smoothed event rate (events per unit time).
            ///
            /// Returns `None` if not primed or if interval is zero.
            #[inline]
            #[must_use]
            pub fn rate(&self) -> Option<$ty> {
                if self.count < self.min_samples || self.interval <= (0.0 as $ty) {
                    Option::None
                } else {
                    Option::Some(1.0 as $ty / self.interval)
                }
            }

            /// Current smoothed inter-event interval, 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 tracker 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;
            }
        }

        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
            }

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

            /// Builds the event rate tracker.
            ///
            /// # Errors
            ///
            /// - Alpha must have been set.
            /// - Alpha must be in (0, 1) exclusive.
            #[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(
                        "EventRate alpha must be in (0, 1)",
                    ));
                }

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

impl_event_rate_float!(EventRateF64, EventRateF64Builder, f64);
impl_event_rate_float!(EventRateF32, EventRateF32Builder, f32);

macro_rules! impl_event_rate_int {
    ($name:ident, $builder:ident, $ty:ty, $acc_ty:ty) => {
        /// Smoothed event rate tracker (integer variant).
        ///
        /// Uses kernel-style fixed-point EMA on inter-arrival ticks.
        /// Rate query returns `unit / smoothed_interval` where unit is
        /// the caller's time unit.
        #[derive(Debug, Clone)]
        pub struct $name {
            acc: $acc_ty,
            shift: u32,
            span: u64,
            last_timestamp: $ty,
            count: u64,
            min_samples: u64,
            initialized: bool,
        }

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

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

            /// Updates with an event at the given tick.
            #[inline]
            pub fn update(&mut self, timestamp: $ty) {
                self.count += 1;

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

                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;
                }
            }

            /// Current smoothed inter-event 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 tracker 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
            }

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

            /// Builds the event rate tracker.
            ///
            /// # Errors
            ///
            /// - Span must have been set and >= 1.
            #[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("EventRate span must be >= 1"));
                }

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

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

impl_event_rate_int!(EventRateI64, EventRateI64Builder, i64, i128);
impl_event_rate_int!(EventRateI32, EventRateI32Builder, i32, i64);

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

    #[test]
    fn constant_rate() {
        let mut er = EventRateF64::builder().alpha(0.3).build().unwrap();

        // Events every 10 units → rate should converge to 0.1
        for i in 0..100 {
            er.update(i as f64 * 10.0).unwrap();
        }

        let rate = er.rate().unwrap();
        assert!((rate - 0.1).abs() < 0.01, "rate should be ~0.1, got {rate}");
    }

    #[test]
    fn burst_increases_rate() {
        let mut er = EventRateF64::builder().alpha(0.5).build().unwrap();

        // Normal rate: every 10 units
        for i in 0..20 {
            er.update(i as f64 * 10.0).unwrap();
        }
        let normal_rate = er.rate().unwrap();

        // Burst: events every 1 unit
        for i in 0..20 {
            er.update(200.0 + i as f64).unwrap();
        }
        let burst_rate = er.rate().unwrap();

        assert!(
            burst_rate > normal_rate,
            "burst rate ({burst_rate}) should exceed normal ({normal_rate})"
        );
    }

    #[test]
    fn priming() {
        let mut er = EventRateF64::builder()
            .alpha(0.3)
            .min_samples(5)
            .build()
            .unwrap();

        for i in 0..4 {
            er.update(i as f64 * 10.0).unwrap();
            assert!(er.rate().is_none());
        }
        er.update(40.0).unwrap();
        assert!(er.rate().is_some());
    }

    #[test]
    fn reset() {
        let mut er = EventRateF64::builder().alpha(0.3).build().unwrap();
        for i in 0..10 {
            er.update(i as f64 * 10.0).unwrap();
        }
        er.reset();
        assert_eq!(er.count(), 0);
        assert!(er.rate().is_none());
    }

    #[test]
    fn f32_basic() {
        let mut er = EventRateF32::builder().alpha(0.3).build().unwrap();
        er.update(0.0).unwrap();
        er.update(10.0).unwrap();
        assert!(er.rate().is_some());
    }

    #[test]
    fn i64_basic() {
        let mut er = EventRateI64::builder().span(7).build().unwrap();
        for i in 0..10 {
            er.update(i * 100);
        }
        let interval = er.interval().unwrap();
        assert!(
            (interval - 100).abs() <= 1,
            "interval should be ~100, got {interval}"
        );
    }

    #[test]
    fn i32_basic() {
        let mut er = EventRateI32::builder().span(3).build().unwrap();
        er.update(0);
        er.update(50);
        assert!(er.interval().is_some());
    }

    #[test]
    fn zero_interval_returns_none() {
        let mut er = EventRateF64::builder().alpha(0.3).build().unwrap();
        er.update(100.0).unwrap();
        er.update(100.0).unwrap(); // same timestamp → interval = 0
        // rate() should return None (division by zero guard)
        assert!(
            er.rate().is_none(),
            "rate should be None with zero interval"
        );
    }

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

    #[test]
    fn rejects_nan_and_inf() {
        let mut er = EventRateF64::builder().alpha(0.3).build().unwrap();
        assert!(matches!(
            er.update(f64::NAN),
            Err(crate::DataError::NotANumber)
        ));
        assert!(matches!(
            er.update(f64::INFINITY),
            Err(crate::DataError::Infinite)
        ));

        let mut er32 = EventRateF32::builder().alpha(0.3).build().unwrap();
        assert!(matches!(
            er32.update(f32::NAN),
            Err(crate::DataError::NotANumber)
        ));
    }
}

// =============================================================================
// EventRateInstant — Instant-based event rate tracker
// =============================================================================

#[cfg(feature = "std")]
mod instant_event_rate {
    use std::time::{Duration, Instant};

    /// Smoothed event rate tracker using `Instant` timestamps.
    ///
    /// Wraps EMA-of-intervals math with `Instant` → f64 seconds conversion.
    /// Rate is in events per second.
    ///
    /// # Use Cases
    /// - Application-internal message throughput monitoring
    /// - Handler invocation rate tracking
    #[derive(Debug, Clone)]
    pub struct EventRateInstant {
        alpha: f64,
        one_minus_alpha: f64,
        interval: f64, // seconds
        last_timestamp: Option<Instant>,
        count: u64,
        min_samples: u64,
    }

    /// Builder for [`EventRateInstant`].
    #[derive(Debug, Clone)]
    pub struct EventRateInstantBuilder {
        alpha: Option<f64>,
        min_samples: u64,
    }

    impl EventRateInstant {
        /// Creates a builder.
        #[inline]
        #[must_use]
        pub fn builder() -> EventRateInstantBuilder {
            EventRateInstantBuilder {
                alpha: None,
                min_samples: 2,
            }
        }

        /// Updates with an event at the given time.
        #[inline]
        pub fn update(&mut self, now: Instant) {
            self.count += 1;

            if let Some(last) = self.last_timestamp {
                let dt = now.saturating_duration_since(last).as_secs_f64();
                if self.count == 2 {
                    self.interval = dt;
                } else {
                    self.interval = self.alpha.mul_add(dt, self.one_minus_alpha * self.interval);
                }
            }
            self.last_timestamp = Some(now);
        }

        /// Current smoothed event rate (events per second).
        ///
        /// Returns `None` if not primed or if interval is zero.
        #[inline]
        #[must_use]
        pub fn rate(&self) -> Option<f64> {
            if self.count < self.min_samples || self.interval <= 0.0 {
                None
            } else {
                Some(1.0 / self.interval)
            }
        }

        /// Current smoothed inter-event interval as Duration.
        #[inline]
        #[must_use]
        pub fn interval(&self) -> Option<Duration> {
            if self.count >= 2 && self.interval > 0.0 {
                Some(Duration::from_secs_f64(self.interval))
            } else {
                None
            }
        }

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

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

        /// Resets. `now` becomes the new time reference.
        #[inline]
        pub fn reset(&mut self, now: Instant) {
            self.interval = 0.0;
            self.last_timestamp = Some(now);
            self.count = 0;
        }
    }

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

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

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

        /// Builds the event rate tracker.
        ///
        /// # Errors
        ///
        /// Alpha must be in (0, 1) exclusive.
        #[inline]
        pub fn build(self) -> Result<EventRateInstant, crate::ConfigError> {
            let alpha = self.alpha.ok_or(crate::ConfigError::Missing("alpha"))?;
            if !(alpha > 0.0 && alpha < 1.0) {
                return Err(crate::ConfigError::Invalid(
                    "EventRateInstant alpha must be in (0, 1)",
                ));
            }

            Ok(EventRateInstant {
                alpha,
                one_minus_alpha: 1.0 - alpha,
                interval: 0.0,
                last_timestamp: None,
                count: 0,
                min_samples: self.min_samples,
            })
        }
    }

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

        #[test]
        fn basic_rate() {
            let base = Instant::now();
            let mut er = EventRateInstant::builder().span(10).build().unwrap();
            er.update(base);
            er.update(base + Duration::from_secs(1));
            let rate = er.rate().unwrap();
            assert!((rate - 1.0).abs() < 0.1, "expected ~1.0 eps, got {rate}");
        }

        #[test]
        fn interval_as_duration() {
            let base = Instant::now();
            let mut er = EventRateInstant::builder().span(10).build().unwrap();
            er.update(base);
            er.update(base + Duration::from_millis(500));
            let interval = er.interval().unwrap();
            let ms = interval.as_millis();
            assert!((450..=550).contains(&ms), "expected ~500ms, got {ms}ms");
        }

        #[test]
        fn not_primed_before_min_samples() {
            let base = Instant::now();
            let mut er = EventRateInstant::builder()
                .span(10)
                .min_samples(5)
                .build()
                .unwrap();
            er.update(base);
            er.update(base + Duration::from_secs(1));
            assert!(!er.is_primed());
            assert!(er.rate().is_none());
        }

        #[test]
        fn reset_clears() {
            let base = Instant::now();
            let mut er = EventRateInstant::builder().span(10).build().unwrap();
            er.update(base);
            er.update(base + Duration::from_secs(1));
            er.reset(base + Duration::from_secs(2));
            assert_eq!(er.count(), 0);
            assert!(er.rate().is_none());
        }
    }
}

#[cfg(feature = "std")]
pub use instant_event_rate::{EventRateInstant, EventRateInstantBuilder};