asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Anytime-valid obligation leak monitor via e-processes.
//!
//! An e-process is a non-negative supermartingale under the null hypothesis
//! ("no leaks: all obligations resolve within their expected lifetime").
//! When the e-value exceeds 1/α, we reject the null with Type-I error ≤ α —
//! regardless of when we choose to stop monitoring (Ville's inequality).
//!
//! # Design
//!
//! Each monitored obligation contributes to the e-value based on how long
//! it has been pending relative to an expected resolution time:
//!
//! ```text
//! E_n = E_{n-1} × likelihood_ratio(obligation_n)
//! ```
//!
//! where the likelihood ratio compares:
//! - H0 (no leak): obligation age follows Exp(1/expected_lifetime)
//! - H1 (leak):   obligation is stuck (age grows without bound)
//!
//! # False-Alarm Guarantees
//!
//! By Ville's inequality: P(∃t: E_t ≥ 1/α | H0) ≤ α.
//! This holds for *any* stopping rule, including data-dependent ones.
//!
//! # Calibration
//!
//! The `expected_lifetime_ns` parameter should be set based on:
//! - Empirical profiling of obligation durations
//! - Budget deadlines for the containing region
//! - A conservative multiple of the median observed duration
//!
//! # Usage
//!
//! ```
//! use asupersync::obligation::eprocess::{LeakMonitor, MonitorConfig};
//!
//! let config = MonitorConfig {
//!     alpha: 0.01,              // 1% false-positive rate
//!     expected_lifetime_ns: 1_000_000, // 1ms expected resolution
//!     min_observations: 5,      // Don't alert before 5 observations
//! };
//! let mut monitor = LeakMonitor::new(config);
//!
//! // Feed observations: age in nanoseconds of each obligation at check time
//! monitor.observe(500_000);    // 0.5ms — normal
//! monitor.observe(800_000);    // 0.8ms — normal
//! monitor.observe(50_000_000); // 50ms  — suspicious
//!
//! if monitor.is_alert() {
//!     // E-value exceeded threshold: leak detected
//! }
//! ```

use std::fmt;

/// Configuration for the leak monitor.
#[derive(Debug, Clone, Copy)]
pub struct MonitorConfig {
    /// Type-I error bound (false-positive rate). Must be in (0, 1).
    /// The monitor guarantees P(false alarm) ≤ alpha under H0.
    pub alpha: f64,
    /// Expected obligation lifetime in nanoseconds under the null.
    /// Obligations pending longer than this are increasingly suspicious.
    pub expected_lifetime_ns: u64,
    /// Minimum observations before the monitor can trigger an alert.
    /// Prevents spurious alerts from small samples.
    pub min_observations: u64,
}

impl Default for MonitorConfig {
    fn default() -> Self {
        Self {
            alpha: 0.01,
            expected_lifetime_ns: 10_000_000, // 10ms
            min_observations: 3,
        }
    }
}

/// The state of the leak monitor's alert.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlertState {
    /// No evidence of leaks.
    Clear,
    /// E-value is elevated but below threshold.
    Watching,
    /// E-value exceeds 1/α: leak detected with bounded false-positive rate.
    Alert,
}

impl fmt::Display for AlertState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Clear => f.write_str("clear"),
            Self::Watching => f.write_str("watching"),
            Self::Alert => f.write_str("ALERT"),
        }
    }
}

/// An anytime-valid leak monitor using e-processes.
///
/// The monitor accumulates evidence against the null hypothesis
/// ("obligations are being resolved on time") via multiplicative
/// likelihood ratios. When evidence is strong enough, it raises
/// an alert with provable Type-I error control.
#[derive(Debug)]
pub struct LeakMonitor {
    /// Configuration.
    config: MonitorConfig,
    /// Current e-value (product of likelihood ratios).
    /// Starts at 1.0 (no evidence).
    e_value: f64,
    /// Rejection threshold: 1/alpha.
    threshold: f64,
    /// Number of observations so far.
    observations: u64,
    /// Running sum of log-likelihood ratios (for numerical stability).
    log_e_value: f64,
    /// Peak e-value observed (for diagnostics).
    peak_e_value: f64,
    /// Number of times alert was triggered.
    alert_count: u64,
}

impl LeakMonitor {
    /// Creates a new monitor with the given configuration.
    ///
    /// # Panics
    ///
    /// Panics if `alpha` is not in (0, 1) or `expected_lifetime_ns` is 0.
    #[must_use]
    pub fn new(config: MonitorConfig) -> Self {
        assert!(
            config.alpha > 0.0 && config.alpha < 1.0,
            "alpha must be in (0, 1), got {}",
            config.alpha
        );
        assert!(
            config.expected_lifetime_ns > 0,
            "expected_lifetime_ns must be > 0"
        );

        let threshold = 1.0 / config.alpha;

        Self {
            config,
            e_value: 1.0,
            threshold,
            observations: 0,
            log_e_value: 0.0,
            peak_e_value: 1.0,
            alert_count: 0,
        }
    }

    /// Observes an obligation's age (time since reservation, in nanoseconds).
    ///
    /// Updates the e-value with the likelihood ratio for this observation.
    /// Under H0 (no leak), obligation ages follow Exp(λ) where
    /// λ = 1/expected_lifetime. Under H1 (leak), ages are unbounded.
    ///
    /// The likelihood ratio at each step is:
    /// ```text
    /// LR = f_1(x) / f_0(x)
    /// ```
    /// We use a mixture alternative where H1 spreads mass more uniformly,
    /// giving LR = max(1, x / expected_lifetime).
    ///
    /// This ensures the e-process is a non-negative supermartingale under H0.
    pub fn observe(&mut self, age_ns: u64) {
        let was_alert = self.is_alert();
        self.observations += 1;

        #[allow(clippy::cast_precision_loss)]
        let ratio = if self.config.expected_lifetime_ns == 0 {
            0.0
        } else {
            age_ns as f64 / self.config.expected_lifetime_ns as f64
        };

        // Likelihood ratio: evidence grows when age exceeds expected.
        // We use a safe mixture: LR = max(1, ratio).
        // Under H0 (exponential): E[max(1, X/μ)] ≤ 1 + 1/e ≈ 1.37
        // To make it a proper supermartingale, we normalize:
        // LR = max(1, ratio) / (1 + 1/e)
        //
        // More precisely, for Exp(1/μ):
        //   E[max(1, X/μ)] = 1 × P(X≤μ) + E[X/μ | X>μ] × P(X>μ)
        //                   = (1 - e^{-1}) + (1 + 1) × e^{-1}
        //                   = 1 - 1/e + 2/e = 1 + 1/e
        //
        // So normalizing by (1 + 1/e) gives E[LR] ≤ 1 under H0.
        let normalizer = 1.0 + (-1.0_f64).exp(); // 1 + 1/e ≈ 1.3679
        let lr = ratio.max(1.0) / normalizer;

        self.log_e_value += lr.ln();
        self.e_value = self.log_e_value.exp();

        if self.e_value > self.peak_e_value {
            self.peak_e_value = self.e_value;
        }

        if !was_alert && self.is_alert() {
            self.alert_count += 1;
        }
    }

    /// Returns the current alert state.
    #[must_use]
    pub fn alert_state(&self) -> AlertState {
        if self.observations < self.config.min_observations {
            return AlertState::Clear;
        }
        if self.e_value >= self.threshold {
            AlertState::Alert
        } else if self.e_value > 1.0 {
            AlertState::Watching
        } else {
            AlertState::Clear
        }
    }

    /// Returns true if the monitor is currently in alert state.
    #[must_use]
    pub fn is_alert(&self) -> bool {
        self.alert_state() == AlertState::Alert
    }

    /// Returns the current e-value.
    #[must_use]
    pub fn e_value(&self) -> f64 {
        self.e_value
    }

    /// Returns the rejection threshold (1/alpha).
    #[must_use]
    pub fn threshold(&self) -> f64 {
        self.threshold
    }

    /// Returns the number of observations.
    #[must_use]
    pub fn observations(&self) -> u64 {
        self.observations
    }

    /// Returns the peak e-value observed.
    #[must_use]
    pub fn peak_e_value(&self) -> f64 {
        self.peak_e_value
    }

    /// Returns the number of times alert was triggered.
    #[must_use]
    pub fn alert_count(&self) -> u64 {
        self.alert_count
    }

    /// Returns the configuration.
    #[must_use]
    pub fn config(&self) -> &MonitorConfig {
        &self.config
    }

    /// Resets the monitor to its initial state, preserving configuration.
    pub fn reset(&mut self) {
        self.e_value = 1.0;
        self.log_e_value = 0.0;
        self.peak_e_value = 1.0;
        self.observations = 0;
        self.alert_count = 0;
    }

    /// Returns a snapshot of the monitor state for diagnostics.
    #[must_use]
    pub fn snapshot(&self) -> MonitorSnapshot {
        MonitorSnapshot {
            e_value: self.e_value,
            threshold: self.threshold,
            observations: self.observations,
            alert_state: self.alert_state(),
            peak_e_value: self.peak_e_value,
            alert_count: self.alert_count,
        }
    }
}

/// Diagnostic snapshot of the monitor state.
#[derive(Debug, Clone)]
pub struct MonitorSnapshot {
    /// Current e-value.
    pub e_value: f64,
    /// Rejection threshold.
    pub threshold: f64,
    /// Number of observations.
    pub observations: u64,
    /// Current alert state.
    pub alert_state: AlertState,
    /// Peak e-value ever observed.
    pub peak_e_value: f64,
    /// Number of alert triggers.
    pub alert_count: u64,
}

impl fmt::Display for MonitorSnapshot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "LeakMonitor[{}]: e={:.4} threshold={:.1} obs={} peak={:.4} alerts={}",
            self.alert_state,
            self.e_value,
            self.threshold,
            self.observations,
            self.peak_e_value,
            self.alert_count,
        )
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    fn init_test(name: &str) {
        crate::test_utils::init_test_logging();
        crate::test_phase!(name);
    }

    fn default_config() -> MonitorConfig {
        MonitorConfig {
            alpha: 0.01,
            expected_lifetime_ns: 1_000_000, // 1ms
            min_observations: 3,
        }
    }

    // ---- Construction ---------------------------------------------------

    #[test]
    fn new_monitor_starts_clear() {
        init_test("new_monitor_starts_clear");
        let monitor = LeakMonitor::new(default_config());
        crate::assert_with_log!(
            monitor.alert_state() == AlertState::Clear,
            "initial state",
            AlertState::Clear,
            monitor.alert_state()
        );
        let e = monitor.e_value();
        crate::assert_with_log!((e - 1.0).abs() < f64::EPSILON, "initial e-value", 1.0, e);
        crate::assert_with_log!(
            monitor.observations() == 0,
            "observations",
            0,
            monitor.observations()
        );
        crate::test_complete!("new_monitor_starts_clear");
    }

    #[test]
    #[should_panic(expected = "alpha must be in (0, 1)")]
    fn alpha_zero_panics() {
        let config = MonitorConfig {
            alpha: 0.0,
            ..default_config()
        };
        let _m = LeakMonitor::new(config);
    }

    #[test]
    #[should_panic(expected = "alpha must be in (0, 1)")]
    fn alpha_one_panics() {
        let config = MonitorConfig {
            alpha: 1.0,
            ..default_config()
        };
        let _m = LeakMonitor::new(config);
    }

    #[test]
    #[should_panic(expected = "expected_lifetime_ns must be > 0")]
    fn zero_lifetime_panics() {
        let config = MonitorConfig {
            expected_lifetime_ns: 0,
            ..default_config()
        };
        let _m = LeakMonitor::new(config);
    }

    // ---- Normal observations stay clear ----------------------------------

    #[test]
    fn normal_observations_stay_clear() {
        init_test("normal_observations_stay_clear");
        let mut monitor = LeakMonitor::new(default_config());

        // Obligations resolving well within expected lifetime.
        for _ in 0..100 {
            monitor.observe(500_000); // 0.5ms < 1ms expected
        }

        let state = monitor.alert_state();
        crate::assert_with_log!(
            state == AlertState::Clear,
            "state after normal",
            AlertState::Clear,
            state
        );
        crate::assert_with_log!(!monitor.is_alert(), "not alert", false, monitor.is_alert());
        crate::test_complete!("normal_observations_stay_clear");
    }

    // ---- Suspicious observations trigger alert ---------------------------

    #[test]
    fn leaked_obligations_trigger_alert() {
        init_test("leaked_obligations_trigger_alert");
        let mut monitor = LeakMonitor::new(MonitorConfig {
            alpha: 0.01,
            expected_lifetime_ns: 1_000_000, // 1ms
            min_observations: 3,
        });

        // Obligations with ages way beyond expected: 100× expected lifetime.
        for _ in 0..10 {
            monitor.observe(100_000_000); // 100ms >> 1ms
        }

        let state = monitor.alert_state();
        crate::assert_with_log!(
            state == AlertState::Alert,
            "alert",
            AlertState::Alert,
            state
        );
        crate::assert_with_log!(monitor.is_alert(), "is_alert", true, monitor.is_alert());
        let alert_count = monitor.alert_count();
        crate::assert_with_log!(alert_count > 0, "alert count > 0", true, alert_count > 0);
        crate::test_complete!("leaked_obligations_trigger_alert");
    }

    #[test]
    fn alert_count_tracks_threshold_crossings_not_samples() {
        init_test("alert_count_tracks_threshold_crossings_not_samples");
        let mut monitor = LeakMonitor::new(MonitorConfig {
            alpha: 0.01,
            expected_lifetime_ns: 1_000_000,
            min_observations: 3,
        });

        for _ in 0..10 {
            monitor.observe(100_000_000);
        }
        crate::assert_with_log!(
            monitor.alert_count() == 1,
            "first alert episode counted once",
            1,
            monitor.alert_count()
        );

        monitor.reset();
        for _ in 0..5 {
            monitor.observe(100_000_000);
        }
        crate::assert_with_log!(
            monitor.alert_count() == 1,
            "post-reset alert episode counted once",
            1,
            monitor.alert_count()
        );
        crate::test_complete!("alert_count_tracks_threshold_crossings_not_samples");
    }

    // ---- Min observations gate -------------------------------------------

    #[test]
    fn alert_gated_by_min_observations() {
        init_test("alert_gated_by_min_observations");
        let mut monitor = LeakMonitor::new(MonitorConfig {
            alpha: 0.01,
            expected_lifetime_ns: 1_000,
            min_observations: 5,
        });

        // Even extreme values don't trigger before min_observations.
        monitor.observe(1_000_000_000);
        monitor.observe(1_000_000_000);
        let state = monitor.alert_state();
        crate::assert_with_log!(
            state == AlertState::Clear,
            "below min obs",
            AlertState::Clear,
            state
        );

        // After enough observations, alert triggers.
        for _ in 0..5 {
            monitor.observe(1_000_000_000);
        }
        let state = monitor.alert_state();
        crate::assert_with_log!(
            state == AlertState::Alert,
            "above min obs",
            AlertState::Alert,
            state
        );
        crate::test_complete!("alert_gated_by_min_observations");
    }

    // ---- Reset -----------------------------------------------------------

    #[test]
    fn reset_clears_state() {
        init_test("reset_clears_state");
        let mut monitor = LeakMonitor::new(default_config());

        for _ in 0..10 {
            monitor.observe(100_000_000);
        }
        crate::assert_with_log!(
            monitor.is_alert(),
            "alert before reset",
            true,
            monitor.is_alert()
        );

        monitor.reset();
        crate::assert_with_log!(
            !monitor.is_alert(),
            "clear after reset",
            false,
            monitor.is_alert()
        );
        crate::assert_with_log!(
            monitor.observations() == 0,
            "obs after reset",
            0,
            monitor.observations()
        );
        let e = monitor.e_value();
        crate::assert_with_log!(
            (e - 1.0).abs() < f64::EPSILON,
            "e-value after reset",
            1.0,
            e
        );
        crate::test_complete!("reset_clears_state");
    }

    // ---- Snapshot --------------------------------------------------------

    #[test]
    fn snapshot_captures_state() {
        init_test("snapshot_captures_state");
        let mut monitor = LeakMonitor::new(default_config());
        monitor.observe(500_000);

        let snap = monitor.snapshot();
        crate::assert_with_log!(snap.observations == 1, "observations", 1, snap.observations);
        let has_threshold = snap.threshold > 0.0;
        crate::assert_with_log!(has_threshold, "threshold", true, has_threshold);

        // Display impl works.
        let display = format!("{snap}");
        let has_leak = display.contains("LeakMonitor");
        crate::assert_with_log!(has_leak, "display", true, has_leak);
        crate::test_complete!("snapshot_captures_state");
    }

    // ---- Supermartingale property (statistical) ---------------------------

    #[test]
    fn supermartingale_property_under_null() {
        init_test("supermartingale_property_under_null");
        // Under H0, E[E_n | E_{n-1}] ≤ E_{n-1}.
        // We verify this empirically: with many normal observations,
        // the e-value should not systematically grow.
        let mut monitor = LeakMonitor::new(MonitorConfig {
            alpha: 0.01,
            expected_lifetime_ns: 1_000_000,
            min_observations: 3,
        });

        // Simulate 1000 observations with ages ≤ expected_lifetime
        // (drawn from the "easy half" of the exponential).
        // E-value should stay bounded.
        for i in 0u64..1000 {
            // Deterministic sequence that stays under expected lifetime.
            let age = ((i % 10) + 1) * 100_000; // 0.1ms to 1.0ms
            monitor.observe(age);
        }

        // Under H0 with these well-behaved observations, e-value should be ≤ 1.
        let e = monitor.e_value();
        let bounded = e <= 2.0; // Allow some slack for edge effects.
        crate::assert_with_log!(bounded, "e-value bounded", true, bounded);
        crate::assert_with_log!(
            !monitor.is_alert(),
            "no alert under H0",
            false,
            monitor.is_alert()
        );
        crate::test_complete!("supermartingale_property_under_null");
    }

    // ---- Deterministic ---------------------------------------------------

    #[test]
    fn deterministic_across_runs() {
        init_test("deterministic_across_runs");
        let config = default_config();
        let ages = [500_000u64, 1_000_000, 2_000_000, 100_000, 5_000_000];

        let mut m1 = LeakMonitor::new(config);
        let mut m2 = LeakMonitor::new(config);

        for &age in &ages {
            m1.observe(age);
            m2.observe(age);
        }

        let e1 = m1.e_value();
        let e2 = m2.e_value();
        crate::assert_with_log!((e1 - e2).abs() < f64::EPSILON, "deterministic", e1, e2);
        crate::test_complete!("deterministic_across_runs");
    }

    // ---- Display impls ---------------------------------------------------

    #[test]
    fn alert_state_display() {
        init_test("alert_state_display");
        let clear = format!("{}", AlertState::Clear);
        crate::assert_with_log!(clear == "clear", "clear display", "clear", clear);
        let watching = format!("{}", AlertState::Watching);
        crate::assert_with_log!(
            watching == "watching",
            "watching display",
            "watching",
            watching
        );
        let alert = format!("{}", AlertState::Alert);
        crate::assert_with_log!(alert == "ALERT", "alert display", "ALERT", alert);
        crate::test_complete!("alert_state_display");
    }

    // ── derive-trait coverage (wave 74) ──────────────────────────────────

    #[test]
    fn monitor_config_debug_clone_copy() {
        let c = MonitorConfig::default();
        let c2 = c; // Copy
        let c3 = c;
        assert!((c2.alpha - 0.01).abs() < 1e-10);
        assert_eq!(c3.min_observations, 3);
        let dbg = format!("{c:?}");
        assert!(dbg.contains("MonitorConfig"));
    }

    #[test]
    fn alert_state_debug_clone_copy_eq() {
        let s = AlertState::Clear;
        let s2 = s; // Copy
        let s3 = s;
        assert_eq!(s, s2);
        assert_eq!(s2, s3);
        assert_ne!(s, AlertState::Alert);
        let dbg = format!("{s:?}");
        assert!(dbg.contains("Clear"));
    }

    #[test]
    fn monitor_snapshot_debug_clone() {
        let ms = MonitorSnapshot {
            e_value: 1.5,
            threshold: 100.0,
            observations: 10,
            alert_state: AlertState::Watching,
            peak_e_value: 2.0,
            alert_count: 0,
        };
        let ms2 = ms;
        assert_eq!(ms2.observations, 10);
        assert_eq!(ms2.alert_state, AlertState::Watching);
        let dbg = format!("{ms2:?}");
        assert!(dbg.contains("MonitorSnapshot"));
    }
}