nexus-stats-core 3.0.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
use crate::Condition;
use crate::math::MulAdd;

/// Smoothed error rate tracker.
///
/// Internally uses an EMA where success = 0.0 and failure = 1.0 (or
/// weighted). The smoothed value approximates the recent error rate.
///
/// # Use Cases
/// - API error rate monitoring
/// - Exchange rejection rate tracking
/// - Weighted severity tracking (critical failures count more)
///
/// # Weighted outcomes
///
/// `update_weighted(false, 2.0)` feeds 2.0 to the EMA (a failure that
/// counts double). With weights > 1.0, the smoothed "rate" can exceed
/// 1.0 — it becomes a severity-weighted signal rather than a pure rate.
#[derive(Debug, Clone)]
pub struct ErrorRateF64 {
    alpha: f64,
    one_minus_alpha: f64,
    value: f64,
    threshold: f64,
    count: u64,
    min_samples: u64,
}

/// Builder for [`ErrorRateF64`].
#[derive(Debug, Clone)]
pub struct ErrorRateF64Builder {
    alpha: Option<f64>,
    threshold: Option<f64>,
    min_samples: u64,
}

impl ErrorRateF64 {
    /// Creates a builder.
    #[inline]
    #[must_use]
    pub fn builder() -> ErrorRateF64Builder {
        ErrorRateF64Builder {
            alpha: None,
            threshold: None,
            min_samples: 1,
        }
    }

    /// Updates with an outcome with default weight 1.0.
    #[inline]
    #[must_use]
    pub fn update(&mut self, success: bool) -> Option<Condition> {
        // Weight 1.0 is always finite — bypass validation.
        self.update_weighted(success, 1.0).unwrap()
    }

    /// Updates with an outcome with a severity weight.
    ///
    /// Success feeds `0.0`, failure feeds `weight`. The EMA smooths
    /// this signal. With `weight=1.0`, the smoothed value is the
    /// recent error rate in [0, 1]. With `weight > 1.0`, it can exceed 1.0.
    ///
    /// # Errors
    ///
    /// Returns `DataError::NotANumber` if the weight is NaN, or
    /// `DataError::Infinite` if the weight is infinite.
    #[inline]
    pub fn update_weighted(
        &mut self,
        success: bool,
        weight: f64,
    ) -> Result<Option<Condition>, crate::DataError> {
        check_finite!(weight);
        self.count += 1;

        let sample = if success { 0.0 } else { weight };

        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 {
            return Ok(None);
        }

        Ok(if self.value > self.threshold {
            Some(Condition::Degraded)
        } else {
            Some(Condition::Normal)
        })
    }

    /// Current smoothed error rate, or `None` if not primed.
    ///
    /// With unweighted `update()`, this is in [0.0, 1.0].
    /// With weighted outcomes, it may exceed 1.0.
    #[inline]
    #[must_use]
    pub fn error_rate(&self) -> Option<f64> {
        if self.count >= self.min_samples {
            Some(self.value)
        } else {
            None
        }
    }

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

    /// Whether enough data has been collected.
    #[inline]
    #[must_use]
    pub fn is_primed(&self) -> bool {
        self.count >= self.min_samples
    }

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

    /// Updates the error rate threshold without resetting state.
    ///
    /// # Errors
    ///
    /// Threshold must be >= 0.
    #[inline]
    pub fn reconfigure_threshold(&mut self, threshold: f64) -> Result<(), crate::ConfigError> {
        if threshold < 0.0 {
            return Err(crate::ConfigError::Invalid(
                "threshold must be non-negative",
            ));
        }
        self.threshold = threshold;
        Ok(())
    }
}

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

    /// Halflife for smoothing.
    #[inline]
    #[must_use]
    #[cfg(any(feature = "std", feature = "libm"))]
    pub fn halflife(mut self, halflife: f64) -> Self {
        let ln2 = core::f64::consts::LN_2;
        self.alpha = Some(1.0 - crate::math::exp(-ln2 / halflife));
        self
    }

    /// Span for smoothing.
    #[inline]
    #[must_use]
    pub fn span(mut self, n: u64) -> Self {
        self.alpha = Some(2.0 / (n as f64 + 1.0));
        self
    }

    /// Error rate threshold. Degraded when smoothed rate exceeds this.
    #[inline]
    #[must_use]
    pub fn threshold(mut self, threshold: f64) -> Self {
        self.threshold = Some(threshold);
        self
    }

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

    /// Builds the error rate tracker.
    ///
    /// # Errors
    ///
    /// - Alpha and threshold must have been set.
    /// - Alpha must be in (0, 1) exclusive.
    /// - Threshold must be non-negative.
    #[inline]
    pub fn build(self) -> Result<ErrorRateF64, crate::ConfigError> {
        let alpha = self.alpha.ok_or(crate::ConfigError::Missing("alpha"))?;
        let threshold = self
            .threshold
            .ok_or(crate::ConfigError::Missing("threshold"))?;
        if !(alpha > 0.0 && alpha < 1.0) {
            return Err(crate::ConfigError::Invalid("alpha must be in (0, 1)"));
        }
        if threshold < 0.0 {
            return Err(crate::ConfigError::Invalid(
                "threshold must be non-negative",
            ));
        }

        Ok(ErrorRateF64 {
            alpha,
            one_minus_alpha: 1.0 - alpha,
            value: 0.0,
            threshold,
            count: 0,
            min_samples: self.min_samples,
        })
    }
}

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

    #[test]
    fn all_success_is_healthy() {
        let mut er = ErrorRateF64::builder()
            .alpha(0.3)
            .threshold(0.05)
            .build()
            .unwrap();

        for _ in 0..100 {
            assert_eq!(er.update(true), Some(Condition::Normal));
        }
    }

    #[test]
    fn all_failure_is_degraded() {
        let mut er = ErrorRateF64::builder()
            .alpha(0.3)
            .threshold(0.05)
            .build()
            .unwrap();

        for _ in 0..50 {
            let _ = er.update(false);
        }
        assert_eq!(er.update(false), Some(Condition::Degraded));
    }

    #[test]
    fn threshold_crossing() {
        let mut er = ErrorRateF64::builder()
            .alpha(0.3)
            .threshold(0.5)
            .build()
            .unwrap();

        // All success — should be healthy
        for _ in 0..20 {
            let _ = er.update(true);
        }
        assert_eq!(er.update(true), Some(Condition::Normal));

        // All failure — should become degraded
        for _ in 0..50 {
            let _ = er.update(false);
        }
        assert_eq!(er.update(false), Some(Condition::Degraded));
    }

    #[test]
    fn weighted_failure_triggers_faster() {
        let mut light = ErrorRateF64::builder()
            .alpha(0.5)
            .threshold(0.5)
            .build()
            .unwrap();
        let mut heavy = ErrorRateF64::builder()
            .alpha(0.5)
            .threshold(0.5)
            .build()
            .unwrap();

        // Both start healthy
        for _ in 0..10 {
            let _ = light.update(true);
            let _ = heavy.update(true);
        }

        // One weighted failure
        let _ = light.update_weighted(false, 1.0).unwrap();
        let _ = heavy.update_weighted(false, 5.0).unwrap();

        let light_rate = light.error_rate().unwrap();
        let heavy_rate = heavy.error_rate().unwrap();

        assert!(
            heavy_rate > light_rate,
            "heavy ({heavy_rate}) should exceed light ({light_rate})"
        );
    }

    #[test]
    fn priming() {
        let mut er = ErrorRateF64::builder()
            .alpha(0.3)
            .threshold(0.05)
            .min_samples(5)
            .build()
            .unwrap();

        for _ in 0..4 {
            assert!(er.update(false).is_none());
        }
        assert!(er.update(false).is_some());
    }

    #[test]
    fn reset() {
        let mut er = ErrorRateF64::builder()
            .alpha(0.3)
            .threshold(0.05)
            .build()
            .unwrap();

        for _ in 0..10 {
            let _ = er.update(false);
        }
        er.reset();
        assert_eq!(er.count(), 0);
        assert!(er.error_rate().is_none());
    }

    #[test]
    fn reconfigure_threshold_changes_behavior() {
        let mut er = ErrorRateF64::builder()
            .alpha(0.1)
            .threshold(0.5)
            .build()
            .unwrap();

        // Drive to low error rate with all successes
        for _ in 0..50 {
            let _ = er.update(true);
        }
        let rate = er.error_rate().unwrap();
        assert!(
            rate < 0.5,
            "rate should be low after all successes, got {rate}"
        );
        assert_eq!(er.update(true), Some(Condition::Normal));

        // Lower threshold below the current rate
        er.reconfigure_threshold(0.0).unwrap();
        // Rate > 0.0 threshold now means degraded (any non-zero rate)
        // Feed a failure to push rate above 0
        assert_eq!(er.update(false), Some(Condition::Degraded));
    }

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

    #[test]
    fn allows_zero_threshold() {
        let er = ErrorRateF64::builder().alpha(0.3).threshold(0.0).build();
        assert!(er.is_ok());
    }

    #[test]
    fn rejects_negative_threshold() {
        let result = ErrorRateF64::builder().alpha(0.3).threshold(-0.1).build();
        assert!(matches!(result, Err(crate::ConfigError::Invalid(_))));
    }

    #[test]
    fn reconfigure_rejects_negative_threshold() {
        let mut er = ErrorRateF64::builder()
            .alpha(0.3)
            .threshold(0.5)
            .build()
            .unwrap();
        assert!(er.reconfigure_threshold(-0.1).is_err());
        assert!(er.reconfigure_threshold(0.0).is_ok());
    }

    #[test]
    fn rejects_nan_and_inf() {
        let mut er = ErrorRateF64::builder()
            .alpha(0.3)
            .threshold(0.5)
            .build()
            .unwrap();

        assert_eq!(
            er.update_weighted(false, f64::NAN).unwrap_err(),
            crate::DataError::NotANumber
        );
        assert_eq!(
            er.update_weighted(false, f64::INFINITY).unwrap_err(),
            crate::DataError::Infinite
        );
        assert_eq!(
            er.update_weighted(false, f64::NEG_INFINITY).unwrap_err(),
            crate::DataError::Infinite
        );
        assert_eq!(er.count(), 0);
    }
}