rill-ml 1.2.0-rc.1

Lightweight, serializable online machine learning for Rust applications and streaming data.
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
//! Page-Hinkley sequential change detection.
//!
//! The Page-Hinkley test detects sustained shifts in the mean of a scalar
//! stream. It is well suited for detecting average-value changes in target
//! values or prediction errors.
//!
//! ## Algorithm
//!
//! For each new observation `x_t`:
//!
//! 1. Update the running mean `x̄` incrementally.
//! 2. Update the cumulative sum: `S_t = α · S_{t-1} + (x_t − x̄ − δ)`
//!    where `α` is the forgetting factor and `δ` is the allowed drift
//!    magnitude.
//! 3. Track the running minimum: `m_t = min(m_{t-1}, S_t)`.
//! 4. Compute the test statistic: `PH_t = S_t − m_t`.
//! 5. Signal drift when `PH_t > threshold`.
//!
//! ## Space complexity
//!
//! `O(1)` — the detector stores only the running mean, cumulative sum,
//! minimum, and a counter.

use crate::drift::detector::{DriftDetector, DriftLevel};
use crate::error::{RillError, checked_increment, ensure_finite};
use crate::persistence::ValidateState;

/// Portable Page-Hinkley state schema version.
pub const PAGE_HINKLEY_PORTABLE_STATE_VERSION: u32 = 1;

/// Configuration for [`PageHinkley`].
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct PageHinkleyConfig {
    /// The detection threshold (λ). When the test statistic exceeds this
    /// value, a drift is reported. Must be finite and strictly positive.
    /// Larger values reduce false positives but increase detection latency.
    pub threshold: f64,

    /// The warning threshold. When the test statistic exceeds this value
    /// but not [`threshold`](Self::threshold), a warning is reported.
    /// Must be in `[0, threshold]`. Set to `0.0` to disable warnings.
    pub warning_threshold: f64,

    /// The forgetting factor (α) applied to the cumulative sum at each step.
    /// Must be in `(0, 1]`. Smaller values make the detector forget old
    /// observations faster. `1.0` gives the standard (non-forgetting)
    /// Page-Hinkley test.
    pub alpha: f64,

    /// The allowed drift magnitude (δ). The cumulative sum is penalised by
    /// this amount at each step, making the detector less sensitive to
    /// small fluctuations. Must be finite and non-negative.
    pub delta: f64,

    /// Minimum number of samples before any detection is reported.
    /// Must be greater than zero.
    pub min_samples: u64,
}

/// Versioned, portable Page-Hinkley state.
///
/// This DTO is the stable persistence surface for Page-Hinkley continuity.
/// The detector's direct serde representation remains Preview.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct PageHinkleyPortableStateV1 {
    /// Portable schema version; always `1`.
    pub version: u32,
    /// Threshold from the configuration that produced this state.
    pub threshold: f64,
    /// Warning threshold from the originating configuration.
    pub warning_threshold: f64,
    /// Forgetting factor from the originating configuration.
    pub alpha: f64,
    /// Allowed drift magnitude from the originating configuration.
    pub delta: f64,
    /// Minimum samples from the originating configuration.
    pub min_samples: u64,
    /// Running mean.
    pub mean: f64,
    /// Total observations incorporated.
    pub samples: u64,
    /// Current cumulative sum.
    pub cumulative_sum: f64,
    /// Smallest cumulative sum observed.
    pub minimum_cumulative_sum: f64,
    /// Last reported detector level.
    pub current_level: DriftLevel,
}

impl ValidateState for PageHinkleyPortableStateV1 {
    fn validate_state(&self) -> Result<(), RillError> {
        if self.version != PAGE_HINKLEY_PORTABLE_STATE_VERSION {
            return Err(RillError::IncompatibleStateVersion {
                expected: PAGE_HINKLEY_PORTABLE_STATE_VERSION,
                actual: self.version,
            });
        }
        let config = PageHinkleyConfig {
            threshold: self.threshold,
            warning_threshold: self.warning_threshold,
            alpha: self.alpha,
            delta: self.delta,
            min_samples: self.min_samples,
        };
        PageHinkley::new(config.clone())?;
        ensure_finite("portable Page-Hinkley mean", self.mean)?;
        ensure_finite("portable Page-Hinkley cumulative_sum", self.cumulative_sum)?;
        ensure_finite(
            "portable Page-Hinkley minimum_cumulative_sum",
            self.minimum_cumulative_sum,
        )?;
        if self.minimum_cumulative_sum > self.cumulative_sum {
            return Err(RillError::InvalidState(
                "Page-Hinkley minimum cumulative sum exceeds cumulative sum".to_owned(),
            ));
        }
        if self.samples == 0
            && (self.mean != 0.0
                || self.cumulative_sum != 0.0
                || self.minimum_cumulative_sum != 0.0
                || self.current_level != DriftLevel::None)
        {
            return Err(RillError::InvalidState(
                "empty Page-Hinkley state must use zero accumulators and no level".to_owned(),
            ));
        }
        if self.samples < self.min_samples && self.current_level != DriftLevel::None {
            return Err(RillError::InvalidState(
                "Page-Hinkley state reports a level before min_samples".to_owned(),
            ));
        }
        Ok(())
    }
}

impl Default for PageHinkleyConfig {
    fn default() -> Self {
        Self {
            threshold: 50.0,
            warning_threshold: 25.0,
            alpha: 1.0,
            delta: 0.005,
            min_samples: 30,
        }
    }
}

/// Page-Hinkley sequential change detector.
///
/// Detects sustained mean shifts in a scalar stream. See the module
/// documentation for the algorithm.
///
/// # Examples
///
/// ```
/// use rill_ml::drift::{DriftDetector, DriftLevel, PageHinkley};
///
/// let mut ph = PageHinkley::default();
///
/// // Stable stream: no drift.
/// for _ in 0..200 {
///     ph.update(0.0).unwrap();
/// }
/// assert_eq!(ph.level(), DriftLevel::None);
///
/// // Sudden shift.
/// for _ in 0..100 {
///     ph.update(5.0).unwrap();
/// }
/// assert!(ph.detected());
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PageHinkley {
    config: PageHinkleyConfig,
    mean: f64,
    samples: u64,
    cum_sum: f64,
    min_cum_sum: f64,
    current_level: DriftLevel,
}

impl PageHinkley {
    /// Create a new Page-Hinkley detector with the given configuration.
    ///
    /// Returns an error if:
    /// - `threshold` is not finite or not strictly positive.
    /// - `warning_threshold` is negative or greater than `threshold`.
    /// - `alpha` is not in `(0, 1]`.
    /// - `delta` is not finite or is negative.
    /// - `min_samples` is zero.
    pub fn new(config: PageHinkleyConfig) -> Result<Self, RillError> {
        ensure_finite("threshold", config.threshold)?;
        if config.threshold <= 0.0 {
            return Err(RillError::InvalidParameter {
                name: "threshold",
                value: config.threshold,
            });
        }
        ensure_finite("warning_threshold", config.warning_threshold)?;
        if config.warning_threshold < 0.0 || config.warning_threshold > config.threshold {
            return Err(RillError::InvalidParameter {
                name: "warning_threshold",
                value: config.warning_threshold,
            });
        }
        ensure_finite("alpha", config.alpha)?;
        if config.alpha <= 0.0 || config.alpha > 1.0 {
            return Err(RillError::InvalidParameter {
                name: "alpha",
                value: config.alpha,
            });
        }
        ensure_finite("delta", config.delta)?;
        if config.delta < 0.0 {
            return Err(RillError::InvalidParameter {
                name: "delta",
                value: config.delta,
            });
        }
        if config.min_samples == 0 {
            return Err(RillError::InvalidParameter {
                name: "min_samples",
                value: 0.0,
            });
        }
        Ok(Self {
            config,
            mean: 0.0,
            samples: 0,
            cum_sum: 0.0,
            min_cum_sum: 0.0,
            current_level: DriftLevel::None,
        })
    }

    /// The current running mean of the observed stream.
    pub const fn mean(&self) -> f64 {
        self.mean
    }

    /// The current cumulative sum `S_t`.
    pub const fn cum_sum(&self) -> f64 {
        self.cum_sum
    }

    /// The current test statistic `PH_t = S_t − min(S)`.
    pub const fn ph_statistic(&self) -> f64 {
        self.cum_sum - self.min_cum_sum
    }

    /// The configuration of this detector.
    pub const fn config(&self) -> &PageHinkleyConfig {
        &self.config
    }

    /// Export the stable portable state without exposing the detector's
    /// Preview internal serde layout.
    pub fn export_state_v1(&self) -> PageHinkleyPortableStateV1 {
        PageHinkleyPortableStateV1 {
            version: PAGE_HINKLEY_PORTABLE_STATE_VERSION,
            threshold: self.config.threshold,
            warning_threshold: self.config.warning_threshold,
            alpha: self.config.alpha,
            delta: self.config.delta,
            min_samples: self.config.min_samples,
            mean: self.mean,
            samples: self.samples,
            cumulative_sum: self.cum_sum,
            minimum_cumulative_sum: self.min_cum_sum,
            current_level: self.current_level,
        }
    }

    /// Restore from a validated portable state.
    ///
    /// The supplied configuration must exactly match the configuration stored
    /// in the state, preventing accidental continuation under new semantics.
    pub fn restore_state_v1(
        config: PageHinkleyConfig,
        state: PageHinkleyPortableStateV1,
    ) -> Result<Self, RillError> {
        state.validate_state()?;
        if config.threshold != state.threshold
            || config.warning_threshold != state.warning_threshold
            || config.alpha != state.alpha
            || config.delta != state.delta
            || config.min_samples != state.min_samples
        {
            return Err(RillError::InvalidState(
                "Page-Hinkley portable state configuration mismatch".to_owned(),
            ));
        }
        PageHinkley::new(config.clone())?;
        Ok(Self {
            config,
            mean: state.mean,
            samples: state.samples,
            cum_sum: state.cumulative_sum,
            min_cum_sum: state.minimum_cumulative_sum,
            current_level: state.current_level,
        })
    }
}

impl Default for PageHinkley {
    fn default() -> Self {
        Self::new(PageHinkleyConfig::default()).expect("default config is valid")
    }
}

impl DriftDetector for PageHinkley {
    fn update(&mut self, value: f64) -> Result<DriftLevel, RillError> {
        ensure_finite("value", value)?;
        self.samples = checked_increment(self.samples, "samples")?;
        // Incremental mean update.
        let delta = value - self.mean;
        self.mean += delta / self.samples as f64;
        // Cumulative sum with optional forgetting.
        self.cum_sum = self.config.alpha * self.cum_sum + (value - self.mean - self.config.delta);
        // Track the running minimum of the cumulative sum.
        if self.cum_sum < self.min_cum_sum {
            self.min_cum_sum = self.cum_sum;
        }
        // Determine the level, respecting the minimum-samples gate.
        if self.samples < self.config.min_samples {
            self.current_level = DriftLevel::None;
        } else {
            let stat = self.ph_statistic();
            if stat > self.config.threshold {
                self.current_level = DriftLevel::Drift;
            } else if stat > self.config.warning_threshold {
                self.current_level = DriftLevel::Warning;
            } else {
                self.current_level = DriftLevel::None;
            }
        }
        Ok(self.current_level)
    }

    fn detected(&self) -> bool {
        self.current_level == DriftLevel::Drift
    }

    fn warning(&self) -> bool {
        self.current_level == DriftLevel::Warning
    }

    fn level(&self) -> DriftLevel {
        self.current_level
    }

    fn samples_seen(&self) -> u64 {
        self.samples
    }

    fn reset(&mut self) {
        self.mean = 0.0;
        self.samples = 0;
        self.cum_sum = 0.0;
        self.min_cum_sum = 0.0;
        self.current_level = DriftLevel::None;
    }

    fn last_value(&self) -> f64 {
        self.ph_statistic()
    }
}

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

    /// Deterministic pseudo-random number in `[0, 1)` using a simple LCG.
    fn next_unit(seed: &mut u64) -> f64 {
        *seed = seed
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        ((*seed >> 11) as f64) / ((1u64 << 53) as f64)
    }

    #[test]
    fn default_config_is_valid() {
        let ph = PageHinkley::default();
        assert_eq!(ph.samples_seen(), 0);
        assert_eq!(ph.level(), DriftLevel::None);
        assert!(!ph.detected());
        assert!(!ph.warning());
    }

    #[test]
    fn detects_sudden_mean_shift() {
        let mut ph = PageHinkley::new(PageHinkleyConfig {
            threshold: 10.0,
            warning_threshold: 5.0,
            alpha: 1.0,
            delta: 0.01,
            min_samples: 10,
        })
        .unwrap();
        // Stable stream around 0.
        let mut seed = 42u64;
        for _ in 0..100 {
            let noise = 0.1 * (next_unit(&mut seed) - 0.5);
            ph.update(noise).unwrap();
        }
        assert_eq!(ph.level(), DriftLevel::None);
        // Sudden shift to mean 5.
        let mut detected = false;
        for _ in 0..100 {
            let noise = 0.1 * (next_unit(&mut seed) - 0.5);
            let level = ph.update(5.0 + noise).unwrap();
            if level == DriftLevel::Drift {
                detected = true;
                break;
            }
        }
        assert!(detected, "should detect the mean shift");
    }

    #[test]
    fn no_false_positive_on_stable_stream() {
        let mut ph = PageHinkley::new(PageHinkleyConfig {
            threshold: 20.0,
            warning_threshold: 10.0,
            alpha: 0.99,
            delta: 0.01,
            min_samples: 30,
        })
        .unwrap();
        // 1000 samples of Gaussian-ish noise around 0 with small variance.
        let mut seed = 7u64;
        for _ in 0..1000 {
            let noise = 0.5 * (next_unit(&mut seed) - 0.5);
            ph.update(noise).unwrap();
        }
        assert!(
            !ph.detected(),
            "false positive: drift reported on stable stream (stat={})",
            ph.ph_statistic()
        );
    }

    #[test]
    fn works_on_prediction_error_stream() {
        // Simulate prediction errors: initially small, then large after drift.
        let mut ph = PageHinkley::new(PageHinkleyConfig {
            threshold: 5.0,
            warning_threshold: 2.0,
            alpha: 1.0,
            delta: 0.0,
            min_samples: 5,
        })
        .unwrap();
        // Low-error phase.
        for _ in 0..50 {
            ph.update(0.1).unwrap();
        }
        assert_eq!(ph.level(), DriftLevel::None);
        // High-error phase.
        let mut detected_step = None;
        for i in 0..100 {
            let level = ph.update(2.0).unwrap();
            if level == DriftLevel::Drift {
                detected_step = Some(i);
                break;
            }
        }
        assert!(detected_step.is_some(), "should detect error increase");
    }

    #[test]
    fn warning_before_drift() {
        let mut ph = PageHinkley::new(PageHinkleyConfig {
            threshold: 100.0,
            warning_threshold: 0.5,
            alpha: 1.0,
            delta: 0.0,
            min_samples: 5,
        })
        .unwrap();
        // Baseline phase: feed 0.0 so the running mean settles at 0.
        for _ in 0..50 {
            ph.update(0.0).unwrap();
        }
        // Shift phase: feed 1.0; the mean lags so cum_sum grows.
        for _ in 0..100 {
            ph.update(1.0).unwrap();
            if ph.warning() || ph.detected() {
                break;
            }
        }
        assert!(
            ph.warning() || ph.detected(),
            "expected warning or drift, got {:?}, stat={}",
            ph.level(),
            ph.ph_statistic()
        );
    }

    #[test]
    fn min_samples_gates_detection() {
        let mut ph = PageHinkley::new(PageHinkleyConfig {
            threshold: 0.001,
            warning_threshold: 0.0,
            alpha: 1.0,
            delta: 0.0,
            min_samples: 100,
        })
        .unwrap();
        // Baseline phase: 98 zeros establish a mean near 0.
        for _ in 0..98 {
            ph.update(0.0).unwrap();
        }
        // Sample 99: shift to 1000.0, but 99 < min_samples=100 → no detection.
        ph.update(1000.0).unwrap();
        assert_eq!(ph.level(), DriftLevel::None);
        // Sample 100: ≥ min_samples, detection can now trigger.
        ph.update(1000.0).unwrap();
        assert!(ph.detected() || ph.warning());
    }

    #[test]
    fn reset_clears_state() {
        let mut ph = PageHinkley::new(PageHinkleyConfig {
            threshold: 1.0,
            warning_threshold: 0.5,
            alpha: 1.0,
            delta: 0.0,
            min_samples: 5,
        })
        .unwrap();
        // Baseline phase: 10 zeros establish a mean near 0.
        for _ in 0..10 {
            ph.update(0.0).unwrap();
        }
        // Shift phase: 10 tens trigger detection (mean lags behind).
        for _ in 0..10 {
            ph.update(10.0).unwrap();
        }
        assert!(ph.detected() || ph.warning());
        ph.reset();
        assert_eq!(ph.samples_seen(), 0);
        assert_eq!(ph.level(), DriftLevel::None);
        assert_eq!(ph.mean(), 0.0);
        assert_eq!(ph.cum_sum(), 0.0);
        assert_eq!(ph.ph_statistic(), 0.0);
    }

    #[test]
    fn rejects_non_finite_input() {
        let mut ph = PageHinkley::default();
        assert!(ph.update(f64::NAN).is_err());
        assert!(ph.update(f64::INFINITY).is_err());
        assert!(ph.update(f64::NEG_INFINITY).is_err());
        assert_eq!(ph.samples_seen(), 0);
    }

    #[test]
    fn rejects_invalid_config() {
        // threshold <= 0
        assert!(
            PageHinkley::new(PageHinkleyConfig {
                threshold: 0.0,
                ..Default::default()
            })
            .is_err()
        );
        // threshold NaN
        assert!(
            PageHinkley::new(PageHinkleyConfig {
                threshold: f64::NAN,
                ..Default::default()
            })
            .is_err()
        );
        // warning_threshold > threshold
        assert!(
            PageHinkley::new(PageHinkleyConfig {
                threshold: 10.0,
                warning_threshold: 20.0,
                ..Default::default()
            })
            .is_err()
        );
        // warning_threshold < 0
        assert!(
            PageHinkley::new(PageHinkleyConfig {
                warning_threshold: -1.0,
                ..Default::default()
            })
            .is_err()
        );
        // alpha <= 0
        assert!(
            PageHinkley::new(PageHinkleyConfig {
                alpha: 0.0,
                ..Default::default()
            })
            .is_err()
        );
        // alpha > 1
        assert!(
            PageHinkley::new(PageHinkleyConfig {
                alpha: 1.5,
                ..Default::default()
            })
            .is_err()
        );
        // delta < 0
        assert!(
            PageHinkley::new(PageHinkleyConfig {
                delta: -1.0,
                ..Default::default()
            })
            .is_err()
        );
        // min_samples == 0
        assert!(
            PageHinkley::new(PageHinkleyConfig {
                min_samples: 0,
                ..Default::default()
            })
            .is_err()
        );
    }

    #[test]
    fn forgetting_factor_detects_drift() {
        // Both the forgetting (alpha < 1) and standard (alpha = 1) variants
        // should detect a sustained mean shift. The forgetting factor decays
        // old contributions, so for a single shift the standard variant is
        // typically faster — we only assert both detect the drift.
        let config_forgetting = PageHinkleyConfig {
            threshold: 5.0,
            warning_threshold: 0.0,
            alpha: 0.8,
            delta: 0.0,
            min_samples: 10,
        };
        let config_standard = PageHinkleyConfig {
            alpha: 1.0,
            ..config_forgetting
        };
        let mut ph_f = PageHinkley::new(config_forgetting).unwrap();
        let mut ph_s = PageHinkley::new(config_standard).unwrap();
        // Long stable phase at mean 0.
        for _ in 0..500 {
            ph_f.update(0.0).unwrap();
            ph_s.update(0.0).unwrap();
        }
        assert_eq!(ph_f.level(), DriftLevel::None);
        assert_eq!(ph_s.level(), DriftLevel::None);
        // Shift to mean 2.0.
        let mut steps_f = None;
        let mut steps_s = None;
        for i in 0..200 {
            let lv_f = ph_f.update(2.0).unwrap();
            let lv_s = ph_s.update(2.0).unwrap();
            if steps_f.is_none() && lv_f == DriftLevel::Drift {
                steps_f = Some(i);
            }
            if steps_s.is_none() && lv_s == DriftLevel::Drift {
                steps_s = Some(i);
            }
            if steps_f.is_some() && steps_s.is_some() {
                break;
            }
        }
        assert!(steps_f.is_some(), "forgetting variant should detect drift");
        assert!(steps_s.is_some(), "standard variant should detect drift");
    }

    #[test]
    fn ph_statistic_is_non_negative() {
        let mut ph = PageHinkley::default();
        let mut seed = 123u64;
        for _ in 0..200 {
            let v = next_unit(&mut seed) * 2.0 - 1.0;
            ph.update(v).unwrap();
            assert!(
                ph.ph_statistic() >= 0.0,
                "PH statistic should be non-negative, got {}",
                ph.ph_statistic()
            );
        }
    }

    #[test]
    fn mean_tracks_stream_average() {
        let mut ph = PageHinkley::default();
        let values = [1.0, 2.0, 3.0, 4.0, 5.0];
        for &v in &values {
            ph.update(v).unwrap();
        }
        assert!((ph.mean() - 3.0).abs() < 1e-9);
    }

    #[test]
    fn portable_state_restore_preserves_future_results() {
        let config = PageHinkleyConfig {
            threshold: 3.0,
            warning_threshold: 1.0,
            alpha: 0.95,
            delta: 0.01,
            min_samples: 5,
        };
        let mut original = PageHinkley::new(config.clone()).unwrap();
        for value in [0.0, 0.1, -0.1, 0.2, 0.0, 1.0, 1.5] {
            original.update(value).unwrap();
        }
        let state = original.export_state_v1();
        state.validate_state().unwrap();
        let mut restored = PageHinkley::restore_state_v1(config, state).unwrap();
        for value in [2.0, 2.0, 0.5, -0.25, 4.0] {
            assert_eq!(
                original.update(value).unwrap(),
                restored.update(value).unwrap()
            );
            assert_eq!(original.export_state_v1(), restored.export_state_v1());
        }
    }

    #[test]
    fn portable_state_rejects_mismatch_and_corruption() {
        let detector = PageHinkley::default();
        let wrong_config = PageHinkleyConfig {
            delta: 0.25,
            ..Default::default()
        };
        assert!(PageHinkley::restore_state_v1(wrong_config, detector.export_state_v1()).is_err());

        let mut corrupt = detector.export_state_v1();
        corrupt.minimum_cumulative_sum = 1.0;
        assert!(corrupt.validate_state().is_err());
        let mut corrupt = detector.export_state_v1();
        corrupt.version = 99;
        assert!(matches!(
            corrupt.validate_state(),
            Err(RillError::IncompatibleStateVersion { .. })
        ));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_roundtrip() {
        let mut ph = PageHinkley::new(PageHinkleyConfig {
            threshold: 15.0,
            warning_threshold: 7.0,
            alpha: 0.95,
            delta: 0.02,
            min_samples: 20,
        })
        .unwrap();
        for i in 0..50 {
            ph.update(i as f64 * 0.1).unwrap();
        }
        let json = serde_json::to_string(&ph).unwrap();
        let restored: PageHinkley = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.samples_seen(), 50);
        assert!((restored.mean() - ph.mean()).abs() < 1e-12);
        assert!((restored.cum_sum() - ph.cum_sum()).abs() < 1e-12);
        assert_eq!(restored.level(), ph.level());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn config_serde_roundtrip() {
        let config = PageHinkleyConfig {
            threshold: 42.0,
            warning_threshold: 21.0,
            alpha: 0.7,
            delta: 0.3,
            min_samples: 15,
        };
        let json = serde_json::to_string(&config).unwrap();
        let restored: PageHinkleyConfig = serde_json::from_str(&json).unwrap();
        assert!((restored.threshold - 42.0).abs() < 1e-12);
        assert!((restored.warning_threshold - 21.0).abs() < 1e-12);
        assert!((restored.alpha - 0.7).abs() < 1e-12);
        assert!((restored.delta - 0.3).abs() < 1e-12);
        assert_eq!(restored.min_samples, 15);
    }
}