nexus-stats 2.1.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
use crate::Condition;
use crate::windowed::{
    WindowedMinF32Raw, WindowedMinF64Raw, WindowedMinI32Raw, WindowedMinI64Raw, WindowedMinI128Raw,
};

// =========================================================================
// Raw (u64 timestamp) variants — no_std compatible
// =========================================================================

macro_rules! impl_codel_raw {
    ($name:ident, $builder:ident, $ty:ty, $windowed_min_raw:ty) => {
        /// CoDel — Controlled Delay queue monitor using raw `u64` timestamps.
        ///
        /// Same algorithm as the `Instant`-based variant but operates on
        /// caller-supplied `u64` timestamps directly. No `std` dependency.
        #[derive(Debug, Clone)]
        pub struct $name {
            windowed_min: $windowed_min_raw,
            target: $ty,
            min_samples: u64,
        }

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

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

            /// Feeds a sojourn time at the given timestamp.
            ///
            /// Returns `Some(Condition)` once primed, `None` before.
            #[inline]
            #[must_use]
            pub fn update(&mut self, timestamp: u64, sojourn: $ty) -> Option<Condition> {
                let min = self.windowed_min.update(timestamp, sojourn);

                if self.windowed_min.count() < self.min_samples {
                    return Option::None;
                }

                if min > self.target {
                    Option::Some(Condition::Degraded)
                } else {
                    Option::Some(Condition::Normal)
                }
            }

            /// Convenience for `i64` timestamps (e.g., wire protocol epoch nanos).
            ///
            /// Timestamps must be non-negative. Negative values wrap to large
            /// `u64` values and will produce incorrect window expiration.
            #[inline]
            #[must_use]
            pub fn update_i64(&mut self, timestamp: i64, sojourn: $ty) -> Option<Condition> {
                debug_assert!(timestamp >= 0, "negative timestamp: {timestamp}");
                self.update(timestamp as u64, sojourn)
            }

            /// Current windowed minimum sojourn time, or `None` if empty.
            #[inline]
            #[must_use]
            pub fn min_sojourn(&self) -> Option<$ty> {
                self.windowed_min.min()
            }

            /// Whether the queue is currently elevated.
            #[inline]
            #[must_use]
            pub fn is_elevated(&self) -> bool {
                if let Some(min) = self.windowed_min.min() {
                    min > self.target
                } else {
                    false
                }
            }

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

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

            /// Resets to empty state. Parameters unchanged.
            #[inline]
            pub fn reset(&mut self) {
                self.windowed_min.reset();
            }
        }

        impl $builder {
            /// Target sojourn time. Elevated when minimum exceeds this.
            #[inline]
            #[must_use]
            pub fn target(mut self, target: $ty) -> Self {
                self.target = Option::Some(target);
                self
            }

            /// Observation window in raw units (same as timestamps).
            #[inline]
            #[must_use]
            pub fn window(mut self, window: u64) -> Self {
                self.window = Option::Some(window);
                self
            }

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

            /// Builds the CoDel monitor.
            ///
            /// # Errors
            ///
            /// - Target must have been set.
            /// - Window must have been set and be positive.
            #[inline]
            pub fn build(self) -> Result<$name, crate::ConfigError> {
                let target = self.target.ok_or(crate::ConfigError::Missing("target"))?;
                let window = self.window.ok_or(crate::ConfigError::Missing("window"))?;
                if window == 0 {
                    return Err(crate::ConfigError::Invalid("CoDel window must be positive"));
                }

                Ok($name {
                    windowed_min: <$windowed_min_raw>::new(window)?,
                    target,
                    min_samples: self.min_samples,
                })
            }
        }
    };
}

impl_codel_raw!(CoDelI64Raw, CoDelI64RawBuilder, i64, WindowedMinI64Raw);
impl_codel_raw!(CoDelI32Raw, CoDelI32RawBuilder, i32, WindowedMinI32Raw);
impl_codel_raw!(CoDelI128Raw, CoDelI128RawBuilder, i128, WindowedMinI128Raw);
impl_codel_raw!(CoDelF64Raw, CoDelF64RawBuilder, f64, WindowedMinF64Raw);
impl_codel_raw!(CoDelF32Raw, CoDelF32RawBuilder, f32, WindowedMinF32Raw);

// =========================================================================
// Instant-based variants — requires std
// =========================================================================

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

#[cfg(feature = "std")]
use crate::windowed::{
    WindowedMinF32, WindowedMinF64, WindowedMinI32, WindowedMinI64, WindowedMinI128,
};

#[cfg(feature = "std")]
macro_rules! impl_codel {
    ($name:ident, $builder:ident, $ty:ty, $windowed_min:ty) => {
        /// CoDel — Controlled Delay queue monitor (Nichols & Jacobson, 2012).
        ///
        /// Composes a windowed minimum of sojourn times with a threshold.
        /// Reports `Degraded` when even the minimum sojourn time in the
        /// observation window exceeds the target — indicating a standing
        /// queue rather than a transient burst.
        ///
        /// # Use Cases
        /// - Internal queue health monitoring
        /// - Backpressure detection
        /// - "Is this queue draining or building up?"
        #[derive(Debug, Clone)]
        pub struct $name {
            windowed_min: $windowed_min,
            target: $ty,
            min_samples: u64,
        }

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

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

            /// Feeds a sojourn time at the given timestamp.
            ///
            /// Returns `Some(Condition)` once primed, `None` before.
            #[inline]
            #[must_use]
            pub fn update(&mut self, now: Instant, sojourn: $ty) -> Option<Condition> {
                let min = self.windowed_min.update(now, sojourn);

                if self.windowed_min.count() < self.min_samples {
                    return Option::None;
                }

                if min > self.target {
                    Option::Some(Condition::Degraded)
                } else {
                    Option::Some(Condition::Normal)
                }
            }

            /// Current windowed minimum sojourn time, or `None` if empty.
            #[inline]
            #[must_use]
            pub fn min_sojourn(&self) -> Option<$ty> {
                self.windowed_min.min()
            }

            /// Whether the queue is currently elevated.
            #[inline]
            #[must_use]
            pub fn is_elevated(&self) -> bool {
                if let Some(min) = self.windowed_min.min() {
                    min > self.target
                } else {
                    false
                }
            }

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

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

            /// Resets to empty state with `now` as the new time base.
            /// Parameters unchanged.
            #[inline]
            pub fn reset(&mut self, now: Instant) {
                self.windowed_min.reset(now);
            }
        }

        impl $builder {
            /// Target sojourn time. Elevated when minimum exceeds this.
            #[inline]
            #[must_use]
            pub fn target(mut self, target: $ty) -> Self {
                self.target = Option::Some(target);
                self
            }

            /// Observation window as a `Duration`.
            #[inline]
            #[must_use]
            pub fn window(mut self, window: Duration) -> Self {
                self.window = Option::Some(window);
                self
            }

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

            /// Base instant for timestamp conversion. Default: `Instant::now()`.
            #[inline]
            #[must_use]
            pub fn base(mut self, base: Instant) -> Self {
                self.base = Option::Some(base);
                self
            }

            /// Builds the CoDel monitor.
            ///
            /// # Errors
            ///
            /// - Target must have been set.
            /// - Window must have been set and be positive.
            #[inline]
            pub fn build(self) -> Result<$name, crate::ConfigError> {
                let target = self.target.ok_or(crate::ConfigError::Missing("target"))?;
                let window = self.window.ok_or(crate::ConfigError::Missing("window"))?;
                if window.is_zero() {
                    return Err(crate::ConfigError::Invalid("CoDel window must be positive"));
                }

                let base = self.base.unwrap_or_else(Instant::now);
                Ok($name {
                    windowed_min: <$windowed_min>::with_base(window, base)?,
                    target,
                    min_samples: self.min_samples,
                })
            }
        }
    };
}

#[cfg(feature = "std")]
impl_codel!(CoDelI64, CoDelI64Builder, i64, WindowedMinI64);
#[cfg(feature = "std")]
impl_codel!(CoDelI32, CoDelI32Builder, i32, WindowedMinI32);
#[cfg(feature = "std")]
impl_codel!(CoDelI128, CoDelI128Builder, i128, WindowedMinI128);
#[cfg(feature = "std")]
impl_codel!(CoDelF64, CoDelF64Builder, f64, WindowedMinF64);
#[cfg(feature = "std")]
impl_codel!(CoDelF32, CoDelF32Builder, f32, WindowedMinF32);

#[cfg(test)]
mod raw_tests {
    use super::*;
    use crate::Condition;

    #[test]
    fn raw_codel_normal() {
        let mut cd = CoDelI64Raw::builder()
            .target(100)
            .window(1000)
            .build()
            .unwrap();
        assert_eq!(cd.update(0, 50), Some(Condition::Normal));
    }

    #[test]
    fn raw_codel_degraded() {
        let mut cd = CoDelI64Raw::builder()
            .target(50)
            .window(1000)
            .build()
            .unwrap();
        for t in 0..10 {
            let _ = cd.update(t * 100, 200);
        }
        assert!(cd.is_elevated());
    }

    #[test]
    fn raw_codel_f64() {
        let mut cd = CoDelF64Raw::builder()
            .target(0.5)
            .window(1000)
            .build()
            .unwrap();
        assert_eq!(cd.update(0, 0.1), Some(Condition::Normal));
    }
}

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

    fn t(base: Instant, ns: u64) -> Instant {
        base + Duration::from_nanos(ns)
    }

    #[test]
    fn healthy_queue() {
        let base = Instant::now();
        let mut qd = CoDelI64::builder()
            .target(100)
            .window(Duration::from_nanos(1000))
            .base(base)
            .build()
            .unwrap();

        // All sojourn times below target
        for ts in 0..100 {
            let result = qd.update(t(base, ts * 10), 50);
            assert_eq!(result, Some(Condition::Normal));
        }
        assert!(!qd.is_elevated());
    }

    #[test]
    fn elevated_detection() {
        let base = Instant::now();
        let mut qd = CoDelI64::builder()
            .target(100)
            .window(Duration::from_nanos(1000))
            .base(base)
            .build()
            .unwrap();

        // Sojourn times above target
        for ts in 0..100 {
            let _ = qd.update(t(base, ts * 10), 200);
        }
        assert!(qd.is_elevated());
    }

    #[test]
    fn recovery_after_drain() {
        let base = Instant::now();
        let mut qd = CoDelI64::builder()
            .target(100)
            .window(Duration::from_nanos(10))
            .base(base)
            .build()
            .unwrap();

        // Build up
        for ts in 0..10 {
            let _ = qd.update(t(base, ts), 200);
        }
        assert!(qd.is_elevated());

        // Drain — low sojourn times should eventually make min drop below target
        for ts in 10..30 {
            let _ = qd.update(t(base, ts), 10);
        }
        assert!(!qd.is_elevated(), "should recover after drain");
    }

    #[test]
    fn burst_vs_standing_queue() {
        let base = Instant::now();
        let mut qd = CoDelI64::builder()
            .target(100)
            .window(Duration::from_nanos(10))
            .base(base)
            .build()
            .unwrap();

        // Single burst sample among low values — min stays low, not elevated
        for ts in 0..10 {
            let _ = qd.update(t(base, ts), 10);
        }
        let _ = qd.update(t(base, 10), 500); // single burst
        assert!(
            !qd.is_elevated(),
            "single burst should not trigger — min is still low"
        );
    }

    #[test]
    fn priming() {
        let base = Instant::now();
        let mut qd = CoDelI64::builder()
            .target(100)
            .window(Duration::from_nanos(1000))
            .min_samples(5)
            .base(base)
            .build()
            .unwrap();

        for ts in 0..4 {
            assert_eq!(qd.update(t(base, ts), 200), None);
        }
        assert!(qd.update(t(base, 4), 200).is_some());
    }

    #[test]
    fn reset_clears() {
        let base = Instant::now();
        let mut qd = CoDelI64::builder()
            .target(100)
            .window(Duration::from_nanos(1000))
            .base(base)
            .build()
            .unwrap();

        for ts in 0..10 {
            let _ = qd.update(t(base, ts), 200);
        }
        qd.reset(base);
        assert_eq!(qd.count(), 0);
        assert!(qd.min_sojourn().is_none());
    }

    #[test]
    fn i32_basic() {
        let base = Instant::now();
        let mut qd = CoDelI32::builder()
            .target(50)
            .window(Duration::from_nanos(100))
            .base(base)
            .build()
            .unwrap();

        let result = qd.update(t(base, 0), 30);
        assert_eq!(result, Some(Condition::Normal));
    }

    #[test]
    fn errors_without_target() {
        let base = Instant::now();
        let result = CoDelI64::builder()
            .window(Duration::from_nanos(100))
            .base(base)
            .build();
        assert!(matches!(result, Err(crate::ConfigError::Missing("target"))));
    }

    #[test]
    fn errors_without_window() {
        let base = Instant::now();
        let result = CoDelI64::builder().target(100).base(base).build();
        assert!(matches!(result, Err(crate::ConfigError::Missing("window"))));
    }

    #[test]
    fn i128_basic() {
        let base = Instant::now();
        let mut qd = CoDelI128::builder()
            .target(50)
            .window(Duration::from_nanos(100))
            .base(base)
            .build()
            .unwrap();

        let result = qd.update(t(base, 0), 30);
        assert_eq!(result, Some(Condition::Normal));
    }
}