alice-analytics 0.5.0

High-performance telemetry & probabilistic statistical estimation — HyperLogLog++, DDSketch, Count-Min Sketch, local differential privacy, streaming anomaly detection
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
//! Degenerate-input contracts: what each public entry point does with an
//! empty, out-of-domain, non-finite or extreme input.
//!
//! The crate takes numbers off a live telemetry stream, so the inputs here
//! are not hypothetical: an upstream division by zero sends `inf`, a missing
//! sample sends `NaN`, a clock that has not been set sends a timestamp near
//! `u64::MAX`, and a configuration file can set a relative accuracy of 0.
//!
//! Each test states which of the three possible answers is the correct one
//! for that input and asserts it, rather than asserting only that nothing
//! panicked:
//!
//! * **a value** — the input is inside the contract and has a defined answer
//!   (an empty estimator returns its documented neutral value; a magnitude
//!   beyond the accurate range is filed in the edge bin, keeping its rank but
//!   losing the α bound);
//! * **a saturated value** — the input is outside the representable range and
//!   the answer is the nearest representable one;
//! * **a panic** — the input violates a precondition the caller cannot
//!   recover from (a zero-width window), so the contract is a panic and
//!   `#[should_panic]` pins the message.
//!
//! "Does not panic" on its own is never the assertion: a counter that wraps
//! silently also does not panic, and that is the defect these tests exist to
//! keep out (see `bucket_index` in `src/sketch.rs`, where an `i32` overflow
//! panicked in a debug build and wrapped a magnitude into bin 0 in a release
//! one).
//!
//! The teeth are measured, not assumed: removing the `saturating_add` in
//! `bucket_index` or in `TumblingWindow::insert`, or making the zero-width
//! `push` return early instead of panicking, turns the corresponding test
//! red.
// `privacy` is deprecated (not differentially private) and still pinned here until 0.5.0 removes it
#![allow(deprecated)]
#![allow(clippy::float_cmp)]

use alice_analytics::anomaly::{
    CompositeDetector, EwmaDetector, MadDetector, StreamingMedian, ZScoreDetector,
};
use alice_analytics::pipeline::RingBuffer;
use alice_analytics::privacy::{
    LaplaceNoise, PrivacyBudget, PrivateAggregator, RandomizedResponse,
};
use alice_analytics::sketch::{CountMinSketch, DDSketch, HyperLogLog, Mergeable};
use alice_analytics::stats::{iqr, percentile_rank, quantile_sorted, StreamingStats};
use alice_analytics::streaming_ops::{
    ChangeRate, ExponentialMovingAverage, LinearRegression, SimpleMovingAverage,
};
use alice_analytics::window::{HierarchicalRollup, SlidingWindow, TumblingWindow};

// ---------------------------------------------------------------------------
// Preconditions the caller cannot recover from: a zero-width buffer
// ---------------------------------------------------------------------------
//
// `N` is a type parameter, so `N == 0` is a programming error rather than bad
// data: there is no value the call could return and no error the caller could
// handle. The contract is a panic, and these tests pin it so that a future
// change to a silent early return is a red test rather than a window that
// accepts values and forgets them.

#[test]
#[should_panic(expected = "SlidingWindow needs N > 0")]
fn sliding_window_of_width_zero_panics_on_push() {
    let mut w = SlidingWindow::<0>::new();
    w.push(1.0);
}

#[test]
#[should_panic(expected = "SimpleMovingAverage needs N > 0")]
fn simple_moving_average_of_width_zero_panics_on_observe() {
    let mut sma = SimpleMovingAverage::<0>::new();
    sma.observe(1.0);
}

#[test]
#[should_panic(expected = "RingBuffer needs N > 0")]
fn ring_buffer_of_capacity_zero_panics_on_push() {
    let mut rb = RingBuffer::<u8, 0>::new();
    let _ = rb.push(1);
}

/// Constructing one is still fine, and the read-only accessors answer for the
/// empty state: only the write paths above have a precondition.
#[test]
fn zero_width_buffers_construct_and_read_as_empty() {
    let w = SlidingWindow::<0>::new();
    assert_eq!(w.len(), 0);
    assert!(w.is_empty());
    assert_eq!(w.mean(), 0.0);
    assert_eq!(w.sum(), 0.0);

    let sma = SimpleMovingAverage::<0>::new();
    assert_eq!(sma.value(), 0.0);
    assert!(sma.is_empty());

    let mut rb = RingBuffer::<u8, 0>::new();
    assert_eq!(rb.capacity(), 0, "no usable slot");
    assert!(
        rb.is_full(),
        "a buffer with no usable slot is full from the start"
    );
    assert!(rb.is_empty());
    assert_eq!(rb.len(), 0);
    assert_eq!(rb.pop(), None);
    // N = 1 is the smallest instantiation that can be pushed to; it also has
    // no usable slot, but it refuses the push instead of panicking
    let mut rb1 = RingBuffer::<u8, 1>::new();
    assert_eq!(rb1.capacity(), 0);
    assert!(!rb1.push(7), "a full buffer refuses the item");
    assert_eq!(rb1.dropped(), 1);
}

// ---------------------------------------------------------------------------
// Documented argument contracts
// ---------------------------------------------------------------------------
//
// `ExponentialMovingAverage` already declares these panics in its `# Panics`
// section. They are pinned here because the assertion is the published
// contract: a smoothing factor outside (0, 1] is not a value the type can
// represent, and silently clamping it would produce an average that is not
// the one the caller asked for.

#[test]
#[should_panic(expected = "alpha must be in (0.0, 1.0]")]
fn ema_rejects_a_zero_smoothing_factor() {
    let _ = ExponentialMovingAverage::new(0.0);
}

#[test]
#[should_panic(expected = "alpha must be in (0.0, 1.0]")]
fn ema_rejects_a_smoothing_factor_above_one() {
    let _ = ExponentialMovingAverage::new(1.000_001);
}

/// `NaN` fails every comparison, so it is rejected by the same assertion
/// rather than slipping through as "not out of range".
#[test]
#[should_panic(expected = "alpha must be in (0.0, 1.0]")]
fn ema_rejects_a_nan_smoothing_factor() {
    let _ = ExponentialMovingAverage::new(f64::NAN);
}

#[test]
#[should_panic(expected = "span must be > 0")]
fn ema_rejects_a_zero_span() {
    let _ = ExponentialMovingAverage::from_span(0);
}

/// `alpha = 1` is the boundary and is inside the contract: the average is the
/// latest value.
#[test]
fn ema_accepts_the_boundary_factor_of_one() {
    let mut ema = ExponentialMovingAverage::new(1.0);
    ema.observe(3.0);
    ema.observe(11.0);
    assert_eq!(ema.value(), 11.0);
    // span = u64::MAX makes alpha the smallest positive value the formula can
    // produce; it is still inside (0, 1] and must not be rejected
    let tiny = ExponentialMovingAverage::from_span(u64::MAX);
    assert!(tiny.alpha() > 0.0 && tiny.alpha() <= 1.0);
}

// ---------------------------------------------------------------------------
// Non-finite and extreme magnitudes in a sketch
// ---------------------------------------------------------------------------

/// A non-finite sample is not a magnitude: it is counted on its own and
/// touches nothing else.
///
/// `inf` is the realistic shape of an upstream division by zero and `NaN` of
/// a missing sample. The classification follows `law::PointClass::NonFinite`
/// (feature `law`), which groups "NaN or infinite" and keeps such points out
/// of the summary — so `count`, `sum`, `min`, `max` and every bin stay as if
/// the sample had not arrived, and the ranks `quantile` computes remain the
/// ranks of the values that reached a bin.
#[test]
fn a_non_finite_sample_is_counted_on_its_own_and_touches_nothing_else() {
    let mut dd = DDSketch::new(0.01);
    for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
        dd.insert(v);
    }
    assert_eq!(dd.non_finite(), 3);
    assert_eq!(dd.count(), 0, "a non-finite sample is not summarised");
    assert_eq!(dd.sum(), 0.0, "and cannot poison the sum");
    assert_eq!(dd.mean(), 0.0);
    assert_eq!(
        dd.min(),
        f64::INFINITY,
        "the empty-state sentinel is untouched"
    );
    assert_eq!(dd.max(), f64::NEG_INFINITY);
    // the sketch is still empty, so the quantile is the empty-state answer
    assert_eq!(dd.quantile(0.5), 0.0);

    // mixed with finite company: the finite values keep their own ranks
    let mut dd = DDSketch::new(0.01);
    for v in [1.0, 2.0, 3.0] {
        dd.insert(v);
    }
    dd.insert(f64::NAN);
    dd.insert(f64::INFINITY);
    dd.insert(f64::NEG_INFINITY);
    assert_eq!(dd.count(), 3);
    assert_eq!(dd.non_finite(), 3);
    assert_eq!(dd.sum(), 6.0);
    assert_eq!(
        dd.min(),
        1.0,
        "an infinity must not widen the observed range"
    );
    assert_eq!(dd.max(), 3.0);
    for (q, want) in [(0.0f64, 1.0f64), (0.5, 2.0), (1.0, 3.0)] {
        let got = dd.quantile(q);
        assert!(
            (got - want).abs() <= 0.01 * want,
            "quantile({q}) = {got}, expected {want} within alpha"
        );
    }

    // merging adds the counter, clearing resets it
    let mut a = DDSketch::new(0.01);
    let mut b = DDSketch::new(0.01);
    a.insert(f64::NAN);
    a.insert(1.0);
    b.insert(f64::INFINITY);
    b.insert(2.0);
    a.merge(&b);
    assert_eq!((a.count(), a.non_finite()), (2, 2));
    a.clear();
    assert_eq!((a.count(), a.non_finite()), (0, 0));
}

/// Representative of the top bin of a `DDSketch`: the bin covers
/// `(γ^(i−1), γ^i]` with `γ^i` the top of `accurate_range()`, and the
/// representative is `2γ^i/(γ + 1)`.
fn top_edge_representative(alpha: f64, hi: f64) -> f64 {
    let gamma = (1.0 + alpha) / (1.0 - alpha);
    2.0 * hi / (gamma + 1.0)
}

/// `f64::MAX` takes the same path: a finite magnitude far above the accurate
/// range must also saturate rather than wrap.
#[test]
fn the_largest_finite_magnitudes_are_filed_in_the_edge_bins() {
    let mut dd = DDSketch::new(0.01);
    dd.insert(f64::MAX);
    dd.insert(f64::MIN_POSITIVE);
    dd.insert(-f64::MAX);
    assert_eq!(dd.count(), 3);
    let (_, hi) = dd.accurate_range();
    let top = top_edge_representative(0.01, hi);
    assert!((dd.quantile(1.0) / top - 1.0).abs() < 1e-9);
    assert!((dd.quantile(0.0) / -top - 1.0).abs() < 1e-9);
}

/// A relative accuracy of 0 is a degenerate configuration (γ = 1, so the
/// logarithm base is 1 and `inv_ln_gamma` is infinite). It must not panic:
/// the accurate range collapses to the single magnitude 1, which is what a
/// zero-width bin layout means, and the reported quantile stays finite.
#[test]
fn a_zero_relative_accuracy_collapses_the_range_instead_of_overflowing() {
    let mut dd = DDSketch::new(0.0);
    dd.insert(2.0);
    dd.insert(0.5);
    assert_eq!(dd.count(), 2);
    assert_eq!(dd.alpha(), 0.0);
    assert_eq!(dd.accurate_range(), (1.0, 1.0));
    assert!(dd.quantile(0.5).is_finite());
}

/// Quantile arguments outside the unit interval and `NaN` are clamped, not
/// rejected: the reported value stays inside the observed range.
#[test]
fn quantile_arguments_outside_the_unit_interval_are_clamped() {
    let mut dd = DDSketch::new(0.01);
    for v in 1..=100 {
        dd.insert(f64::from(v));
    }
    for q in [-1.0f64, 2.0, f64::NAN] {
        let v = dd.quantile(q);
        assert!(
            (1.0..=100.0).contains(&v),
            "quantile({q}) returned {v}, outside the observed [1, 100]"
        );
    }
}

/// Empty estimators report their documented neutral value rather than
/// dividing by zero.
#[test]
fn empty_estimators_report_their_neutral_value() {
    let dd = DDSketch::new(0.01);
    assert_eq!(dd.count(), 0);
    assert_eq!(dd.quantile(0.5), 0.0);

    let hll = HyperLogLog::new();
    assert_eq!(hll.cardinality(), 0.0);

    let cm = CountMinSketch::new();
    assert_eq!(cm.estimate(&7u64), 0);

    let st = StreamingStats::new();
    assert_eq!(st.count(), 0);
    assert_eq!(st.mean(), 0.0);
    assert_eq!(st.variance(), 0.0);
    assert_eq!(st.std_dev(), 0.0);
    // fewer than 3 (4) observations cannot define g₁ (excess kurtosis)
    assert_eq!(st.skewness(), 0.0);
    assert_eq!(st.kurtosis(), 0.0);

    let mut med = StreamingMedian::new();
    assert_eq!(med.count(), 0);
    assert_eq!(med.median(), 0.0);

    let z = ZScoreDetector::new(3.0);
    assert_eq!(z.variance(), 0.0);
    assert_eq!(z.std_dev(), 0.0);
    // with no observed spread the standardised distance is infinite, which is
    // the honest answer; the detector still reports no anomaly, because it
    // has not seen enough observations to judge
    assert_eq!(z.z_score(1.0), f64::INFINITY);
    assert!(!z.is_anomaly(1e9));

    let mut mad = MadDetector::new(3.0);
    assert_eq!(mad.mad(), 0.0);
    assert!(!mad.is_anomaly(1e9));

    let agg = PrivateAggregator::new(1.0);
    assert_eq!(agg.estimate_mean(), 0.0);
    assert_eq!(agg.estimate_sum(), 0.0);
    // the standard error scales as 1/√n, so with no observations the
    // uncertainty is unbounded: infinity, not a misleading 0
    assert_eq!(agg.standard_error(), f64::INFINITY);
}

/// Empty and short slices: `quantile_sorted` and `percentile_rank` return 0
/// for an empty input, and `iqr` returns `None` below the four points the
/// quartiles need.
#[test]
fn sorted_slice_statistics_handle_empty_and_short_inputs() {
    assert_eq!(quantile_sorted(&[], 0.5), 0.0);
    assert_eq!(percentile_rank(&[], 1.0), 0.0);
    assert_eq!(quantile_sorted(&[42.0], 0.5), 42.0);
    assert!(iqr(&[]).is_none());
    assert!(iqr(&[1.0, 2.0, 3.0]).is_none());
    assert!(iqr(&[1.0, 2.0, 3.0, 4.0]).is_some());
    // a NaN or out-of-range q is clamped into [0, 1] and indexes a real element
    for q in [-1.0f64, 2.0, f64::NAN] {
        let v = quantile_sorted(&[1.0, 2.0, 3.0], q);
        assert!((1.0..=3.0).contains(&v), "q {q} gave {v}");
    }
}

// ---------------------------------------------------------------------------
// Timestamps near the end of the u64 range
// ---------------------------------------------------------------------------

/// A clock that has not been set reports a timestamp near `u64::MAX`. Adding
/// the window width to it overflows; the correct answer is the saturated
/// boundary. Wrapping instead would move the boundary backwards and emit
/// windows whose `end_ms` precedes their `start_ms`, and would silently lose
/// or duplicate events.
#[test]
fn window_boundaries_saturate_at_the_end_of_the_timestamp_range() {
    let mut tw = TumblingWindow::new(1_000, 0.01);
    let mut emitted = 0u64;
    for (v, ts) in [(1.0, u64::MAX), (2.0, u64::MAX), (3.0, u64::MAX)] {
        if let Some(r) = tw.insert(v, ts) {
            assert_eq!(r.end_ms, u64::MAX, "the boundary must saturate, not wrap");
            assert!(
                r.end_ms >= r.start_ms,
                "a wrapped boundary gives end_ms {} < start_ms {}",
                r.end_ms,
                r.start_ms
            );
            emitted += r.event_count;
        }
    }
    let r = tw.flush();
    assert_eq!(r.end_ms, u64::MAX);
    assert!(r.end_ms >= r.start_ms);
    // the saturated boundary is reached by every insert at the very end of
    // the range, so a window closes each time; what must hold is that the
    // three events are accounted for exactly once between the emitted
    // windows and the final flush
    assert_eq!(
        emitted + r.event_count,
        3,
        "three inserts must be accounted for exactly once"
    );

    // The boolean that decides whether a window has ended is where the two
    // behaviours differ observably. With a window starting at `u64::MAX - 500`
    // the boundary is past the end of the range: a later timestamp that is
    // still inside the window must not close it. A wrapping `+` would compute
    // a boundary of 499 and close the window on every subsequent sample —
    // silently, in a release build, where the addition does not panic.
    let mut tw = TumblingWindow::new(1_000, 0.01);
    assert!(
        tw.insert(1.0, u64::MAX - 500).is_none(),
        "the first sample opens the window"
    );
    assert!(
        tw.insert(2.0, u64::MAX - 400).is_none(),
        "u64::MAX - 400 is inside the window that opened at u64::MAX - 500; \
         a wrapped boundary (499) would close it here"
    );
    // the boundary saturates to u64::MAX exactly, and the comparison is `>=`,
    // so a sample *at* u64::MAX does close the window
    assert!(tw.insert(3.0, u64::MAX).is_some());
    let r = tw.flush();
    assert_eq!(
        r.event_count, 1,
        "only the third sample is in the new window"
    );
    assert_eq!(r.end_ms, u64::MAX, "the boundary saturates");

    let mut hr = HierarchicalRollup::new(1, 2, 3, 0.01);
    hr.insert(1.0, u64::MAX);
    hr.insert(2.0, u64::MAX);
    assert_eq!(hr.level_count(), 3);
}

/// A width of 0 is clamped to 1 by the constructor, so the modulo inside
/// `insert` can never divide by zero.
#[test]
fn a_zero_window_width_is_clamped_to_one() {
    let mut tw = TumblingWindow::new(0, 0.01);
    tw.insert(1.0, 5);
    tw.insert(2.0, 9);
    let r = tw.flush();
    assert!(r.end_ms > r.start_ms);
}

/// Two samples with the same timestamp give no new rate (dt = 0): the last
/// rate is repeated rather than dividing by zero.
#[test]
fn a_repeated_timestamp_repeats_the_last_change_rate() {
    let mut cr = ChangeRate::new();
    assert_eq!(cr.observe(1.0, 10), None, "the first sample has no rate");
    assert_eq!(cr.observe(3.0, 20), Some(0.2));
    assert_eq!(
        cr.observe(999.0, 20),
        Some(0.2),
        "dt = 0 keeps the last rate"
    );
    // a timestamp going backwards saturates dt to 0 and behaves the same way
    assert_eq!(cr.observe(999.0, 5), Some(0.2));
}

/// One point cannot define a slope; the documented answer is 0 rather than a
/// division by a zero second moment.
#[test]
fn a_single_point_regression_reports_a_zero_slope() {
    let mut lr = LinearRegression::new();
    lr.observe(1.0, 2.0);
    assert_eq!(lr.slope(), 0.0);
    assert_eq!(lr.r_squared(), 0.0);
    assert_eq!(lr.intercept(), 2.0, "the intercept is the single y");
    assert_eq!(lr.predict(100.0), 2.0);
}

// ---------------------------------------------------------------------------
// Privacy parameters
// ---------------------------------------------------------------------------

/// ε = 0 means an infinite noise scale. The mechanism stays usable (the
/// sample is infinite or `NaN`, which is the honest answer for "no privacy
/// budget spent"), and the integer form saturates instead of wrapping.
#[test]
fn a_zero_epsilon_gives_an_infinite_scale_without_wrapping() {
    let mut ln = LaplaceNoise::with_seed(1.0, 0.0, 7);
    assert_eq!(ln.scale(), f64::INFINITY);
    let s = ln.sample();
    assert!(s.is_infinite(), "scale inf gives an infinite sample: {s}");

    // the i64 conversion saturates (Rust `as` semantics, pinned here because
    // the noise can exceed the i64 range by construction)
    let mut big = LaplaceNoise::with_seed(1e300, 1e-300, 7);
    let v = big.privatize_int(0);
    assert!(
        v == i64::MAX || v == i64::MIN,
        "expected saturation, got {v}"
    );
}

/// The truthfulness probability must be inside [0.5, 1]: below 0.5 the
/// estimator inverts the sign of every reported proportion.
///
/// The domain is enforced the way `ExponentialMovingAverage::new` enforces
/// its own — an assertion rather than a silent correction. Measured
/// precedent (`cargo test`, every boundary): that constructor rejects a
/// negative factor, `-0.0`, `0.0`, anything above `1.0` including
/// `1.0 + f64::EPSILON`, `NaN`, `inf` and `-inf`, and accepts everything from
/// `f64::MIN_POSITIVE` up to and including `1.0`. A single `&&` of two
/// comparisons covers the non-finite cases for free, because every comparison
/// against `NaN` is false.
#[test]
fn a_randomized_response_accepts_its_whole_domain_and_only_that() {
    // the closed ends are inside the domain: 0.5 means "always answer at
    // random" (which `new(0.0)` produces exactly), 1.0 means "always truthful"
    assert_eq!(RandomizedResponse::with_probability(0.5, 7).p_true(), 0.5);
    assert_eq!(RandomizedResponse::with_probability(1.0, 7).p_true(), 1.0);
    // and the value is kept, not corrected
    assert_eq!(RandomizedResponse::with_probability(0.75, 7).p_true(), 0.75);

    // p_true = 0.5 carries no information about the input, so the estimator
    // returns the prior 0.5 rather than dividing by zero
    assert_eq!(RandomizedResponse::estimate_proportion(0.5, 10, 5), 0.5);
    // no responses at all: 0, not 0/0
    assert_eq!(RandomizedResponse::estimate_proportion(0.75, 0, 0), 0.0);
}

#[test]
#[should_panic(expected = "p_true must be in [0.5, 1.0]")]
fn a_randomized_response_rejects_a_probability_below_the_domain() {
    let _ = RandomizedResponse::with_probability(0.0, 7);
}

#[test]
#[should_panic(expected = "p_true must be in [0.5, 1.0]")]
fn a_randomized_response_rejects_a_probability_above_the_domain() {
    let _ = RandomizedResponse::with_probability(2.0, 7);
}

/// ⚠️ Until 2026-10-07 this was the one input the old `clamp(0.5, 1.0)` let
/// through: `f64::clamp` returns `NaN` when the value is `NaN`, so a
/// misconfigured probability was not corrected and `p_true()` reported `NaN`.
#[test]
#[should_panic(expected = "p_true must be in [0.5, 1.0]")]
fn a_randomized_response_rejects_a_nan_probability() {
    let _ = RandomizedResponse::with_probability(f64::NAN, 7);
}

#[test]
#[should_panic(expected = "p_true must be in [0.5, 1.0]")]
fn a_randomized_response_rejects_an_infinite_probability() {
    let _ = RandomizedResponse::with_probability(f64::INFINITY, 7);
}

/// A malformed spend request is refused and leaves the ledger byte for byte
/// unchanged.
///
/// This is the invariant the type exists for. Until 2026-10-07 the only guard
/// was the budget comparison `total + epsilon <= max`, which a negative value
/// passes trivially: `try_spend(-10.0)` returned `true` and *raised* the
/// remaining budget from 1 to 11, and `-inf` raised it to infinity — so a
/// caller could slip a negative epsilon between two honest queries and escape
/// the limit entirely. `NaN` and `+inf` were refused, but only as a side
/// effect of the comparison being false.
///
/// Refusal is asserted on every field, not just on the returned `bool`: a
/// guard that returns `false` after charging the ledger would pass a
/// `bool`-only test.
#[test]
fn a_malformed_spend_is_refused_and_leaves_the_ledger_untouched() {
    for bad in [
        -10.0f64,
        -f64::MIN_POSITIVE,
        f64::INFINITY,
        f64::NEG_INFINITY,
        f64::NAN,
    ] {
        let mut b = PrivacyBudget::new(1.0);
        // spend something first, so "untouched" is distinguishable from "reset"
        assert!(b.try_spend(0.25));
        let (spent, remaining, queries) = (b.spent(), b.remaining(), b.query_count());
        assert_eq!((spent, remaining, queries), (0.25, 0.75, 1));

        assert!(!b.try_spend(bad), "{bad:e} must be refused");
        assert_eq!(b.spent(), spent, "{bad:e} moved `spent`");
        assert_eq!(b.remaining(), remaining, "{bad:e} moved `remaining`");
        assert_eq!(b.query_count(), queries, "{bad:e} counted a query");
        assert!(!b.is_exhausted(), "{bad:e} changed exhaustion");
    }
}

/// Zero is well formed — it charges nothing and counts a query — and the
/// limit is enforced at the boundary.
#[test]
fn a_well_formed_spend_is_monotone_and_bounded() {
    let mut b = PrivacyBudget::new(1.0);
    assert_eq!(b.remaining(), 1.0);

    // 0.0 and -0.0 are both zero; `-0.0 < 0.0` is false in IEEE 754, so both
    // are accepted and neither moves the ledger
    for zero in [0.0f64, -0.0] {
        assert!(b.try_spend(zero), "{zero:e} is a well-formed request");
        assert_eq!(b.spent(), 0.0);
        assert_eq!(b.remaining(), 1.0);
    }
    assert_eq!(b.query_count(), 2, "a zero spend still counts as a query");

    assert!(b.try_spend(0.5));
    assert_eq!(b.spent(), 0.5);
    assert_eq!(b.remaining(), 0.5);

    assert!(!b.try_spend(0.75), "over budget is refused");
    assert_eq!(b.spent(), 0.5, "the refused amount is not charged");
    assert_eq!(b.remaining(), 0.5);

    // exactly the remainder fits, and then the budget is exhausted
    assert!(b.try_spend(0.5));
    assert_eq!(b.remaining(), 0.0);
    assert!(b.is_exhausted());
    assert!(!b.try_spend(f64::EPSILON), "nothing fits once exhausted");
    // ⚠️ a request below the ulp of the accumulated total is absorbed by the
    // addition and therefore accepted: `1.0 + f64::MIN_POSITIVE` rounds back
    // to `1.0`, so the comparison passes. It charges nothing, which is why
    // this is a property of f64 rather than a hole in the limit
    assert!(b.try_spend(f64::MIN_POSITIVE));
    assert_eq!(b.spent(), 1.0, "an absorbed request charges nothing");
    assert_eq!(b.remaining(), 0.0);

    // a budget that starts non-positive accepts nothing above zero
    let mut none = PrivacyBudget::new(-1.0);
    assert!(!none.try_spend(0.5));
    assert_eq!(none.spent(), 0.0);
    assert_eq!(none.query_count(), 0);
}

/// `EwmaDetector` enforces the same smoothing-factor domain as
/// `ExponentialMovingAverage::new`, and the value it stores is the one that
/// was passed.
#[test]
fn ewma_detector_accepts_its_whole_domain_and_only_that() {
    // the closed upper end is inside the domain, and so is anything above 0
    for alpha in [f64::MIN_POSITIVE, 1e-9, 0.0005, 0.3, 1.0] {
        let d = EwmaDetector::new(alpha, 3.0);
        assert_eq!(
            d.alpha(),
            alpha,
            "the factor must be stored as given, not corrected"
        );
    }
    // the setter carries the same invariant, or the constructor's check would
    // be defeatable after the fact
    let mut d = EwmaDetector::new(0.3, 3.0);
    d.set_alpha(1.0);
    assert_eq!(d.alpha(), 1.0);
}

/// ⚠️ Until 2026-10-07 `alpha.clamp(0.001, 1.0)` turned both of these into
/// `0.001`, which is why `-1.0` and `0.0` produced byte-identical detectors.
#[test]
#[should_panic(expected = "EwmaDetector alpha must be in (0.0, 1.0]")]
fn ewma_detector_rejects_a_zero_smoothing_factor() {
    let _ = EwmaDetector::new(0.0, 3.0);
}

#[test]
#[should_panic(expected = "EwmaDetector alpha must be in (0.0, 1.0]")]
fn ewma_detector_rejects_a_negative_smoothing_factor() {
    let _ = EwmaDetector::new(-1.0, 3.0);
}

#[test]
#[should_panic(expected = "EwmaDetector alpha must be in (0.0, 1.0]")]
fn ewma_detector_rejects_a_smoothing_factor_above_one() {
    let _ = EwmaDetector::new(2.0, 3.0);
}

/// ⚠️ The input the old clamp let through, and the worst of the set: `NaN`
/// propagated into `ewma` / `std_dev` / `anomaly_score`, and because every
/// comparison against `NaN` is false, `is_anomaly` then answered **`false`**
/// for every value — the detector was silently switched off. An infinite
/// score reads as "anomalous"; `false` reads as "normal".
#[test]
#[should_panic(expected = "EwmaDetector alpha must be in (0.0, 1.0]")]
fn ewma_detector_rejects_a_nan_smoothing_factor() {
    let _ = EwmaDetector::new(f64::NAN, 3.0);
}

#[test]
#[should_panic(expected = "EwmaDetector alpha must be in (0.0, 1.0]")]
fn ewma_detector_setter_rejects_a_nan_smoothing_factor() {
    let mut d = EwmaDetector::new(0.3, 3.0);
    d.set_alpha(f64::NAN);
}

/// `CompositeDetector::with_thresholds` forwards the factor, so it inherits
/// the same contract rather than having a second, looser one.
#[test]
#[should_panic(expected = "EwmaDetector alpha must be in (0.0, 1.0]")]
fn composite_detector_inherits_the_smoothing_factor_domain() {
    let _ = CompositeDetector::with_thresholds(3.0, f64::NAN, 2.5, 3.0);
}

/// A series with no spread scores every deviation as infinitely anomalous,
/// and the value equal to the level as `0.0`.
///
/// ⚠️ This is **not** specific to `alpha = 1.0`: a constant stream collapses
/// the variance estimate at any factor. Both cases are asserted so that the
/// contract is read as "zero spread ⇒ infinite score" rather than as an
/// artefact of the boundary — which is why the boundary is kept legal (the
/// crate's own `ExponentialMovingAverage::new` accepts `1.0`) instead of
/// being asserted away.
#[test]
fn a_series_with_no_spread_scores_any_deviation_as_infinite() {
    // alpha = 1.0: no smoothing, so the level is the latest value
    let mut fast = EwmaDetector::new(1.0, 3.0);
    for i in 0..10 {
        fast.observe(f64::from(i));
    }
    assert_eq!(
        fast.ewma(),
        9.0,
        "alpha = 1 tracks the latest value exactly"
    );
    assert_eq!(fast.std_dev(), 0.0);
    assert_eq!(fast.anomaly_score(100.0), f64::INFINITY);
    assert_eq!(
        fast.anomaly_score(9.0),
        0.0,
        "the level itself is not a deviation"
    );
    assert!(fast.is_anomaly(100.0));
    assert!(!fast.is_anomaly(9.0));

    // alpha = 0.3 on a constant stream: an ordinary configuration reaching the
    // same state
    let mut slow = EwmaDetector::new(0.3, 3.0);
    for _ in 0..50 {
        slow.observe(7.0);
    }
    assert_eq!(slow.ewma(), 7.0);
    assert_eq!(slow.std_dev(), 0.0);
    assert_eq!(slow.anomaly_score(8.0), f64::INFINITY);
    assert_eq!(slow.anomaly_score(7.0), 0.0);

    // an ordinary spread keeps the score finite, so the infinity above is the
    // zero-spread case and not the general answer
    let mut varied = EwmaDetector::new(0.3, 3.0);
    for i in 0..50 {
        varied.observe(f64::from(i % 7));
    }
    assert!(varied.std_dev() > 0.0);
    assert!(varied.anomaly_score(100.0).is_finite());
}

// ---------------------------------------------------------------------------
// The privacy parameter of a randomized response
// ---------------------------------------------------------------------------

/// `RandomizedResponse::new` validates the `epsilon` it is given, and derives
/// `p_true` over the whole of `[0, ∞)` without ever producing `NaN`.
///
/// The checked quantity is the input: `p_true` is derived from it. The upper
/// end is not cut off, because the old overflow was a property of the
/// algebraic form rather than of the domain — `p = e^ε/(1 + e^ε)` returned
/// `NaN` for `ε ≳ 709.79` (`inf/inf`), while the equivalent
/// `p = 1/(1 + e^(−ε))` returns the limit `1.0`.
#[cfg(feature = "std")] // `RandomizedResponse::new` is std-only
#[test]
fn a_randomized_response_epsilon_maps_onto_its_whole_domain() {
    // ε = 0 is "always answer at random", the same meaningful end that
    // `with_probability(0.5)` accepts
    assert_eq!(RandomizedResponse::new(0.0).p_true(), 0.5);
    assert_eq!(RandomizedResponse::new(-0.0).p_true(), 0.5);
    // the textbook values
    assert!((RandomizedResponse::new(1.0).p_true() - 0.731_058_578_630_004_9).abs() < 1e-15);

    // monotone in ε, and inside the domain that `with_probability` enforces
    let mut previous = 0.5;
    for e in [
        0.0f64, 0.25, 0.5, 1.0, 3.0, 10.0, 50.0, 100.0, 709.0, 710.0, 1e3, 1e300,
    ] {
        let p = RandomizedResponse::new(e).p_true();
        assert!(!p.is_nan(), "epsilon {e:e} produced NaN");
        assert!(
            (0.5..=1.0).contains(&p),
            "epsilon {e:e} produced p_true {p}, outside the domain              with_probability accepts"
        );
        assert!(
            p >= previous,
            "p_true must not decrease: {e:e} gave {p} after {previous}"
        );
        previous = p;
        // the same value must be constructible through the other path
        let _ = RandomizedResponse::with_probability(p, 1);
    }
    // ⚠️ the limit, where the old form returned NaN
    assert_eq!(RandomizedResponse::new(710.0).p_true(), 1.0);
    assert_eq!(RandomizedResponse::new(f64::MAX).p_true(), 1.0);
}

/// ⚠️ A negative ε used to return a detector whose `p_true` was below 0.5
/// (measured: `new(-5.0)` gave `6.69e-3`), which inverts the sign of every
/// proportion `estimate_proportion` reports.
#[cfg(feature = "std")] // `RandomizedResponse::new` is std-only
#[test]
#[should_panic(expected = "epsilon must be finite and non-negative")]
fn a_randomized_response_rejects_a_negative_epsilon() {
    let _ = RandomizedResponse::new(-5.0);
}

#[cfg(feature = "std")] // `RandomizedResponse::new` is std-only
#[test]
#[should_panic(expected = "epsilon must be finite and non-negative")]
fn a_randomized_response_rejects_a_nan_epsilon() {
    let _ = RandomizedResponse::new(f64::NAN);
}

#[cfg(feature = "std")] // `RandomizedResponse::new` is std-only
#[test]
#[should_panic(expected = "epsilon must be finite and non-negative")]
fn a_randomized_response_rejects_an_infinite_epsilon() {
    let _ = RandomizedResponse::new(f64::INFINITY);
}

#[cfg(feature = "std")] // `RandomizedResponse::new` is std-only
#[test]
#[should_panic(expected = "epsilon must be finite and non-negative")]
fn a_randomized_response_rejects_a_negative_infinite_epsilon() {
    let _ = RandomizedResponse::new(f64::NEG_INFINITY);
}

/// `NaN` observations are total (no panic) and keep their place in the count.
#[test]
fn nan_observations_do_not_panic_the_estimators() {
    let mut st = StreamingStats::new();
    for _ in 0..8 {
        st.observe(f64::NAN);
    }
    assert_eq!(st.count(), 8, "NaN still counts as an observation");

    let mut med = StreamingMedian::new();
    med.push(f64::NAN);
    med.push(1.0);
    assert_eq!(med.count(), 2);
}

/// The bucket index saturates instead of overflowing, on a **finite** input.
///
/// Non-finite samples no longer reach `bucket_index`, so this is the oracle
/// that keeps the `saturating_add` there honest. The cast overflows whenever
/// `ln(value) / ln(γ)` exceeds `i32::MAX`, and `1/ln(γ)` grows without bound
/// as `alpha` approaches 0 — a small relative accuracy is enough on its own.
///
/// What the two behaviours produce is different in *value*, not only in
/// whether a debug build panics: saturating files the huge value in the top
/// bin, so it is still the largest; wrapping sends the index negative, the
/// `max(0)` files it in **bin 0**, and it becomes the smallest. The top
/// order statistic is therefore the discriminator, and it works in a release
/// build where the addition does not panic.
#[test]
fn an_extreme_finite_magnitude_saturates_the_bucket_index() {
    let alpha = 1e-9;
    let mut dd = DDSketch::new(alpha);
    dd.insert(1.0);
    dd.insert(1e300);
    assert_eq!(dd.count(), 2);
    assert_eq!(dd.non_finite(), 0, "1e300 is finite");

    let (_, hi) = dd.accurate_range();
    let top = top_edge_representative(alpha, hi);
    let q_top = dd.quantile(1.0);
    assert!(
        q_top > 1.0,
        "the largest sample must stay the largest: a wrapped index files it \
         in bin 0 and reports {q_top} (= the smallest observed value)"
    );
    assert!(
        (q_top / top - 1.0).abs() < 1e-9,
        "expected the top edge-bin representative {top:e}, got {q_top:e}"
    );

    // alpha = 0 drives `1/ln(gamma)` to infinity, so even an ordinary
    // magnitude saturates the cast
    let mut dd = DDSketch::new(0.0);
    dd.insert(2.0);
    assert_eq!(dd.count(), 1);
    assert!(dd.quantile(0.5).is_finite());
}