nexus-stats-core 1.1.1

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
use crate::math::MulAdd;
// =============================================================================
// Float EMA
// =============================================================================

macro_rules! impl_ema_float {
    ($name:ident, $builder:ident, $ty:ty) => {
        /// EMA — Exponential Moving Average.
        ///
        /// Smooths a streaming signal with exponential decay. Recent samples
        /// weighted more heavily. Equivalent to a first-order IIR low-pass filter.
        ///
        /// # Construction
        ///
        /// Three ways to configure the smoothing factor:
        /// - `alpha(a)` — direct, a ∈ (0, 1). Higher = more reactive.
        /// - `halflife(h)` — samples for weight to decay by half.
        /// - `span(n)` — pandas/finance convention, alpha = 2/(n+1).
        ///
        /// # Use Cases
        /// - Smoothing noisy latency measurements
        /// - Tracking moving average of throughput
        /// - Baseline estimation for anomaly detection
        #[derive(Debug, Clone)]
        pub struct $name {
            alpha: $ty,
            one_minus_alpha: $ty,
            value: $ty,
            count: u64,
            min_samples: u64,
        }

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

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

            /// Feeds a sample. Returns smoothed value once primed.
            ///
            /// First sample initializes the EMA directly (no smoothing).
            ///
            /// # Errors
            ///
            /// Returns `DataError::NotANumber` if the sample is NaN, or
            /// `DataError::Infinite` if the sample is infinite.
            #[inline]
            pub fn update(&mut self, sample: $ty) -> Result<Option<$ty>, crate::DataError> {
                check_finite!(sample);
                self.count += 1;

                if self.count == 1 {
                    self.value = sample;
                } else {
                    self.value = self.alpha.fma(sample, self.one_minus_alpha * self.value);
                }

                if self.count >= self.min_samples {
                    Ok(Option::Some(self.value))
                } else {
                    Ok(Option::None)
                }
            }

            /// Current smoothed value, or `None` if not primed.
            #[inline]
            #[must_use]
            pub fn value(&self) -> Option<$ty> {
                if self.count >= self.min_samples {
                    Option::Some(self.value)
                } else {
                    Option::None
                }
            }

            /// The smoothing factor alpha.
            #[inline]
            #[must_use]
            pub fn alpha(&self) -> $ty {
                self.alpha
            }

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

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

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

            /// Updates the smoothing factor without resetting state.
            ///
            /// # Errors
            ///
            /// Alpha must be in (0, 1) exclusive.
            #[inline]
            pub fn reconfigure_alpha(&mut self, alpha: $ty) -> Result<(), crate::ConfigError> {
                if !(alpha > 0.0 as $ty && alpha < 1.0 as $ty) {
                    return Err(crate::ConfigError::Invalid("EMA alpha must be in (0, 1)"));
                }
                self.alpha = alpha;
                self.one_minus_alpha = 1.0 as $ty - alpha;
                Ok(())
            }
        }

        impl $builder {
            /// Direct smoothing factor. Must be in (0, 1) exclusive.
            #[inline]
            #[must_use]
            pub fn alpha(mut self, alpha: $ty) -> Self {
                self.alpha = Option::Some(alpha);
                self
            }

            /// Samples for weight to decay by half.
            ///
            /// Computes: `alpha = 1 - exp(-ln(2) / halflife)`
            #[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
            }

            /// Number of samples for center of mass (pandas convention).
            ///
            /// Computes: `alpha = 2 / (n + 1)`
            #[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 samples before value is considered valid. Default: 1.
            #[inline]
            #[must_use]
            pub fn min_samples(mut self, min: u64) -> Self {
                self.min_samples = min;
                self
            }

            /// Pre-loads the smoothed value from calibration data.
            ///
            /// When seeded, `is_primed()` returns true immediately and
            /// the first `update()` applies smoothing (no raw initialization).
            #[inline]
            #[must_use]
            pub fn seed(mut self, value: $ty) -> Self {
                self.seed = Option::Some(value);
                self
            }

            /// Builds the EMA.
            ///
            /// # Errors
            ///
            /// - Alpha must have been set (via `alpha`, `halflife`, or `span`).
            /// - 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("EMA alpha must be in (0, 1)"));
                }

                let (value, count) = if let Some(seed_val) = self.seed {
                    (seed_val, self.min_samples)
                } else {
                    (0.0 as $ty, 0)
                };

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

impl_ema_float!(EmaF64, EmaF64Builder, f64);
impl_ema_float!(EmaF32, EmaF32Builder, f32);

// =============================================================================
// Integer EMA (kernel-style fixed-point)
// =============================================================================

/// Rounds `n` up to the next value of the form `2^k - 1`.
///
/// Examples: 1→1, 2→3, 3→3, 4→7, 5→7, 10→15, 20→31.
#[inline]
pub(crate) const fn next_power_of_two_minus_one(n: u64) -> u64 {
    if n == 0 {
        return 0;
    }
    // next_power_of_two(n + 1) - 1
    // But we need to handle the case where n+1 is already a power of 2
    let v = n + 1;
    let p = v.next_power_of_two();
    p - 1
}

/// Returns log2 of (n + 1), where n must be of the form 2^k - 1.
#[inline]
pub(crate) const fn log2_of_span_plus_one(span: u64) -> u32 {
    // span = 2^k - 1, so span + 1 = 2^k
    (span + 1).trailing_zeros()
}

macro_rules! impl_ema_int {
    ($name:ident, $builder:ident, $ty:ty, $acc_ty:ty) => {
        /// EMA — Exponential Moving Average (integer fixed-point variant).
        ///
        /// Uses the Linux kernel pattern: bit-shift arithmetic with integer-only
        /// operations. No floating point. Weight is derived from span, rounded
        /// up to the next valid value (`2^k - 1`) for shift optimization.
        ///
        /// The weight reciprocal is `span + 1` (a power of 2), so division
        /// becomes a right-shift by `k` bits.
        ///
        /// # Use Cases
        /// - Smoothing nanosecond latency measurements without float
        /// - Kernel-style EWMA for counters and durations
        #[derive(Debug, Clone)]
        pub struct $name {
            /// Accumulator — stores value << shift for precision
            acc: $acc_ty,
            /// Bit shift amount: log2(span + 1)
            shift: u32,
            /// Effective span (2^k - 1)
            span: u64,
            count: u64,
            min_samples: u64,
            initialized: bool,
        }

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

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

            /// Feeds a sample. Returns smoothed value once primed.
            ///
            /// First sample initializes the accumulator directly.
            ///
            /// Update formula (kernel pattern):
            /// ```text
            /// acc += (sample << shift) - acc) >> shift
            /// ```
            /// This is equivalent to: `value = value + (sample - value) / (span + 1)`
            #[inline]
            #[must_use]
            pub fn update(&mut self, sample: $ty) -> Option<$ty> {
                self.count += 1;

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

                if self.count >= self.min_samples {
                    Option::Some((self.acc >> self.shift) as $ty)
                } else {
                    Option::None
                }
            }

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

            /// The actual span after rounding up to `2^k - 1`.
            #[inline]
            #[must_use]
            pub fn effective_span(&self) -> u64 {
                self.span
            }

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

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

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

            /// Updates the span without resetting state.
            ///
            /// Unshifts the accumulator with the old shift and reshifts with the
            /// new one, preserving the smoothed value.
            ///
            /// # Errors
            ///
            /// Span must be >= 1.
            #[inline]
            pub fn reconfigure_span(&mut self, span: u64) -> Result<(), crate::ConfigError> {
                if span < 1 {
                    return Err(crate::ConfigError::Invalid("EMA span must be >= 1"));
                }
                let effective = next_power_of_two_minus_one(span);
                let new_shift = log2_of_span_plus_one(effective);

                // Rescale accumulator directly to preserve fixed-point precision.
                // Only loses bits when shifting down (smaller span), which is unavoidable.
                if self.initialized {
                    if new_shift > self.shift {
                        self.acc <<= new_shift - self.shift;
                    } else {
                        self.acc >>= self.shift - new_shift;
                    }
                }

                self.shift = new_shift;
                self.span = effective;
                Ok(())
            }
        }

        impl $builder {
            /// Minimum span. Rounded up to next `2^k - 1`.
            ///
            /// Call [`
            #[doc = stringify!($name)]
            /// ::effective_span()`] after build to see the actual value.
            #[inline]
            #[must_use]
            pub fn span(mut self, n: u64) -> Self {
                self.span = Option::Some(n);
                self
            }

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

            /// Pre-loads the smoothed value from calibration data.
            ///
            /// When seeded, `is_primed()` returns true immediately.
            #[inline]
            #[must_use]
            pub fn seed(mut self, value: $ty) -> Self {
                self.seed = Option::Some(value);
                self
            }

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

                let effective = next_power_of_two_minus_one(requested);
                let shift = log2_of_span_plus_one(effective);

                let (acc, count, initialized) = if let Some(seed_val) = self.seed {
                    ((seed_val as $acc_ty) << shift, self.min_samples, true)
                } else {
                    (0, 0, false)
                };

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

impl_ema_int!(EmaI64, EmaI64Builder, i64, i128);
impl_ema_int!(EmaI32, EmaI32Builder, i32, i64);

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

    // =========================================================================
    // Float EMA
    // =========================================================================

    #[test]
    fn first_sample_initializes() {
        let mut ema = EmaF64::builder().alpha(0.5).build().unwrap();
        assert_eq!(ema.update(100.0).unwrap(), Some(100.0));
        assert_eq!(ema.value(), Some(100.0));
    }

    #[test]
    fn convergence_toward_constant() {
        let mut ema = EmaF64::builder().alpha(0.1).build().unwrap();

        // Initialize with 0
        ema.update(0.0).unwrap();

        // Feed constant 100 — should converge
        for _ in 0..1000 {
            ema.update(100.0).unwrap();
        }

        let val = ema.value().unwrap();
        assert!(
            (val - 100.0).abs() < 0.01,
            "EMA should converge to 100, got {val}"
        );
    }

    #[test]
    fn higher_alpha_reacts_faster() {
        let mut fast = EmaF64::builder().alpha(0.9).build().unwrap();
        let mut slow = EmaF64::builder().alpha(0.1).build().unwrap();

        fast.update(0.0).unwrap();
        slow.update(0.0).unwrap();

        fast.update(100.0).unwrap();
        slow.update(100.0).unwrap();

        let fast_val = fast.value().unwrap();
        let slow_val = slow.value().unwrap();

        assert!(
            fast_val > slow_val,
            "fast ({fast_val}) should react more than slow ({slow_val})"
        );
    }

    #[test]
    fn priming_behavior() {
        let mut ema = EmaF64::builder().alpha(0.5).min_samples(5).build().unwrap();

        for i in 1..5 {
            assert_eq!(
                ema.update(100.0).unwrap(),
                None,
                "sample {i} should not be primed"
            );
            assert!(!ema.is_primed());
        }

        assert!(ema.update(100.0).unwrap().is_some());
        assert!(ema.is_primed());
    }

    #[test]
    fn reset_clears_state() {
        let mut ema = EmaF64::builder().alpha(0.5).build().unwrap();
        ema.update(100.0).unwrap();
        ema.update(200.0).unwrap();

        ema.reset();
        assert_eq!(ema.count(), 0);
        assert_eq!(ema.value(), None);

        // Re-initialize should work
        assert_eq!(ema.update(50.0).unwrap(), Some(50.0));
    }

    #[test]
    fn span_computes_alpha() {
        let ema = EmaF64::builder().span(19).build().unwrap();
        // alpha = 2 / (19 + 1) = 0.1
        assert!((ema.alpha() - 0.1).abs() < 1e-10);
    }

    #[test]
    fn halflife_computes_alpha() {
        let ema = EmaF64::builder().halflife(1.0).build().unwrap();
        // halflife=1: alpha = 1 - exp(-ln2) = 1 - 0.5 = 0.5
        assert!((ema.alpha() - 0.5).abs() < 1e-10);
    }

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

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

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

    #[test]
    fn f32_basic() {
        let mut ema = EmaF32::builder().alpha(0.5).build().unwrap();
        assert_eq!(ema.update(100.0).unwrap(), Some(100.0));
        let v = ema.update(200.0).unwrap().unwrap();
        assert!((v - 150.0).abs() < 0.01);
    }

    // =========================================================================
    // Integer EMA
    // =========================================================================

    #[test]
    fn span_rounding() {
        // 1 → 1 (2^1 - 1)
        let ema = EmaI64::builder().span(1).build().unwrap();
        assert_eq!(ema.effective_span(), 1);

        // 2 → 3 (2^2 - 1)
        let ema = EmaI64::builder().span(2).build().unwrap();
        assert_eq!(ema.effective_span(), 3);

        // 3 → 3
        let ema = EmaI64::builder().span(3).build().unwrap();
        assert_eq!(ema.effective_span(), 3);

        // 7 → 7 (2^3 - 1, exact)
        let ema = EmaI64::builder().span(7).build().unwrap();
        assert_eq!(ema.effective_span(), 7);

        // 10 → 15 (2^4 - 1)
        let ema = EmaI64::builder().span(10).build().unwrap();
        assert_eq!(ema.effective_span(), 15);

        // 20 → 31 (2^5 - 1)
        let ema = EmaI64::builder().span(20).build().unwrap();
        assert_eq!(ema.effective_span(), 31);
    }

    #[test]
    fn int_first_sample_initializes() {
        let mut ema = EmaI64::builder().span(7).build().unwrap();
        assert_eq!(ema.update(1000), Some(1000));
    }

    #[test]
    fn int_convergence() {
        let mut ema = EmaI64::builder().span(7).build().unwrap();

        let _ = ema.update(0);
        for _ in 0..10_000 {
            let _ = ema.update(1000);
        }

        let val = ema.value().unwrap();
        // Should converge close to 1000 (integer precision may be off by 1)
        assert!(
            (val - 1000).abs() <= 1,
            "should converge to ~1000, got {val}"
        );
    }

    #[test]
    fn int_no_drift_over_many_samples() {
        let mut ema = EmaI64::builder().span(15).build().unwrap();

        // Feed constant value — should not drift
        for _ in 0..100_000 {
            let _ = ema.update(500);
        }

        let val = ema.value().unwrap();
        assert_eq!(
            val, 500,
            "constant input should produce exact output, got {val}"
        );
    }

    #[test]
    fn int_priming() {
        let mut ema = EmaI64::builder().span(7).min_samples(5).build().unwrap();

        for _ in 0..4 {
            assert_eq!(ema.update(100), None);
        }
        assert!(ema.update(100).is_some());
    }

    #[test]
    fn int_reset() {
        let mut ema = EmaI64::builder().span(7).build().unwrap();
        let _ = ema.update(1000);
        let _ = ema.update(2000);

        ema.reset();
        assert_eq!(ema.count(), 0);
        assert_eq!(ema.value(), None);
    }

    #[test]
    fn i32_basic() {
        let mut ema = EmaI32::builder().span(3).build().unwrap();
        assert_eq!(ema.update(100), Some(100));
    }

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

    // =========================================================================
    // Reconfigure
    // =========================================================================

    #[test]
    #[allow(clippy::float_cmp)]
    fn float_reconfigure_alpha_preserves_value() {
        let mut ema = EmaF64::builder().alpha(0.5).build().unwrap();
        ema.update(100.0).unwrap();
        ema.update(200.0).unwrap();
        let val_before = ema.value().unwrap();
        let count_before = ema.count();

        ema.reconfigure_alpha(0.9).unwrap();

        assert!((ema.alpha() - 0.9).abs() < 1e-10);
        assert_eq!(ema.value().unwrap(), val_before);
        assert_eq!(ema.count(), count_before);
    }

    #[test]
    fn float_reconfigure_alpha_validates() {
        let mut ema = EmaF64::builder().alpha(0.5).build().unwrap();
        assert!(ema.reconfigure_alpha(0.0).is_err());
        assert!(ema.reconfigure_alpha(1.0).is_err());
        assert!(ema.reconfigure_alpha(-0.1).is_err());
    }

    #[test]
    fn int_reconfigure_span_preserves_value() {
        let mut ema = EmaI64::builder().span(7).build().unwrap();
        for _ in 0..100 {
            let _ = ema.update(500);
        }
        let val_before = ema.value().unwrap();
        let count_before = ema.count();

        ema.reconfigure_span(15).unwrap();

        assert_eq!(ema.effective_span(), 15);
        assert_eq!(ema.value().unwrap(), val_before);
        assert_eq!(ema.count(), count_before);
    }

    #[test]
    fn int_reconfigure_span_validates() {
        let mut ema = EmaI64::builder().span(7).build().unwrap();
        assert!(ema.reconfigure_span(0).is_err());
    }

    #[test]
    fn int_vs_float_comparison() {
        // Both should produce similar results on the same input
        let mut int_ema = EmaI64::builder().span(15).build().unwrap();
        let mut float_ema = EmaF64::builder().span(15).build().unwrap();

        let samples = [100, 110, 95, 105, 120, 90, 100, 115, 85, 100];

        for &s in &samples {
            let _ = int_ema.update(s);
            float_ema.update(s as f64).unwrap();
        }

        let int_val = int_ema.value().unwrap();
        let float_val = float_ema.value().unwrap();

        // Should be within a few units of each other
        let diff = (int_val as f64 - float_val).abs();
        assert!(
            diff < 5.0,
            "int ({int_val}) and float ({float_val}) should be close, diff={diff}"
        );
    }

    #[test]
    fn rejects_nan_and_inf() {
        let mut ema = EmaF64::builder().alpha(0.5).build().unwrap();
        assert!(matches!(
            ema.update(f64::NAN),
            Err(crate::DataError::NotANumber)
        ));
        assert!(matches!(
            ema.update(f64::INFINITY),
            Err(crate::DataError::Infinite)
        ));
        assert!(matches!(
            ema.update(f64::NEG_INFINITY),
            Err(crate::DataError::Infinite)
        ));
        // State unchanged — counter should still be 0
        assert_eq!(ema.count(), 0);
    }
}