nexus-stats-core 1.1.0

Core types and utilities shared across nexus-stats subcrates
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
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,
                }
            }

            /// Updates with 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.
            ///
            /// # 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<bool, crate::DataError> {
                check_finite!(timestamp);
                self.count += 1;

                if self.count == 1 {
                    self.last_timestamp = timestamp;
                    return Ok(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 Ok(true);
                }

                Ok(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,
                }
            }

            /// Updates with an event at the given tick. Returns `true` if alive.
            #[inline]
            #[must_use]
            pub fn update(&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::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,
                    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.update(i as f64 * 10.0).unwrap(),
                "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.update(i as f64 * 10.0).unwrap();
        }

        // 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.update(i as f64 * 10.0).unwrap();
        }

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

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

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

        let _ = lv.update(0.0).unwrap();
        let _ = lv.update(10.0).unwrap();

        // 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.update(0.0).unwrap());
        assert!(lv.update(1000.0).unwrap());
        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.update(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.update(0);
        let _ = lv.update(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.update(i as f64 * 10.0).unwrap();
        }

        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.update(0.0).unwrap();
        let _ = lv.update(10.0).unwrap();

        // 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.update(i as f64 * 10.0).unwrap();
        }

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

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

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

// =============================================================================
// LivenessInstant — Instant-based liveness detector
// =============================================================================

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

    /// Liveness detector using `Instant` timestamps.
    ///
    /// EMA of inter-arrival times with deadline threshold. Timestamps
    /// are `Instant`, deadlines are `Duration` or multiples.
    #[derive(Debug, Clone)]
    pub struct LivenessInstant {
        alpha: f64,
        one_minus_alpha: f64,
        interval: f64, // seconds
        last_timestamp: Option<Instant>,
        deadline_multiple: Option<f64>,
        deadline_absolute: Option<Duration>,
        count: u64,
        min_samples: u64,
    }

    /// Builder for [`LivenessInstant`].
    #[derive(Debug, Clone)]
    pub struct LivenessInstantBuilder {
        alpha: Option<f64>,
        deadline_multiple: Option<f64>,
        deadline_absolute: Option<Duration>,
        min_samples: u64,
    }

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

        /// Updates with an event. Returns `true` if alive.
        #[inline]
        #[must_use]
        pub fn update(&mut self, now: Instant) -> bool {
            self.count += 1;

            let dt = if let Some(last) = self.last_timestamp {
                now.saturating_duration_since(last).as_secs_f64()
            } else {
                self.last_timestamp = Some(now);
                return true;
            };
            self.last_timestamp = Some(now);

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

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

            self.is_alive_at_interval(dt)
        }

        /// Checks liveness without recording. Returns `true` if alive.
        #[inline]
        #[must_use]
        pub fn check(&self, now: Instant) -> bool {
            if self.count < self.min_samples {
                return true;
            }
            let dt = match self.last_timestamp {
                Some(last) => now.saturating_duration_since(last).as_secs_f64(),
                None => return true,
            };
            self.is_alive_at_interval(dt)
        }

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

        /// Current smoothed inter-arrival time 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 detector 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;
        }

        /// Switch to deadline-multiple threshold.
        #[inline]
        pub fn reconfigure_deadline_multiple(&mut self, n: f64) {
            self.deadline_multiple = Some(n);
            self.deadline_absolute = None;
        }

        /// Switch to absolute deadline threshold.
        #[inline]
        pub fn reconfigure_deadline_absolute(&mut self, d: Duration) {
            self.deadline_absolute = Some(d);
            self.deadline_multiple = None;
        }
    }

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

        /// Span for 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 checking. Default: 2.
        #[inline]
        #[must_use]
        pub fn min_samples(mut self, min: u64) -> Self {
            self.min_samples = min;
            self
        }

        /// Deadline as multiple of smoothed interval.
        #[inline]
        #[must_use]
        pub fn deadline_multiple(mut self, n: f64) -> Self {
            self.deadline_multiple = Some(n);
            self
        }

        /// Deadline as absolute Duration.
        #[inline]
        #[must_use]
        pub fn deadline_absolute(mut self, d: Duration) -> Self {
            self.deadline_absolute = Some(d);
            self
        }

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

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

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

        #[test]
        fn alive_within_deadline() {
            let base = Instant::now();
            let mut lv = LivenessInstant::builder()
                .span(10)
                .deadline_multiple(3.0)
                .build()
                .unwrap();
            assert!(lv.update(base));
            assert!(lv.update(base + Duration::from_secs(1)));
            // 2 seconds later — 2x interval, within 3x deadline
            assert!(lv.check(base + Duration::from_secs(3)));
        }

        #[test]
        fn dead_beyond_deadline() {
            let base = Instant::now();
            let mut lv = LivenessInstant::builder()
                .span(10)
                .deadline_multiple(3.0)
                .build()
                .unwrap();
            assert!(lv.update(base));
            assert!(lv.update(base + Duration::from_secs(1)));
            // 10 seconds later — 10x interval, exceeds 3x deadline
            assert!(!lv.check(base + Duration::from_secs(11)));
        }

        #[test]
        fn absolute_deadline() {
            let base = Instant::now();
            let mut lv = LivenessInstant::builder()
                .span(10)
                .deadline_absolute(Duration::from_secs(5))
                .build()
                .unwrap();
            assert!(lv.update(base));
            assert!(lv.update(base + Duration::from_secs(1)));
            assert!(lv.check(base + Duration::from_secs(5))); // within 5s
            assert!(!lv.check(base + Duration::from_secs(7))); // beyond 5s
        }

        #[test]
        fn reset_clears() {
            let base = Instant::now();
            let mut lv = LivenessInstant::builder()
                .span(10)
                .deadline_multiple(3.0)
                .build()
                .unwrap();
            let _ = lv.update(base);
            let _ = lv.update(base + Duration::from_secs(1));
            lv.reset(base + Duration::from_secs(2));
            assert_eq!(lv.count(), 0);
        }
    }
}

#[cfg(feature = "std")]
pub use instant_liveness::{LivenessInstant, LivenessInstantBuilder};