ftui-runtime 0.3.1

Elm-style runtime loop and subscriptions for FrankenTUI.
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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
#![forbid(unsafe_code)]

//! Anytime-valid throttle using e-process (test martingale) control.
//!
//! This module provides an adaptive recompute throttle for streaming workloads
//! (e.g., live log search). It uses a wealth-based betting strategy to decide
//! when accumulated evidence warrants a full recomputation, while providing
//! anytime-valid statistical guarantees.
//!
//! # Mathematical Model
//!
//! The throttle maintains a wealth process `W_t`:
//!
//! ```text
//! W_0 = 1
//! W_t = W_{t-1} × (1 + λ_t × (X_t − μ₀))
//! ```
//!
//! where:
//! - `X_t ∈ {0, 1}`: whether observation `t` is evidence for recompute
//!   (e.g., a log line matched the active search/filter query)
//! - `μ₀`: null hypothesis match rate — the "normal" baseline match frequency
//! - `λ_t ∈ (0, 1/μ₀)`: betting fraction (adaptive via GRAPA)
//!
//! When `W_t ≥ 1/α` (the e-value threshold), we reject H₀ ("results are
//! still fresh") and trigger recompute. After triggering, `W` resets to 1.
//!
//! # Key Invariants
//!
//! 1. **Supermartingale**: `E[W_t | W_{t-1}] ≤ W_{t-1}` under H₀
//! 2. **Anytime-valid Type I control**: `P(∃t: W_t ≥ 1/α) ≤ α` under H₀
//! 3. **Non-negative wealth**: `W_t ≥ 0` always
//! 4. **Bounded latency**: hard deadline forces recompute regardless of `W_t`
//!
//! # Failure Modes
//!
//! | Condition | Behavior | Rationale |
//! |-----------|----------|-----------|
//! | `μ₀ = 0` | Clamp to `μ₀ = ε` (1e-6) | Division by zero guard |
//! | `μ₀ ≥ 1` | Clamp to `1 − ε` | Degenerate: everything matches |
//! | `W_t` underflow | Clamp to `W_MIN` (1e-12) | Prevents permanent zero-lock |
//! | Hard deadline exceeded | Force recompute | Bounded worst-case latency |
//! | No observations | No change to `W_t` | Idle is not evidence |
//!
//! # Usage
//!
//! ```ignore
//! use ftui_runtime::eprocess_throttle::{EProcessThrottle, ThrottleConfig};
//!
//! let mut throttle = EProcessThrottle::new(ThrottleConfig::default());
//!
//! // On each log line push:
//! let matched = line.contains(&query);
//! let decision = throttle.observe(matched);
//! if decision.should_recompute {
//!     recompute_search_results();
//! }
//! ```

use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use web_time::{Duration, Instant};

/// Minimum wealth floor to prevent permanent zero-lock after adverse bets.
const W_MIN: f64 = 1e-12;

/// Minimum mu_0 to prevent division by zero.
const MU_0_MIN: f64 = 1e-6;

/// Maximum mu_0 to prevent degenerate all-match scenarios.
const MU_0_MAX: f64 = 1.0 - 1e-6;

// ---------------------------------------------------------------------------
// Monotonic counters (exported for observability dashboards / tests)
// ---------------------------------------------------------------------------

static EPROCESS_REJECTIONS_TOTAL: AtomicU64 = AtomicU64::new(0);

/// Total e-process rejections (monotonic counter for metrics export).
#[must_use]
pub fn eprocess_rejections_total() -> u64 {
    EPROCESS_REJECTIONS_TOTAL.load(Ordering::Relaxed)
}

/// Configuration for the e-process throttle.
#[derive(Debug, Clone)]
pub struct ThrottleConfig {
    /// Significance level `α`. Recompute triggers when `W_t ≥ 1/α`.
    /// Lower α → more conservative (fewer recomputes). Default: 0.05.
    pub alpha: f64,

    /// Prior null hypothesis match rate `μ₀`. The expected fraction of
    /// observations that are matches under "normal" conditions.
    /// Default: 0.1 (10% of log lines match).
    pub mu_0: f64,

    /// Initial betting fraction. Adaptive GRAPA updates this, but this
    /// sets the starting value. Must be in `(0, 1/(1 − μ₀))`.
    /// Default: 0.5.
    pub initial_lambda: f64,

    /// GRAPA learning rate for adaptive lambda. Higher → faster adaptation
    /// but noisier. Default: 0.1.
    pub grapa_eta: f64,

    /// Hard deadline: force recompute if this many milliseconds pass since
    /// last recompute, regardless of wealth. Default: 500ms.
    pub hard_deadline_ms: u64,

    /// Minimum observations between recomputes. Prevents rapid-fire
    /// recomputes when every line matches. Default: 8.
    pub min_observations_between: u64,

    /// Window size for empirical match rate estimation. Default: 64.
    pub rate_window_size: usize,

    /// Enable JSONL-compatible decision logging. Default: false.
    pub enable_logging: bool,
}

impl Default for ThrottleConfig {
    fn default() -> Self {
        Self {
            alpha: 0.05,
            mu_0: 0.1,
            initial_lambda: 0.5,
            grapa_eta: 0.1,
            hard_deadline_ms: 500,
            min_observations_between: 8,
            rate_window_size: 64,
            enable_logging: false,
        }
    }
}

/// Decision returned by the throttle on each observation.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ThrottleDecision {
    /// Whether to trigger recomputation now.
    pub should_recompute: bool,
    /// Current wealth (e-value). When `≥ 1/α`, triggers recompute.
    pub wealth: f64,
    /// Current adaptive betting fraction.
    pub lambda: f64,
    /// Empirical match rate over the sliding window.
    pub empirical_rate: f64,
    /// Whether the decision was forced by hard deadline.
    pub forced_by_deadline: bool,
    /// Observations since last recompute.
    pub observations_since_recompute: u64,
}

/// Decision log entry for observability.
#[derive(Debug, Clone)]
pub struct ThrottleLog {
    /// Timestamp of the observation.
    pub timestamp: Instant,
    /// Observation index (total count).
    pub observation_idx: u64,
    /// Whether this observation was a match (X_t = 1).
    pub matched: bool,
    /// Wealth before this observation.
    pub wealth_before: f64,
    /// Wealth after this observation.
    pub wealth_after: f64,
    /// Betting fraction used.
    pub lambda: f64,
    /// Empirical match rate.
    pub empirical_rate: f64,
    /// Action taken.
    pub action: &'static str,
    /// Time since last recompute (ms).
    pub time_since_recompute_ms: f64,
}

impl ThrottleDecision {
    /// Format this decision as a JSONL line for structured logging.
    #[must_use]
    pub fn to_jsonl(&self) -> String {
        format!(
            r#"{{"schema":"eprocess-throttle-v1","should_recompute":{},"wealth":{:.6},"lambda":{:.6},"empirical_rate":{:.6},"forced_by_deadline":{},"obs_since_recompute":{}}}"#,
            self.should_recompute,
            self.wealth,
            self.lambda,
            self.empirical_rate,
            self.forced_by_deadline,
            self.observations_since_recompute,
        )
    }
}

impl ThrottleLog {
    /// Format this log entry as a JSONL line for structured logging.
    #[must_use]
    pub fn to_jsonl(&self) -> String {
        format!(
            r#"{{"schema":"eprocess-log-v1","obs_idx":{},"matched":{},"wealth_before":{:.6},"wealth_after":{:.6},"lambda":{:.6},"empirical_rate":{:.6},"action":"{}","time_since_recompute_ms":{:.3}}}"#,
            self.observation_idx,
            self.matched,
            self.wealth_before,
            self.wealth_after,
            self.lambda,
            self.empirical_rate,
            self.action,
            self.time_since_recompute_ms,
        )
    }
}

/// Aggregate statistics for the throttle.
#[derive(Debug, Clone)]
pub struct ThrottleStats {
    /// Total observations processed.
    pub total_observations: u64,
    /// Total recomputes triggered.
    pub total_recomputes: u64,
    /// Recomputes forced by hard deadline.
    pub forced_recomputes: u64,
    /// Recomputes triggered by e-process threshold.
    pub eprocess_recomputes: u64,
    /// Current wealth.
    pub current_wealth: f64,
    /// Current lambda.
    pub current_lambda: f64,
    /// Current empirical match rate.
    pub empirical_rate: f64,
    /// Average observations between recomputes (0 if no recomputes yet).
    pub avg_observations_between_recomputes: f64,
}

/// Anytime-valid recompute throttle using e-process (test martingale) control.
///
/// See module-level docs for the mathematical model and guarantees.
#[derive(Debug)]
pub struct EProcessThrottle {
    config: ThrottleConfig,

    /// Current wealth W_t. Starts at 1, resets on recompute.
    wealth: f64,

    /// Current adaptive betting fraction λ_t.
    lambda: f64,

    /// Clamped mu_0 for safe arithmetic.
    mu_0: f64,

    /// Maximum lambda: `1 / (1 − μ₀)` minus small epsilon.
    lambda_max: f64,

    /// E-value threshold: `1 / α`.
    threshold: f64,

    /// Sliding window of recent observations for empirical rate.
    recent_matches: VecDeque<bool>,

    /// Total observation count.
    observation_count: u64,

    /// Observations since last recompute (or creation).
    observations_since_recompute: u64,

    /// Timestamp of last recompute (or creation).
    last_recompute: Instant,

    /// Total recomputes.
    total_recomputes: u64,

    /// Recomputes forced by deadline.
    forced_recomputes: u64,

    /// Recomputes triggered by e-process.
    eprocess_recomputes: u64,

    /// Sum of observations_since_recompute at each recompute (for averaging).
    cumulative_obs_at_recompute: u64,

    /// Decision logs (if logging enabled).
    logs: Vec<ThrottleLog>,
}

impl EProcessThrottle {
    /// Create a new throttle with the given configuration.
    pub fn new(config: ThrottleConfig) -> Self {
        Self::new_at(config, Instant::now())
    }

    /// Create a new throttle at a specific time (for deterministic testing).
    pub fn new_at(config: ThrottleConfig, now: Instant) -> Self {
        let mu_0 = config.mu_0.clamp(MU_0_MIN, MU_0_MAX);
        let lambda_max = 1.0 / mu_0 - 1e-6;
        let lambda = config.initial_lambda.clamp(1e-6, lambda_max);
        let threshold = 1.0 / config.alpha.max(1e-12);

        Self {
            config,
            wealth: 1.0,
            lambda,
            mu_0,
            lambda_max,
            threshold,
            recent_matches: VecDeque::new(),
            observation_count: 0,
            observations_since_recompute: 0,
            last_recompute: now,
            total_recomputes: 0,
            forced_recomputes: 0,
            eprocess_recomputes: 0,
            cumulative_obs_at_recompute: 0,
            logs: Vec::new(),
        }
    }

    /// Observe a single event. `matched` indicates whether this observation
    /// is evidence for recomputation (e.g., the log line matched the query).
    ///
    /// Returns a [`ThrottleDecision`] indicating whether to recompute.
    pub fn observe(&mut self, matched: bool) -> ThrottleDecision {
        self.observe_at(matched, Instant::now())
    }

    /// Observe at a specific time (for deterministic testing).
    pub fn observe_at(&mut self, matched: bool, now: Instant) -> ThrottleDecision {
        self.observation_count += 1;
        self.observations_since_recompute += 1;

        // Update sliding window
        self.recent_matches.push_back(matched);
        while self.recent_matches.len() > self.config.rate_window_size {
            self.recent_matches.pop_front();
        }

        let empirical_rate = self.empirical_match_rate();

        // Wealth update: W_t = W_{t-1} × (1 + λ × (X_t − μ₀))
        let x_t = if matched { 1.0 } else { 0.0 };
        let wealth_before = self.wealth;
        let multiplier = 1.0 + self.lambda * (x_t - self.mu_0);
        self.wealth = (self.wealth * multiplier).max(W_MIN);

        // GRAPA adaptive lambda update
        // Gradient of log-wealth w.r.t. lambda: (X_t - μ₀) / (1 + λ(X_t - μ₀))
        let denominator = 1.0 + self.lambda * (x_t - self.mu_0);
        if denominator.abs() > 1e-12 {
            let grad = (x_t - self.mu_0) / denominator;
            self.lambda = (self.lambda + self.config.grapa_eta * grad).clamp(1e-6, self.lambda_max);
        }

        // Check recompute conditions
        let time_since_recompute = now.saturating_duration_since(self.last_recompute);
        let hard_deadline_exceeded =
            time_since_recompute >= Duration::from_millis(self.config.hard_deadline_ms);
        let min_obs_met = self.observations_since_recompute >= self.config.min_observations_between;
        let wealth_exceeded = self.wealth >= self.threshold;

        let eprocess_triggered = wealth_exceeded && min_obs_met;
        let should_recompute = hard_deadline_exceeded || eprocess_triggered;
        let forced_by_deadline = hard_deadline_exceeded && !eprocess_triggered;

        let action = if should_recompute {
            if forced_by_deadline {
                "recompute_forced"
            } else {
                "recompute_eprocess"
            }
        } else {
            "observe"
        };

        // --- Tracing observability (bd-37a.5) ---
        let rejected = eprocess_triggered;
        let _span = tracing::debug_span!(
            "eprocess.update",
            test_id = "throttle",
            wealth_current = %self.wealth,
            wealth_threshold = %self.threshold,
            observation_count = self.observation_count,
            rejected = rejected,
        )
        .entered();

        tracing::debug!(
            target: "ftui.eprocess",
            wealth_before = %wealth_before,
            wealth_after = %self.wealth,
            lambda = %self.lambda,
            empirical_rate = %empirical_rate,
            matched = matched,
            eprocess_wealth = %self.wealth,
            observation_count = self.observation_count,
            action = %action,
            "wealth update"
        );

        if rejected {
            EPROCESS_REJECTIONS_TOTAL.fetch_add(1, Ordering::Relaxed);
            tracing::info!(
                target: "ftui.eprocess",
                wealth = %self.wealth,
                threshold = %self.threshold,
                observation_count = self.observation_count,
                observations_since_recompute = self.observations_since_recompute,
                "e-process rejection: significant finding"
            );
        }

        if forced_by_deadline && should_recompute {
            tracing::info!(
                target: "ftui.eprocess",
                deadline_ms = self.config.hard_deadline_ms,
                observation_count = self.observation_count,
                "hard deadline forced recompute"
            );
        }

        self.log_decision(
            now,
            matched,
            wealth_before,
            self.wealth,
            action,
            time_since_recompute,
        );

        if should_recompute {
            self.trigger_recompute(now, forced_by_deadline);
        }

        ThrottleDecision {
            should_recompute,
            wealth: self.wealth,
            lambda: self.lambda,
            empirical_rate,
            forced_by_deadline: should_recompute && forced_by_deadline,
            observations_since_recompute: self.observations_since_recompute,
        }
    }

    /// Manually trigger a recompute (e.g., when the query changes).
    /// Resets the e-process state.
    pub fn reset(&mut self) {
        self.reset_at(Instant::now());
    }

    /// Reset at a specific time (for testing).
    pub fn reset_at(&mut self, now: Instant) {
        self.wealth = 1.0;
        self.observations_since_recompute = 0;
        self.last_recompute = now;
        self.recent_matches.clear();
        // Lambda keeps its adapted value — intentional, since the match rate
        // character of the data likely hasn't changed.
    }

    /// Update the null hypothesis match rate μ₀.
    ///
    /// Call this when the baseline match rate changes (e.g., new query with
    /// different selectivity). Resets the e-process.
    pub fn set_mu_0(&mut self, mu_0: f64) {
        self.mu_0 = mu_0.clamp(MU_0_MIN, MU_0_MAX);
        self.lambda_max = 1.0 / self.mu_0 - 1e-6;
        self.lambda = self.lambda.clamp(1e-6, self.lambda_max);
        self.reset();
    }

    /// Current wealth (e-value).
    #[inline]
    pub fn wealth(&self) -> f64 {
        self.wealth
    }

    /// Current adaptive lambda.
    #[inline]
    pub fn lambda(&self) -> f64 {
        self.lambda
    }

    /// Empirical match rate over the sliding window.
    pub fn empirical_match_rate(&self) -> f64 {
        if self.recent_matches.is_empty() {
            return 0.0;
        }
        let matches = self.recent_matches.iter().filter(|&&m| m).count();
        matches as f64 / self.recent_matches.len() as f64
    }

    /// E-value threshold (1/α).
    #[inline]
    pub fn threshold(&self) -> f64 {
        self.threshold
    }

    /// Total observation count.
    #[inline]
    pub fn observation_count(&self) -> u64 {
        self.observation_count
    }

    /// Get aggregate statistics.
    pub fn stats(&self) -> ThrottleStats {
        let avg_obs = if self.total_recomputes > 0 {
            self.cumulative_obs_at_recompute as f64 / self.total_recomputes as f64
        } else {
            0.0
        };

        ThrottleStats {
            total_observations: self.observation_count,
            total_recomputes: self.total_recomputes,
            forced_recomputes: self.forced_recomputes,
            eprocess_recomputes: self.eprocess_recomputes,
            current_wealth: self.wealth,
            current_lambda: self.lambda,
            empirical_rate: self.empirical_match_rate(),
            avg_observations_between_recomputes: avg_obs,
        }
    }

    /// Get decision logs (if logging enabled).
    pub fn logs(&self) -> &[ThrottleLog] {
        &self.logs
    }

    /// Clear decision logs.
    pub fn clear_logs(&mut self) {
        self.logs.clear();
    }

    // --- Internal ---

    fn trigger_recompute(&mut self, now: Instant, forced: bool) {
        self.total_recomputes += 1;
        self.cumulative_obs_at_recompute += self.observations_since_recompute;
        if forced {
            self.forced_recomputes += 1;
        } else {
            self.eprocess_recomputes += 1;
        }
        self.wealth = 1.0;
        self.observations_since_recompute = 0;
        self.last_recompute = now;
    }

    fn log_decision(
        &mut self,
        now: Instant,
        matched: bool,
        wealth_before: f64,
        wealth_after: f64,
        action: &'static str,
        time_since_recompute: Duration,
    ) {
        if !self.config.enable_logging {
            return;
        }

        self.logs.push(ThrottleLog {
            timestamp: now,
            observation_idx: self.observation_count,
            matched,
            wealth_before,
            wealth_after,
            lambda: self.lambda,
            empirical_rate: self.empirical_match_rate(),
            action,
            time_since_recompute_ms: time_since_recompute.as_secs_f64() * 1000.0,
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex};
    use tracing_subscriber::layer::SubscriberExt;
    use tracing_subscriber::registry::LookupSpan;

    fn test_config() -> ThrottleConfig {
        ThrottleConfig {
            alpha: 0.05,
            mu_0: 0.1,
            initial_lambda: 0.5,
            grapa_eta: 0.1,
            hard_deadline_ms: 500,
            min_observations_between: 4,
            rate_window_size: 32,
            enable_logging: true,
        }
    }

    // ---------------------------------------------------------------
    // Basic construction and invariants
    // ---------------------------------------------------------------

    #[test]
    fn initial_state() {
        let t = EProcessThrottle::new(test_config());
        assert!((t.wealth() - 1.0).abs() < f64::EPSILON);
        assert_eq!(t.observation_count(), 0);
        assert!(t.lambda() > 0.0);
        assert!((t.threshold() - 20.0).abs() < 0.01); // 1/0.05 = 20
    }

    #[test]
    fn mu_0_clamped_to_valid_range() {
        let mut cfg = test_config();
        cfg.mu_0 = 0.0;
        let t = EProcessThrottle::new(cfg.clone());
        assert!(t.mu_0 >= MU_0_MIN);

        cfg.mu_0 = 1.0;
        let t = EProcessThrottle::new(cfg.clone());
        assert!(t.mu_0 <= MU_0_MAX);

        cfg.mu_0 = -5.0;
        let t = EProcessThrottle::new(cfg);
        assert!(t.mu_0 >= MU_0_MIN);
    }

    // ---------------------------------------------------------------
    // Wealth dynamics
    // ---------------------------------------------------------------

    #[test]
    fn no_match_decreases_wealth() {
        let base = Instant::now();
        let mut t = EProcessThrottle::new_at(test_config(), base);
        let d = t.observe_at(false, base + Duration::from_millis(1));
        assert!(
            d.wealth < 1.0,
            "No-match should decrease wealth: {}",
            d.wealth
        );
    }

    #[test]
    fn match_increases_wealth() {
        let base = Instant::now();
        let mut t = EProcessThrottle::new_at(test_config(), base);
        let d = t.observe_at(true, base + Duration::from_millis(1));
        assert!(d.wealth > 1.0, "Match should increase wealth: {}", d.wealth);
    }

    #[test]
    fn wealth_stays_positive() {
        let base = Instant::now();
        let mut t = EProcessThrottle::new_at(test_config(), base);
        // 1000 non-matches in a row — wealth should never reach zero
        for i in 1..=1000 {
            let d = t.observe_at(false, base + Duration::from_millis(i));
            assert!(d.wealth > 0.0, "Wealth must stay positive at obs {}", i);
        }
    }

    #[test]
    fn wealth_floor_prevents_zero_lock() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = u64::MAX; // disable deadline
        cfg.initial_lambda = 0.99; // aggressive betting
        let mut t = EProcessThrottle::new_at(cfg, base);

        for i in 1..=500 {
            t.observe_at(false, base + Duration::from_millis(i));
        }
        assert!(t.wealth() >= W_MIN, "Wealth should be at floor, not zero");

        // A match should still be able to grow wealth from the floor
        let before = t.wealth();
        t.observe_at(true, base + Duration::from_millis(501));
        assert!(
            t.wealth() > before,
            "Match should grow wealth even from floor"
        );
    }

    // ---------------------------------------------------------------
    // Recompute triggering
    // ---------------------------------------------------------------

    #[test]
    fn burst_of_matches_triggers_recompute() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.min_observations_between = 1; // allow fast trigger
        let mut t = EProcessThrottle::new_at(cfg, base);

        let mut triggered = false;
        for i in 1..=100 {
            let d = t.observe_at(true, base + Duration::from_millis(i));
            if d.should_recompute && !d.forced_by_deadline {
                triggered = true;
                break;
            }
        }
        assert!(
            triggered,
            "Burst of matches should trigger e-process recompute"
        );
    }

    #[test]
    fn no_matches_does_not_trigger_eprocess() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = u64::MAX;
        let mut t = EProcessThrottle::new_at(cfg, base);

        for i in 1..=200 {
            let d = t.observe_at(false, base + Duration::from_millis(i));
            assert!(
                !d.should_recompute,
                "No-match stream should never trigger e-process recompute at obs {}",
                i
            );
        }
    }

    #[test]
    fn hard_deadline_forces_recompute() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = 100;
        cfg.min_observations_between = 1;
        let mut t = EProcessThrottle::new_at(cfg, base);

        // Only non-matches, but exceed deadline
        let d = t.observe_at(false, base + Duration::from_millis(150));
        assert!(d.should_recompute, "Should trigger on deadline");
        assert!(d.forced_by_deadline, "Should be forced by deadline");
    }

    #[test]
    fn min_observations_between_prevents_rapid_fire() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.min_observations_between = 10;
        cfg.hard_deadline_ms = u64::MAX;
        cfg.alpha = 0.5; // very permissive to trigger early
        let mut t = EProcessThrottle::new_at(cfg, base);

        let mut first_trigger = None;
        for i in 1..=100 {
            let d = t.observe_at(true, base + Duration::from_millis(i));
            if d.should_recompute {
                first_trigger = Some(i);
                break;
            }
        }

        assert!(
            first_trigger.unwrap_or(0) >= 10,
            "First trigger should be at obs >= 10, was {:?}",
            first_trigger
        );
    }

    #[test]
    fn reset_clears_wealth_and_counter() {
        let base = Instant::now();
        let mut t = EProcessThrottle::new_at(test_config(), base);

        for i in 1..=10 {
            t.observe_at(true, base + Duration::from_millis(i));
        }
        assert!(t.wealth() > 1.0);
        assert!(t.observations_since_recompute > 0);

        t.reset_at(base + Duration::from_millis(20));
        assert!((t.wealth() - 1.0).abs() < f64::EPSILON);
        assert_eq!(t.observations_since_recompute, 0);
    }

    // ---------------------------------------------------------------
    // Adaptive lambda (GRAPA)
    // ---------------------------------------------------------------

    #[test]
    fn lambda_adapts_to_high_match_rate() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = u64::MAX;
        cfg.min_observations_between = u64::MAX;
        let mut t = EProcessThrottle::new_at(cfg, base);

        let initial_lambda = t.lambda();

        // Many matches should increase lambda (bet more aggressively)
        for i in 1..=50 {
            t.observe_at(true, base + Duration::from_millis(i));
        }

        assert!(
            t.lambda() > initial_lambda,
            "Lambda should increase with frequent matches: {} vs {}",
            t.lambda(),
            initial_lambda
        );
    }

    #[test]
    fn lambda_adapts_to_low_match_rate() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = u64::MAX;
        cfg.min_observations_between = u64::MAX;
        cfg.initial_lambda = 0.8;
        let mut t = EProcessThrottle::new_at(cfg, base);

        let initial_lambda = t.lambda();

        // Many non-matches should decrease lambda (bet more conservatively)
        for i in 1..=50 {
            t.observe_at(false, base + Duration::from_millis(i));
        }

        assert!(
            t.lambda() < initial_lambda,
            "Lambda should decrease with few matches: {} vs {}",
            t.lambda(),
            initial_lambda
        );
    }

    #[test]
    fn lambda_stays_bounded() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = u64::MAX;
        cfg.min_observations_between = u64::MAX;
        cfg.grapa_eta = 1.0; // aggressive learning
        let mut t = EProcessThrottle::new_at(cfg, base);

        for i in 1..=200 {
            let matched = i % 2 == 0;
            t.observe_at(matched, base + Duration::from_millis(i as u64));
        }

        assert!(t.lambda() > 0.0, "Lambda must be positive");
        assert!(
            t.lambda() <= t.lambda_max,
            "Lambda must not exceed 1/(1-mu_0): {} vs {}",
            t.lambda(),
            t.lambda_max
        );
    }

    // ---------------------------------------------------------------
    // Empirical match rate
    // ---------------------------------------------------------------

    #[test]
    fn empirical_rate_tracks_window() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.rate_window_size = 10;
        cfg.hard_deadline_ms = u64::MAX;
        cfg.min_observations_between = u64::MAX;
        let mut t = EProcessThrottle::new_at(cfg, base);

        // 10 matches
        for i in 1..=10 {
            t.observe_at(true, base + Duration::from_millis(i));
        }
        assert!((t.empirical_match_rate() - 1.0).abs() < f64::EPSILON);

        // 10 non-matches (window slides)
        for i in 11..=20 {
            t.observe_at(false, base + Duration::from_millis(i));
        }
        assert!((t.empirical_match_rate() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn empirical_rate_zero_when_empty() {
        let t = EProcessThrottle::new(test_config());
        assert!((t.empirical_match_rate() - 0.0).abs() < f64::EPSILON);
    }

    // ---------------------------------------------------------------
    // Stats and logging
    // ---------------------------------------------------------------

    #[test]
    fn stats_reflect_state() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.min_observations_between = 1;
        let mut t = EProcessThrottle::new_at(cfg, base);

        // Drive past a recompute
        let mut recomputed = false;
        for i in 1..=50 {
            let d = t.observe_at(true, base + Duration::from_millis(i));
            if d.should_recompute {
                recomputed = true;
            }
        }

        let stats = t.stats();
        assert_eq!(stats.total_observations, 50);
        if recomputed {
            assert!(stats.total_recomputes > 0);
            assert!(stats.avg_observations_between_recomputes > 0.0);
        }
    }

    #[test]
    fn logging_captures_decisions() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.enable_logging = true;
        let mut t = EProcessThrottle::new_at(cfg, base);

        t.observe_at(true, base + Duration::from_millis(1));
        t.observe_at(false, base + Duration::from_millis(2));

        assert_eq!(t.logs().len(), 2);
        assert!(t.logs()[0].matched);
        assert!(!t.logs()[1].matched);

        t.clear_logs();
        assert!(t.logs().is_empty());
    }

    #[test]
    fn logging_disabled_by_default() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.enable_logging = false;
        let mut t = EProcessThrottle::new_at(cfg, base);

        t.observe_at(true, base + Duration::from_millis(1));
        assert!(t.logs().is_empty());
    }

    // ---------------------------------------------------------------
    // set_mu_0
    // ---------------------------------------------------------------

    #[test]
    fn set_mu_0_resets_eprocess() {
        let base = Instant::now();
        let mut t = EProcessThrottle::new_at(test_config(), base);

        for i in 1..=10 {
            t.observe_at(true, base + Duration::from_millis(i));
        }
        assert!(t.wealth() > 1.0);

        t.set_mu_0(0.5);
        assert!((t.wealth() - 1.0).abs() < f64::EPSILON);
    }

    // ---------------------------------------------------------------
    // Determinism
    // ---------------------------------------------------------------

    #[test]
    fn deterministic_behavior() {
        let base = Instant::now();
        let cfg = test_config();

        let run = |cfg: &ThrottleConfig| {
            let mut t = EProcessThrottle::new_at(cfg.clone(), base);
            let mut decisions = Vec::new();
            for i in 1..=30 {
                let matched = i % 3 == 0;
                let d = t.observe_at(matched, base + Duration::from_millis(i));
                decisions.push((d.should_recompute, d.forced_by_deadline));
            }
            (decisions, t.wealth(), t.lambda())
        };

        let (d1, w1, l1) = run(&cfg);
        let (d2, w2, l2) = run(&cfg);

        assert_eq!(d1, d2, "Decisions must be deterministic");
        assert!((w1 - w2).abs() < 1e-10, "Wealth must be deterministic");
        assert!((l1 - l2).abs() < 1e-10, "Lambda must be deterministic");
    }

    // ---------------------------------------------------------------
    // Supermartingale property (Monte Carlo)
    // ---------------------------------------------------------------

    #[test]
    fn property_supermartingale_under_null() {
        // Under H₀ (match rate = μ₀), the expected wealth should not grow.
        // We verify empirically by running many trials and checking the
        // average final wealth ≤ initial wealth (with statistical slack).
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = u64::MAX;
        cfg.min_observations_between = u64::MAX;
        cfg.mu_0 = 0.2;
        cfg.grapa_eta = 0.0; // fix lambda to test pure martingale property

        let n_trials = 200;
        let n_obs = 100;
        let mut total_wealth = 0.0;

        // Simple LCG for deterministic pseudo-random
        let mut rng_state: u64 = 42;
        let lcg_next = |state: &mut u64| -> f64 {
            *state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (*state >> 33) as f64 / (1u64 << 31) as f64
        };

        for trial in 0..n_trials {
            let mut t = EProcessThrottle::new_at(cfg.clone(), base);
            for i in 1..=n_obs {
                let matched = lcg_next(&mut rng_state) < cfg.mu_0;
                t.observe_at(
                    matched,
                    base + Duration::from_millis(i as u64 + trial * 1000),
                );
            }
            total_wealth += t.wealth();
        }

        let avg_wealth = total_wealth / n_trials as f64;
        // Under H₀ with fixed lambda, E[W_t] ≤ 1. Allow statistical slack.
        assert!(
            avg_wealth < 2.0,
            "Average wealth under Hâ‚€ should be near 1.0, got {}",
            avg_wealth
        );
    }

    // ---------------------------------------------------------------
    // Anytime-valid Type I control
    // ---------------------------------------------------------------

    #[test]
    fn property_type_i_control() {
        // Under H₀, the probability of ever triggering should be ≤ α.
        // We test with many trials.
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = u64::MAX;
        cfg.min_observations_between = 1;
        cfg.alpha = 0.05;
        cfg.mu_0 = 0.1;
        cfg.grapa_eta = 0.0; // fixed lambda for clean test

        let n_trials = 500;
        let n_obs = 200;
        let mut false_triggers = 0u64;

        let mut rng_state: u64 = 123;
        let lcg_next = |state: &mut u64| -> f64 {
            *state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (*state >> 33) as f64 / (1u64 << 31) as f64
        };

        for trial in 0..n_trials {
            let mut t = EProcessThrottle::new_at(cfg.clone(), base);
            let mut triggered = false;
            for i in 1..=n_obs {
                let matched = lcg_next(&mut rng_state) < cfg.mu_0;
                let d = t.observe_at(
                    matched,
                    base + Duration::from_millis(i as u64 + trial * 1000),
                );
                if d.should_recompute {
                    triggered = true;
                    break;
                }
            }
            if triggered {
                false_triggers += 1;
            }
        }

        let false_trigger_rate = false_triggers as f64 / n_trials as f64;
        // Allow 3× slack for finite-sample variance
        assert!(
            false_trigger_rate < cfg.alpha * 3.0,
            "False trigger rate {} exceeds 3×α = {}",
            false_trigger_rate,
            cfg.alpha * 3.0
        );
    }

    // ---------------------------------------------------------------
    // Edge cases
    // ---------------------------------------------------------------

    #[test]
    fn single_observation() {
        let base = Instant::now();
        let cfg = test_config();
        let mut t = EProcessThrottle::new_at(cfg, base);
        let d = t.observe_at(true, base + Duration::from_millis(1));
        assert_eq!(t.observation_count(), 1);
        // Should not trigger with just 1 obs (min_observations_between = 4)
        assert!(!d.should_recompute || d.forced_by_deadline);
    }

    #[test]
    fn alternating_match_pattern() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = u64::MAX;
        cfg.min_observations_between = u64::MAX;
        let mut t = EProcessThrottle::new_at(cfg, base);

        // Alternating: match rate = 0.5, much higher than μ₀ = 0.1
        for i in 1..=100 {
            t.observe_at(i % 2 == 0, base + Duration::from_millis(i as u64));
        }

        // With 50% match rate vs 10% null, wealth should grow significantly
        assert!(
            t.wealth() > 1.0,
            "50% match rate vs 10% null should grow wealth: {}",
            t.wealth()
        );
    }

    #[test]
    fn recompute_resets_wealth() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.min_observations_between = 1;
        let mut t = EProcessThrottle::new_at(cfg, base);

        // Drive to recompute
        let mut triggered = false;
        for i in 1..=100 {
            let d = t.observe_at(true, base + Duration::from_millis(i));
            if d.should_recompute && !d.forced_by_deadline {
                // Wealth should be reset to 1.0 after recompute
                assert!(
                    (t.wealth() - 1.0).abs() < f64::EPSILON,
                    "Wealth should reset to 1.0 after recompute, got {}",
                    t.wealth()
                );
                triggered = true;
                break;
            }
        }
        assert!(
            triggered,
            "Should have triggered at least one e-process recompute"
        );
    }

    #[test]
    fn config_default_values() {
        let cfg = ThrottleConfig::default();
        assert!((cfg.alpha - 0.05).abs() < f64::EPSILON);
        assert!((cfg.mu_0 - 0.1).abs() < f64::EPSILON);
        assert!((cfg.initial_lambda - 0.5).abs() < f64::EPSILON);
        assert!((cfg.grapa_eta - 0.1).abs() < f64::EPSILON);
        assert_eq!(cfg.hard_deadline_ms, 500);
        assert_eq!(cfg.min_observations_between, 8);
        assert_eq!(cfg.rate_window_size, 64);
        assert!(!cfg.enable_logging);
    }

    #[test]
    fn throttle_decision_fields() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = u64::MAX;
        let mut t = EProcessThrottle::new_at(cfg, base);
        let d = t.observe_at(true, base + Duration::from_millis(1));

        assert!(!d.should_recompute);
        assert!(!d.forced_by_deadline);
        assert!(d.wealth > 1.0);
        assert!(d.lambda > 0.0);
        assert!((d.empirical_rate - 1.0).abs() < f64::EPSILON);
        assert_eq!(d.observations_since_recompute, 1);
    }

    #[test]
    fn stats_no_recomputes_avg_is_zero() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = u64::MAX;
        cfg.min_observations_between = u64::MAX;
        let mut t = EProcessThrottle::new_at(cfg, base);

        t.observe_at(false, base + Duration::from_millis(1));
        let stats = t.stats();
        assert_eq!(stats.total_recomputes, 0);
        assert!((stats.avg_observations_between_recomputes - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn set_mu_0_clamps_extreme_values() {
        let base = Instant::now();
        let mut t = EProcessThrottle::new_at(test_config(), base);

        t.set_mu_0(0.0);
        assert!(t.mu_0 >= MU_0_MIN);

        t.set_mu_0(2.0);
        assert!(t.mu_0 <= MU_0_MAX);
    }

    #[test]
    fn reset_preserves_lambda() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.hard_deadline_ms = u64::MAX;
        cfg.min_observations_between = u64::MAX;
        let mut t = EProcessThrottle::new_at(cfg, base);

        for i in 1..=20 {
            t.observe_at(true, base + Duration::from_millis(i));
        }
        let lambda_before = t.lambda();
        t.reset_at(base + Duration::from_millis(30));
        assert!(
            (t.lambda() - lambda_before).abs() < f64::EPSILON,
            "Lambda should be preserved across reset"
        );
    }

    #[test]
    fn logging_records_match_status_and_action() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.enable_logging = true;
        cfg.hard_deadline_ms = u64::MAX;
        cfg.min_observations_between = u64::MAX;
        let mut t = EProcessThrottle::new_at(cfg, base);

        t.observe_at(true, base + Duration::from_millis(1));
        let log = &t.logs()[0];
        assert!(log.matched);
        assert_eq!(log.observation_idx, 1);
        assert_eq!(log.action, "observe");
        assert!(log.wealth_after > log.wealth_before);
    }

    #[test]
    fn consecutive_recomputes_tracked() {
        let base = Instant::now();
        let mut cfg = test_config();
        cfg.min_observations_between = 1;
        cfg.alpha = 0.5; // permissive
        let mut t = EProcessThrottle::new_at(cfg, base);

        let mut recompute_count = 0;
        for i in 1..=200 {
            let d = t.observe_at(true, base + Duration::from_millis(i));
            if d.should_recompute {
                recompute_count += 1;
            }
        }

        let stats = t.stats();
        assert_eq!(stats.total_recomputes, recompute_count as u64);
        assert!(
            stats.total_recomputes >= 2,
            "Should have multiple recomputes"
        );
    }

    // =========================================================================
    // Tracing capture infrastructure (bd-37a.5)
    // =========================================================================

    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    struct CapturedSpan {
        name: String,
        target: String,
        level: tracing::Level,
        fields: HashMap<String, String>,
    }

    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    struct CapturedEvent {
        level: tracing::Level,
        target: String,
        message: String,
        fields: HashMap<String, String>,
    }

    struct SpanCapture {
        spans: Arc<Mutex<Vec<CapturedSpan>>>,
        events: Arc<Mutex<Vec<CapturedEvent>>>,
    }

    impl SpanCapture {
        fn new() -> (Self, CaptureHandle) {
            let spans = Arc::new(Mutex::new(Vec::new()));
            let events = Arc::new(Mutex::new(Vec::new()));

            let handle = CaptureHandle {
                spans: spans.clone(),
                events: events.clone(),
            };

            (Self { spans, events }, handle)
        }
    }

    struct CaptureHandle {
        spans: Arc<Mutex<Vec<CapturedSpan>>>,
        events: Arc<Mutex<Vec<CapturedEvent>>>,
    }

    impl CaptureHandle {
        fn spans(&self) -> Vec<CapturedSpan> {
            self.spans.lock().unwrap().clone()
        }

        fn events(&self) -> Vec<CapturedEvent> {
            self.events.lock().unwrap().clone()
        }
    }

    struct FieldVisitor(Vec<(String, String)>);

    impl tracing::field::Visit for FieldVisitor {
        fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
            self.0
                .push((field.name().to_string(), format!("{value:?}")));
        }

        fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
            self.0.push((field.name().to_string(), value.to_string()));
        }

        fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
            self.0.push((field.name().to_string(), value.to_string()));
        }

        fn record_f64(&mut self, field: &tracing::field::Field, value: f64) {
            self.0.push((field.name().to_string(), value.to_string()));
        }

        fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
            self.0.push((field.name().to_string(), value.to_string()));
        }

        fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
            self.0.push((field.name().to_string(), value.to_string()));
        }
    }

    impl<S> tracing_subscriber::Layer<S> for SpanCapture
    where
        S: tracing::Subscriber + for<'a> LookupSpan<'a>,
    {
        fn on_new_span(
            &self,
            attrs: &tracing::span::Attributes<'_>,
            _id: &tracing::span::Id,
            _ctx: tracing_subscriber::layer::Context<'_, S>,
        ) {
            let mut visitor = FieldVisitor(Vec::new());
            attrs.record(&mut visitor);

            let mut fields: HashMap<String, String> = visitor.0.into_iter().collect();
            for field in attrs.metadata().fields() {
                fields.entry(field.name().to_string()).or_default();
            }

            self.spans.lock().unwrap().push(CapturedSpan {
                name: attrs.metadata().name().to_string(),
                target: attrs.metadata().target().to_string(),
                level: *attrs.metadata().level(),
                fields,
            });
        }

        fn on_event(
            &self,
            event: &tracing::Event<'_>,
            _ctx: tracing_subscriber::layer::Context<'_, S>,
        ) {
            let mut visitor = FieldVisitor(Vec::new());
            event.record(&mut visitor);

            let fields: HashMap<String, String> = visitor.0.clone().into_iter().collect();
            let message = visitor
                .0
                .iter()
                .find(|(k, _)| k == "message")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();

            self.events.lock().unwrap().push(CapturedEvent {
                level: *event.metadata().level(),
                target: event.metadata().target().to_string(),
                message,
                fields,
            });
        }
    }

    fn with_captured_tracing<F>(f: F) -> CaptureHandle
    where
        F: FnOnce(),
    {
        let (layer, handle) = SpanCapture::new();
        let subscriber = tracing_subscriber::registry().with(layer);
        tracing::subscriber::with_default(subscriber, f);
        handle
    }

    // =========================================================================
    // Tracing span field assertions
    // =========================================================================

    #[test]
    fn span_eprocess_update_has_required_fields() {
        let handle = with_captured_tracing(|| {
            let base = Instant::now();
            let mut t = EProcessThrottle::new_at(test_config(), base);
            t.observe_at(true, base + Duration::from_millis(1));
        });

        let spans = handle.spans();
        let ep_spans: Vec<_> = spans
            .iter()
            .filter(|s| s.name == "eprocess.update")
            .collect();
        assert!(
            !ep_spans.is_empty(),
            "expected at least one eprocess.update span"
        );

        let span = &ep_spans[0];
        assert!(span.fields.contains_key("test_id"), "missing test_id field");
        assert!(
            span.fields.contains_key("wealth_current"),
            "missing wealth_current"
        );
        assert!(
            span.fields.contains_key("wealth_threshold"),
            "missing wealth_threshold"
        );
        assert!(
            span.fields.contains_key("observation_count"),
            "missing observation_count"
        );
        assert!(
            span.fields.contains_key("rejected"),
            "missing rejected field"
        );
    }

    #[test]
    fn span_rejected_field_true_on_eprocess_trigger() {
        let handle = with_captured_tracing(|| {
            let base = Instant::now();
            let mut cfg = test_config();
            cfg.min_observations_between = 1;
            let mut t = EProcessThrottle::new_at(cfg, base);

            for i in 1..=100 {
                let d = t.observe_at(true, base + Duration::from_millis(i));
                if d.should_recompute && !d.forced_by_deadline {
                    break;
                }
            }
        });

        let spans = handle.spans();
        let ep_spans: Vec<_> = spans
            .iter()
            .filter(|s| s.name == "eprocess.update")
            .collect();

        // At least one span should have rejected=true
        let rejected_spans: Vec<_> = ep_spans
            .iter()
            .filter(|s| s.fields.get("rejected").is_some_and(|v| v == "true"))
            .collect();
        assert!(
            !rejected_spans.is_empty(),
            "expected at least one span with rejected=true"
        );
    }

    // =========================================================================
    // DEBUG log assertions
    // =========================================================================

    #[test]
    fn debug_log_wealth_update() {
        let handle = with_captured_tracing(|| {
            let base = Instant::now();
            let mut t = EProcessThrottle::new_at(test_config(), base);
            t.observe_at(true, base + Duration::from_millis(1));
        });

        let events = handle.events();
        let debug_events: Vec<_> = events
            .iter()
            .filter(|e| {
                e.level == tracing::Level::DEBUG
                    && e.target == "ftui.eprocess"
                    && e.fields.contains_key("wealth_before")
            })
            .collect();

        assert!(
            !debug_events.is_empty(),
            "expected at least one DEBUG wealth update event"
        );

        let evt = &debug_events[0];
        assert!(
            evt.fields.contains_key("wealth_after"),
            "missing wealth_after"
        );
        assert!(evt.fields.contains_key("lambda"), "missing lambda");
        assert!(
            evt.fields.contains_key("eprocess_wealth"),
            "missing eprocess_wealth gauge"
        );
    }

    // =========================================================================
    // INFO log on rejection
    // =========================================================================

    #[test]
    fn info_log_on_eprocess_rejection() {
        let handle = with_captured_tracing(|| {
            let base = Instant::now();
            let mut cfg = test_config();
            cfg.min_observations_between = 1;
            let mut t = EProcessThrottle::new_at(cfg, base);

            for i in 1..=100 {
                let d = t.observe_at(true, base + Duration::from_millis(i));
                if d.should_recompute && !d.forced_by_deadline {
                    break;
                }
            }
        });

        let events = handle.events();
        let info_events: Vec<_> = events
            .iter()
            .filter(|e| {
                e.level == tracing::Level::INFO
                    && e.target == "ftui.eprocess"
                    && e.fields.contains_key("wealth")
                    && e.fields.contains_key("threshold")
            })
            .collect();

        assert!(
            !info_events.is_empty(),
            "expected INFO log on e-process rejection"
        );
    }

    #[test]
    fn info_log_on_deadline_forced_recompute() {
        let handle = with_captured_tracing(|| {
            let base = Instant::now();
            let mut cfg = test_config();
            cfg.hard_deadline_ms = 100;
            cfg.min_observations_between = 1;
            let mut t = EProcessThrottle::new_at(cfg, base);

            // Only non-matches, exceed deadline
            t.observe_at(false, base + Duration::from_millis(150));
        });

        let events = handle.events();
        let deadline_events: Vec<_> = events
            .iter()
            .filter(|e| {
                e.level == tracing::Level::INFO
                    && e.target == "ftui.eprocess"
                    && e.fields.contains_key("deadline_ms")
            })
            .collect();

        assert!(
            !deadline_events.is_empty(),
            "expected INFO log on deadline forced recompute"
        );
    }

    // =========================================================================
    // Counter verification
    // =========================================================================

    #[test]
    fn counter_accessor_is_callable() {
        let total = eprocess_rejections_total();
        let _ = total.checked_add(0).expect("counter overflow");
    }

    #[test]
    fn counter_increments_on_rejection() {
        let before = eprocess_rejections_total();

        let base = Instant::now();
        let mut cfg = test_config();
        cfg.min_observations_between = 1;
        let mut t = EProcessThrottle::new_at(cfg, base);

        for i in 1..=100 {
            let d = t.observe_at(true, base + Duration::from_millis(i));
            if d.should_recompute && !d.forced_by_deadline {
                break;
            }
        }

        let after = eprocess_rejections_total();
        assert!(
            after > before,
            "counter should increment on rejection: before={before}, after={after}"
        );
    }

    #[test]
    fn debug_events_per_observation() {
        let handle = with_captured_tracing(|| {
            let base = Instant::now();
            let mut cfg = test_config();
            cfg.hard_deadline_ms = u64::MAX;
            cfg.min_observations_between = u64::MAX;
            let mut t = EProcessThrottle::new_at(cfg, base);

            for i in 1..=5 {
                t.observe_at(i % 2 == 0, base + Duration::from_millis(i));
            }
        });

        let events = handle.events();
        let debug_events: Vec<_> = events
            .iter()
            .filter(|e| {
                e.level == tracing::Level::DEBUG
                    && e.target == "ftui.eprocess"
                    && e.fields.contains_key("wealth_before")
            })
            .collect();

        assert_eq!(
            debug_events.len(),
            5,
            "expected one DEBUG wealth event per observation"
        );
    }
}