lineprior 0.7.1

Domain-agnostic action priors built from historical action sequences.
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
use crate::build::{PriorAccumulator, SequenceContextTracker};
use crate::error::{Result, Warning};
use crate::input::parse_line;
use crate::model::{BuildConfig, Observation, Outcome, PriorBook, outcome_credit};
use crate::score::ratio;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::io::{BufRead, BufReader, Read};

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::Error;
    use crate::model::PriorAction;

    fn obs(state: &str, action: &str) -> Observation {
        Observation {
            sequence_id: "seq".to_string(),
            step: 0,
            state: state.to_string(),
            action: action.to_string(),
            outcome: Outcome::Success,
            score: None,
            weight: 1.0,
            tags: Vec::new(),
            observed_at_unix_seconds: None,
            source: None,
        }
    }

    /// State "s" ranks a (highest prior) > b > c; state "t" is unused by
    /// the tests below except to confirm it doesn't interfere.
    fn sample_book() -> PriorBook {
        let mut entries = HashMap::new();
        entries.insert(
            "s".to_string(),
            vec![
                PriorAction {
                    action: "a".into(),
                    count: 10,
                    weighted_count: 10.0,
                    success_rate: Some(0.9),
                    mean_score: None,
                    prior: 0.6,
                    confidence: 0.5,
                },
                PriorAction {
                    action: "b".into(),
                    count: 5,
                    weighted_count: 5.0,
                    success_rate: Some(0.5),
                    mean_score: None,
                    prior: 0.3,
                    confidence: 0.3,
                },
                PriorAction {
                    action: "c".into(),
                    count: 2,
                    weighted_count: 2.0,
                    success_rate: Some(0.2),
                    mean_score: None,
                    prior: 0.1,
                    confidence: 0.1,
                },
            ],
        );
        PriorBook {
            entries,
            ..Default::default()
        }
    }

    #[test]
    fn is_train_is_stable_for_a_fixed_id() {
        assert_eq!(is_train("seq-1", 0.8), is_train("seq-1", 0.8));
    }

    #[test]
    fn is_train_ratio_zero_is_always_false() {
        for i in 0..50 {
            assert!(!is_train(&format!("seq-{i}"), 0.0));
        }
    }

    #[test]
    fn is_train_ratio_one_is_always_true() {
        for i in 0..50 {
            assert!(is_train(&format!("seq-{i}"), 1.0));
        }
    }

    #[test]
    fn is_train_splits_roughly_by_ratio() {
        // Statistical sanity check on a deterministic hash, not an exact
        // count -- generous band avoids flakiness while still catching a
        // badly broken hash/bucketing (e.g. always-train or always-test).
        let train_count = (0..1000)
            .filter(|i| is_train(&format!("seq-{i}"), 0.8))
            .count();
        assert!(
            (700..=900).contains(&train_count),
            "train_count = {train_count}, expected roughly 800/1000"
        );
    }

    #[test]
    fn topk_hit_rate_and_mrr_match_hand_computed_ranks() {
        let book = sample_book();
        let top_k = vec![1, 2, 3];
        let mut acc = EvalAccumulator::new(&top_k, 0.5, 0, 0, &[]);

        acc.observe(&book, &obs("s", "a")).unwrap(); // rank 1
        acc.observe(&book, &obs("s", "b")).unwrap(); // rank 2
        acc.observe(&book, &obs("s", "c")).unwrap(); // rank 3
        acc.observe(&book, &obs("s", "z")).unwrap(); // not found among candidates

        let report = acc.finish(0);
        assert_eq!(report.num_evaluated_observations, 4);
        assert_eq!(report.top1_hit_rate, Some(0.25));
        assert_eq!(
            report.topk_hit_rate,
            vec![
                TopKHitRate {
                    k: 1,
                    hit_rate: Some(0.25)
                },
                TopKHitRate {
                    k: 2,
                    hit_rate: Some(0.5)
                },
                TopKHitRate {
                    k: 3,
                    hit_rate: Some(0.75)
                },
            ]
        );
        let expected_mrr = (1.0 + 0.5 + 1.0 / 3.0) / 4.0;
        assert!((report.mean_reciprocal_rank.unwrap() - expected_mrr).abs() < 1e-9);
        assert_eq!(report.avg_rank_when_found, Some(2.0)); // (1 + 2 + 3) / 3
    }

    #[test]
    fn unseen_state_counts_as_fallback_not_evaluated() {
        let book = sample_book(); // only has state "s"
        let top_k = vec![1];
        let mut acc = EvalAccumulator::new(&top_k, 0.5, 0, 0, &[]);

        acc.observe(&book, &obs("unseen_state", "a")).unwrap();

        let report = acc.finish(0);
        assert_eq!(report.num_test_states, 1);
        assert_eq!(report.num_fallback_observations, 1);
        assert_eq!(report.num_evaluated_observations, 0);
        assert_eq!(report.num_test_states_with_candidates, 0);
        assert_eq!(report.coverage, Some(0.0));
        assert_eq!(report.fallback_rate, Some(1.0));
        assert_eq!(report.top1_hit_rate, None);
    }

    #[test]
    fn success_weighted_metrics_equal_unweighted_when_everything_succeeds() {
        // Every observation from `obs()` defaults to Outcome::Success, so
        // full credit (1.0) applies uniformly -- the weighted average
        // degenerates to the plain average.
        let book = sample_book();
        let top_k = vec![1];
        let mut acc = EvalAccumulator::new(&top_k, 0.5, 0, 0, &[]);

        acc.observe(&book, &obs("s", "a")).unwrap(); // rank 1
        acc.observe(&book, &obs("s", "b")).unwrap(); // rank 2
        acc.observe(&book, &obs("s", "z")).unwrap(); // not found

        let report = acc.finish(0);
        assert_eq!(report.success_weighted_top1_hit_rate, report.top1_hit_rate);
        assert_eq!(
            report.success_weighted_mean_reciprocal_rank,
            report.mean_reciprocal_rank
        );
    }

    #[test]
    fn success_weighted_metrics_are_none_when_nothing_earns_credit() {
        let book = sample_book();
        let top_k = vec![1];
        let mut acc = EvalAccumulator::new(&top_k, 0.5, 0, 0, &[]);

        acc.observe(
            &book,
            &Observation {
                outcome: Outcome::Failure,
                ..obs("s", "a")
            },
        )
        .unwrap();
        acc.observe(
            &book,
            &Observation {
                outcome: Outcome::Unknown,
                ..obs("s", "a")
            },
        )
        .unwrap();

        let report = acc.finish(0);
        assert_eq!(report.num_evaluated_observations, 2);
        assert_eq!(report.success_weighted_top1_hit_rate, None);
        assert_eq!(report.success_weighted_mean_reciprocal_rank, None);
    }

    #[test]
    fn success_weighted_metrics_give_draws_partial_credit() {
        let book = sample_book();
        let top_k = vec![1];
        let mut acc = EvalAccumulator::new(&top_k, 0.5, 0, 0, &[]);

        acc.observe(&book, &obs("s", "a")).unwrap(); // Success, rank 1 (hit), credit 1.0
        acc.observe(
            &book,
            &Observation {
                outcome: Outcome::Draw,
                ..obs("s", "b")
            },
        )
        .unwrap(); // Draw, rank 2 (miss on #1), credit 0.5
        acc.observe(
            &book,
            &Observation {
                outcome: Outcome::Failure,
                ..obs("s", "z")
            },
        )
        .unwrap(); // Failure, not found, credit 0.0 (self-excludes)

        let report = acc.finish(0);
        // weight sum = 1.0 + 0.5 + 0.0 = 1.5; weighted hit sum = 1.0 (only obs 1 hits #1)
        let expected_top1 = 1.0 / 1.5;
        // weighted rr sum = 1.0*1.0 + 0.5*0.5 + 0.0*0.0 = 1.25
        let expected_mrr = 1.25 / 1.5;
        assert!((report.success_weighted_top1_hit_rate.unwrap() - expected_top1).abs() < 1e-9);
        assert!(
            (report.success_weighted_mean_reciprocal_rank.unwrap() - expected_mrr).abs() < 1e-9
        );
    }

    #[test]
    fn draw_value_zero_makes_success_weighted_metrics_treat_draws_as_failures() {
        // Parity with build.rs's draw_value_zero_reproduces_draw_as_failure_behavior:
        // draw_value=0.0 means a draw earns no credit, same as a loss.
        let book = sample_book();
        let top_k = vec![1];
        let mut acc = EvalAccumulator::new(&top_k, 0.0, 0, 0, &[]);

        acc.observe(
            &book,
            &Observation {
                outcome: Outcome::Draw,
                ..obs("s", "a")
            },
        )
        .unwrap();

        let report = acc.finish(0);
        assert_eq!(report.success_weighted_top1_hit_rate, None);
        assert_eq!(report.success_weighted_mean_reciprocal_rank, None);
    }

    #[test]
    fn failure_agreement_top1_hit_rate_flags_the_prior_recommending_a_loser() {
        let book = sample_book();
        let top_k = vec![1];
        let mut acc = EvalAccumulator::new(&top_k, 0.5, 0, 0, &[]);

        acc.observe(
            &book,
            &Observation {
                outcome: Outcome::Failure,
                ..obs("s", "a") // top1 is "a" -- the prior's pick failed
            },
        )
        .unwrap();
        acc.observe(
            &book,
            &Observation {
                outcome: Outcome::Failure,
                ..obs("s", "b") // top1 is "a", actual was "b" -- prior didn't recommend the failure
            },
        )
        .unwrap();

        let report = acc.finish(0);
        assert_eq!(report.failure_agreement_top1_hit_rate, Some(0.5));
    }

    #[test]
    fn failure_agreement_top1_hit_rate_is_none_without_failure_observations() {
        let book = sample_book();
        let top_k = vec![1];
        let mut acc = EvalAccumulator::new(&top_k, 0.5, 0, 0, &[]);

        acc.observe(&book, &obs("s", "a")).unwrap();

        let report = acc.finish(0);
        assert_eq!(report.failure_agreement_top1_hit_rate, None);
    }

    #[test]
    fn evaluate_end_to_end_matches_hand_derived_expectations() {
        let train_ratio = 0.5;
        // Partition sequence ids using the same deterministic split
        // evaluate() itself uses, so expectations below are derived from
        // the actual split rather than guessed at.
        let candidate_ids: Vec<String> = (0..40).map(|i| format!("seq-{i}")).collect();
        let train_ids: Vec<&String> = candidate_ids
            .iter()
            .filter(|id| is_train(id, train_ratio))
            .collect();
        let test_ids: Vec<&String> = candidate_ids
            .iter()
            .filter(|id| !is_train(id, train_ratio))
            .collect();
        assert!(!train_ids.is_empty(), "need at least one train sequence");
        assert!(test_ids.len() >= 2, "need at least two test sequences");

        // Train: state "s" always leads to action "a".
        let mut jsonl = String::new();
        for id in &train_ids {
            jsonl.push_str(&format!(
                "{{\"sequence_id\":\"{id}\",\"step\":0,\"state\":\"s\",\"action\":\"a\",\"outcome\":\"success\"}}\n"
            ));
        }
        // Test: even-indexed sequences repeat "a" (should hit rank 1),
        // odd-indexed take a never-before-seen action "z" (miss, but still
        // evaluated since state "s" has candidates).
        for (i, id) in test_ids.iter().enumerate() {
            let action = if i % 2 == 0 { "a" } else { "z" };
            jsonl.push_str(&format!(
                "{{\"sequence_id\":\"{id}\",\"step\":0,\"state\":\"s\",\"action\":\"{action}\",\"outcome\":\"success\"}}\n"
            ));
        }

        let hits = test_ids
            .iter()
            .enumerate()
            .filter(|(i, _)| i % 2 == 0)
            .count();
        let expected_confidence = train_ids.len() as f64 / (train_ids.len() as f64 + 20.0);

        let eval_config = EvalConfig {
            train_ratio,
            top_k: vec![1],
            ..EvalConfig::default()
        };
        let output = evaluate(
            jsonl.as_bytes(),
            jsonl.as_bytes(),
            true,
            &BuildConfig::default(),
            &eval_config,
        )
        .unwrap();

        assert_eq!(output.report.num_train_observations, train_ids.len() as u64);
        assert_eq!(output.report.num_test_observations, test_ids.len() as u64);
        assert_eq!(output.report.num_test_states, 1);
        assert_eq!(
            output.report.num_evaluated_observations,
            test_ids.len() as u64
        );
        assert_eq!(output.report.num_fallback_observations, 0);
        assert_eq!(output.report.coverage, Some(1.0));
        assert_eq!(output.report.fallback_rate, Some(0.0));
        let expected_rate = Some(hits as f64 / test_ids.len() as f64);
        assert_eq!(output.report.top1_hit_rate, expected_rate);
        assert_eq!(
            output.report.topk_hit_rate,
            vec![TopKHitRate {
                k: 1,
                hit_rate: expected_rate
            }]
        );
        assert_eq!(output.report.mean_reciprocal_rank, expected_rate);
        assert_eq!(output.report.avg_rank_when_found, Some(1.0));
        assert_eq!(
            output.report.avg_confidence_on_hit,
            Some(expected_confidence)
        );
        assert_eq!(
            output.report.avg_confidence_on_miss,
            Some(expected_confidence)
        );
        assert_eq!(output.report.score_lift, None); // no `score` field anywhere
        assert!(output.warnings.is_empty());
    }

    #[test]
    fn evaluate_reports_context_aware_metrics_when_context_order_is_set() {
        let train_ratio = 0.5;
        let candidate_ids: Vec<String> = (0..60).map(|i| format!("seq-{i}")).collect();
        let train_ids: Vec<&String> = candidate_ids
            .iter()
            .filter(|id| is_train(id, train_ratio))
            .collect();
        let test_ids: Vec<&String> = candidate_ids
            .iter()
            .filter(|id| !is_train(id, train_ratio))
            .collect();
        assert!(train_ids.len() >= 2, "need at least two train sequences");
        assert!(test_ids.len() >= 2, "need at least two test sequences");

        // Every sequence: step 0 picks "x" or "y" (alternating), step 1's
        // action from state "s" always matches ("x" -> "A", "y" -> "B").
        // Order-0 alone can't tell A from B apart at state "s" (tied), but
        // order-1 context (step 0's own action) predicts it perfectly.
        let mut jsonl = String::new();
        for (i, id) in train_ids.iter().chain(test_ids.iter()).enumerate() {
            let (first, second) = if i % 2 == 0 { ("x", "A") } else { ("y", "B") };
            jsonl.push_str(&format!(
                "{{\"sequence_id\":\"{id}\",\"step\":0,\"state\":\"s0\",\"action\":\"{first}\",\"outcome\":\"success\"}}\n"
            ));
            jsonl.push_str(&format!(
                "{{\"sequence_id\":\"{id}\",\"step\":1,\"state\":\"s\",\"action\":\"{second}\",\"outcome\":\"success\"}}\n"
            ));
        }

        let build_config = BuildConfig {
            context_order: 1,
            ..Default::default()
        };
        let eval_config = EvalConfig {
            train_ratio,
            top_k: vec![1],
            ..EvalConfig::default()
        };
        let output = evaluate(
            jsonl.as_bytes(),
            jsonl.as_bytes(),
            true,
            &build_config,
            &eval_config,
        )
        .unwrap();
        let report = output.report;

        // Context-aware backoff beats plain order-0 in the same run, over
        // the same test observations.
        assert!(report.context_top1_hit_rate.unwrap() > report.top1_hit_rate.unwrap());
        assert!(
            report.context_mean_reciprocal_rank.unwrap() > report.mean_reciprocal_rank.unwrap()
        );

        // Isolated by matched order: every state-"s" observation resolves
        // via order-1 context and is always correct there (state "s0"'s
        // order-0-only, ~tied predictions land in the order-0 bucket
        // instead, which is why the *aggregate* above isn't a clean 1.0).
        let order1 = report
            .hit_rate_by_matched_order
            .iter()
            .find(|m| m.order == 1)
            .expect("order-1 entries should exist");
        assert_eq!(order1.top1_hit_rate, Some(1.0));
        assert_eq!(order1.num_evaluated, test_ids.len() as u64);
    }

    #[test]
    fn evaluate_context_fields_are_absent_when_context_order_is_zero() {
        let train_ratio = 0.5;
        let candidate_ids: Vec<String> = (0..40).map(|i| format!("seq-{i}")).collect();
        let train_ids: Vec<&String> = candidate_ids
            .iter()
            .filter(|id| is_train(id, train_ratio))
            .collect();
        let test_ids: Vec<&String> = candidate_ids
            .iter()
            .filter(|id| !is_train(id, train_ratio))
            .collect();
        assert!(!train_ids.is_empty());
        assert!(!test_ids.is_empty());

        let mut jsonl = String::new();
        for id in train_ids.iter().chain(test_ids.iter()) {
            jsonl.push_str(&format!(
                "{{\"sequence_id\":\"{id}\",\"step\":0,\"state\":\"s\",\"action\":\"a\",\"outcome\":\"success\"}}\n"
            ));
        }

        let eval_config = EvalConfig {
            train_ratio,
            top_k: vec![1],
            ..EvalConfig::default()
        };
        // context_order defaults to 0 -- confirm the new fields stay absent
        // even though there's real evaluated test data, not just because
        // nothing was evaluated at all.
        let output = evaluate(
            jsonl.as_bytes(),
            jsonl.as_bytes(),
            true,
            &BuildConfig::default(),
            &eval_config,
        )
        .unwrap();
        assert!(output.report.num_evaluated_observations > 0);
        assert_eq!(output.report.context_top1_hit_rate, None);
        assert_eq!(output.report.context_mean_reciprocal_rank, None);
        assert!(output.report.hit_rate_by_matched_order.is_empty());
    }

    #[test]
    fn evaluate_applies_time_decay_to_its_train_side_prior_same_as_build() {
        // `evaluate()` folds train observations through the same
        // `PriorAccumulator::observe` build.rs uses, so it must respond to
        // `BuildConfig::time_decay_half_life_days` identically: an action
        // dominant by raw count should lose its #1 ranking to a fresher
        // action once decay crushes its effective weight.
        let train_ratio = 0.5;
        let candidate_ids: Vec<String> = (0..40).map(|i| format!("seq-{i}")).collect();
        let train_ids: Vec<&String> = candidate_ids
            .iter()
            .filter(|id| is_train(id, train_ratio))
            .collect();
        let test_ids: Vec<&String> = candidate_ids
            .iter()
            .filter(|id| !is_train(id, train_ratio))
            .collect();
        assert!(train_ids.len() >= 2, "need at least two train sequences");
        assert!(!test_ids.is_empty(), "need at least one test sequence");

        // Most train sequences take "old_winner" (dominant by raw count
        // without decay); a minority take "new_winner".
        let split = (train_ids.len() * 4 / 5).clamp(1, train_ids.len() - 1);
        let reference: i64 = 1_000_000;

        let mut jsonl = String::new();
        for id in &train_ids[..split] {
            jsonl.push_str(&format!(
                "{{\"sequence_id\":\"{id}\",\"step\":0,\"state\":\"s\",\"action\":\"old_winner\",\
                 \"outcome\":\"success\",\"observed_at_unix_seconds\":{}}}\n",
                reference - 5000 * 86_400, // 5000 days old == 1000 half-lives at half_life=5
            ));
        }
        for id in &train_ids[split..] {
            jsonl.push_str(&format!(
                "{{\"sequence_id\":\"{id}\",\"step\":0,\"state\":\"s\",\"action\":\"new_winner\",\
                 \"outcome\":\"success\",\"observed_at_unix_seconds\":{reference}}}\n"
            ));
        }
        // Every test observation actually took "new_winner" -- top1_hit_rate
        // is then fully determined by whether the trained book's #1 pick
        // for state "s" is "new_winner" or "old_winner".
        for id in &test_ids {
            jsonl.push_str(&format!(
                "{{\"sequence_id\":\"{id}\",\"step\":0,\"state\":\"s\",\"action\":\"new_winner\",\"outcome\":\"success\"}}\n"
            ));
        }

        let eval_config = EvalConfig {
            train_ratio,
            top_k: vec![1],
            ..EvalConfig::default()
        };

        let without_decay = evaluate(
            jsonl.as_bytes(),
            jsonl.as_bytes(),
            true,
            &BuildConfig::default(),
            &eval_config,
        )
        .unwrap();
        assert_eq!(
            without_decay.report.top1_hit_rate,
            Some(0.0),
            "without decay, old_winner's raw count should dominate and mismatch every \
             new_winner test observation"
        );

        let decay_config = BuildConfig {
            time_decay_half_life_days: Some(5.0),
            time_decay_reference_unix_seconds: Some(reference),
            ..Default::default()
        };
        let with_decay = evaluate(
            jsonl.as_bytes(),
            jsonl.as_bytes(),
            true,
            &decay_config,
            &eval_config,
        )
        .unwrap();
        assert_eq!(
            with_decay.report.top1_hit_rate,
            Some(1.0),
            "with decay, old_winner's effective weight should be crushed, flipping the \
             #1 ranking to new_winner"
        );
    }

    /// Three single-candidate states so each observation's #1 confidence is
    /// fully controlled: "s1" 0.05 (bin 0 of 10), "s2" 0.55 (bin 5), "s3"
    /// 1.0 (edge case -- must clamp into the last bin, not overflow it).
    fn calibration_fixture_book() -> PriorBook {
        let action_with_confidence = |confidence: f64| PriorAction {
            action: "a".into(),
            count: 1,
            weighted_count: 1.0,
            success_rate: None,
            mean_score: None,
            prior: 1.0,
            confidence,
        };
        let mut entries = HashMap::new();
        entries.insert("s1".to_string(), vec![action_with_confidence(0.05)]);
        entries.insert("s2".to_string(), vec![action_with_confidence(0.55)]);
        entries.insert("s3".to_string(), vec![action_with_confidence(1.0)]);
        PriorBook {
            entries,
            ..Default::default()
        }
    }

    #[test]
    fn calibration_bins_are_deterministic_length_and_bucketed_correctly() {
        let book = calibration_fixture_book();
        let top_k = vec![1];
        let mut acc = EvalAccumulator::new(&top_k, 0.5, 0, 10, &[]);

        acc.observe(&book, &obs("s1", "a")).unwrap(); // hit, confidence 0.05 -> bin 0
        acc.observe(&book, &obs("s2", "b")).unwrap(); // miss, confidence 0.55 -> bin 5
        acc.observe(&book, &obs("s3", "a")).unwrap(); // hit, confidence 1.0 -> clamped into last bin 9

        let report = acc.finish(0);
        assert_eq!(report.confidence_calibration.len(), 10); // always calibration_bins entries

        let bin0 = &report.confidence_calibration[0];
        assert!((bin0.min_confidence - 0.0).abs() < 1e-9);
        assert!((bin0.max_confidence - 0.1).abs() < 1e-9);
        assert_eq!(bin0.num_evaluated, 1);
        assert_eq!(bin0.top1_hit_rate, Some(1.0));
        assert_eq!(bin0.mean_reciprocal_rank, Some(1.0));

        let bin5 = &report.confidence_calibration[5];
        assert_eq!(bin5.num_evaluated, 1);
        assert_eq!(bin5.top1_hit_rate, Some(0.0));
        assert_eq!(bin5.mean_reciprocal_rank, Some(0.0));

        let bin9 = &report.confidence_calibration[9]; // confidence == 1.0 lands here, not out of bounds
        assert_eq!(bin9.num_evaluated, 1);
        assert_eq!(bin9.top1_hit_rate, Some(1.0));

        let bin1 = &report.confidence_calibration[1];
        assert_eq!(bin1.num_evaluated, 0);
        assert_eq!(bin1.top1_hit_rate, None);
        assert_eq!(bin1.mean_reciprocal_rank, None);
    }

    #[test]
    fn threshold_sweep_matches_hand_computed_fixture() {
        let book = calibration_fixture_book();
        let top_k = vec![1];
        let thresholds = vec![0.1, 0.6];
        let mut acc = EvalAccumulator::new(&top_k, 0.5, 0, 0, &thresholds);

        acc.observe(&book, &obs("s1", "a")).unwrap(); // confidence 0.05: below both thresholds
        acc.observe(&book, &obs("s2", "b")).unwrap(); // confidence 0.55: covers 0.1 only, miss
        acc.observe(&book, &obs("s3", "a")).unwrap(); // confidence 1.0: covers both, hit

        let report = acc.finish(0);
        assert_eq!(report.threshold_sweep.len(), 2); // always thresholds.len() entries, in request order

        let at_0_1 = &report.threshold_sweep[0];
        assert_eq!(at_0_1.min_confidence, 0.1);
        assert!((at_0_1.covered_fraction - 2.0 / 3.0).abs() < 1e-9); // s2, s3
        assert!((at_0_1.abstained_fraction - 1.0 / 3.0).abs() < 1e-9);
        assert_eq!(at_0_1.top1_hit_rate, Some(0.5)); // 1 hit (s3) of 2 covered
        assert_eq!(at_0_1.mean_reciprocal_rank, Some(0.5)); // (0.0 + 1.0) / 2

        let at_0_6 = &report.threshold_sweep[1];
        assert_eq!(at_0_6.min_confidence, 0.6);
        assert!((at_0_6.covered_fraction - 1.0 / 3.0).abs() < 1e-9); // s3 only
        assert!((at_0_6.abstained_fraction - 2.0 / 3.0).abs() < 1e-9);
        assert_eq!(at_0_6.top1_hit_rate, Some(1.0));
        assert_eq!(at_0_6.mean_reciprocal_rank, Some(1.0));
    }

    #[test]
    fn calibration_and_threshold_sweep_are_empty_when_not_requested() {
        // Default EvalConfig (calibration_bins: None, thresholds: empty) --
        // backward compat for existing callers.
        let train = "{\"sequence_id\":\"x\",\"step\":0,\"state\":\"s\",\"action\":\"a\",\"outcome\":\"success\"}\n";
        let output = evaluate(
            train.as_bytes(),
            train.as_bytes(),
            true,
            &BuildConfig::default(),
            &EvalConfig::default(),
        )
        .unwrap();
        assert!(output.report.confidence_calibration.is_empty());
        assert!(output.report.threshold_sweep.is_empty());
    }

    #[test]
    fn strict_mode_aborts_on_invalid_record_in_train_pass() {
        let train = "{\"sequence_id\":\"x\",\"step\":0,\"state\":\"\",\"action\":\"a\"}\n";
        let err = evaluate(
            train.as_bytes(),
            "".as_bytes(),
            true,
            &BuildConfig::default(),
            &EvalConfig::default(),
        )
        .unwrap_err();
        assert!(matches!(err, Error::EmptyState { line: 1 }));
    }

    #[test]
    fn strict_mode_aborts_on_invalid_record_in_test_pass() {
        let train = "{\"sequence_id\":\"x\",\"step\":0,\"state\":\"s\",\"action\":\"a\"}\n";
        let test = "{\"sequence_id\":\"y\",\"step\":0,\"state\":\"\",\"action\":\"a\"}\n";
        let err = evaluate(
            train.as_bytes(),
            test.as_bytes(),
            true,
            &BuildConfig::default(),
            &EvalConfig::default(),
        )
        .unwrap_err();
        assert!(matches!(err, Error::EmptyState { line: 1 }));
    }

    #[test]
    fn non_strict_mode_skips_invalid_records_without_duplicating_test_pass_warnings() {
        let train = "{\"sequence_id\":\"x\",\"step\":0,\"state\":\"s\",\"action\":\"a\"}\n{\"state\":\"\",\"action\":\"a\",\"sequence_id\":\"bad\",\"step\":0}\n";
        let test = "{\"sequence_id\":\"y\",\"step\":0,\"state\":\"\",\"action\":\"a\"}\n";
        let output = evaluate(
            train.as_bytes(),
            test.as_bytes(),
            false,
            &BuildConfig::default(),
            &EvalConfig::default(),
        )
        .unwrap();
        // Only the train pass's invalid line (2) is reported -- the test
        // pass's invalid line is skipped silently (decision 3).
        assert_eq!(output.warnings.len(), 1);
        assert_eq!(output.warnings[0].line, 2);
    }
}

/// Tuning knobs for [`evaluate`].
#[derive(Debug, Clone)]
pub struct EvalConfig {
    /// Fraction of sequences assigned to the train split (the rest go to
    /// test). See [`evaluate`]'s doc comment for how the split is decided.
    pub train_ratio: f64,
    /// Which top-k hit rates to report, e.g. `[1, 3, 5]`.
    pub top_k: Vec<usize>,
    /// Number of equal-width bins over `[0, 1]` for `confidence_calibration`.
    /// `None` (or `Some(0)`) skips calibration reporting (`confidence_calibration`
    /// comes back empty).
    pub calibration_bins: Option<usize>,
    /// Confidence thresholds to sweep for `threshold_sweep`. Empty skips it.
    pub thresholds: Vec<f64>,
}

impl Default for EvalConfig {
    fn default() -> Self {
        Self {
            train_ratio: 0.8,
            top_k: vec![1, 3, 5],
            calibration_bins: None,
            thresholds: Vec::new(),
        }
    }
}

/// Hit rate for one requested `k`. A `Vec` (not a map) so JSON output has a
/// deterministic order matching the order `top_k` was requested in.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TopKHitRate {
    pub k: usize,
    pub hit_rate: Option<f64>,
}

/// Ranking quality for one equal-width confidence bin of the #1 candidate,
/// among evaluated test observations whose top1 confidence fell in
/// `[min_confidence, max_confidence)` (the last bin is closed on both ends).
/// Always exactly `EvalConfig::calibration_bins` entries, in ascending bin
/// order, regardless of whether a given bin saw any observations.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CalibrationBin {
    pub min_confidence: f64,
    pub max_confidence: f64,
    pub num_evaluated: u64,
    pub top1_hit_rate: Option<f64>,
    pub mean_reciprocal_rank: Option<f64>,
}

/// Selective-prediction metrics at one confidence threshold: if the caller
/// only acted when the #1 candidate's confidence was `>= min_confidence`,
/// how often would they have predicted at all, and how good were those
/// predictions? Always exactly `EvalConfig::thresholds.len()` entries, in
/// the requested order.
///
/// `covered_fraction`/`abstained_fraction` are a *different* weighting
/// convention than [`EvalReport::coverage`]/[`EvalReport::fallback_rate`]:
/// both are observation-weighted here and sum to 1 by construction
/// (`abstained_fraction = 1.0 - covered_fraction`), whereas the top-level
/// fields deliberately don't (state- vs. observation-weighted). Named
/// differently on purpose so the two pairs are never confused for each other
/// in the same JSON report.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ThresholdSweepEntry {
    pub min_confidence: f64,
    /// Fraction of *all* test observations where the state had a candidate
    /// and its #1 confidence was `>= min_confidence`.
    pub covered_fraction: f64,
    /// `1.0 - covered_fraction`.
    pub abstained_fraction: f64,
    /// Accuracy among covered observations only (`None` if none were covered).
    pub top1_hit_rate: Option<f64>,
    /// Mean reciprocal rank among covered observations only.
    pub mean_reciprocal_rank: Option<f64>,
}

/// Ranking-quality report produced by [`evaluate`].
///
/// `coverage` and `fallback_rate` intentionally do *not* sum to 1: `coverage`
/// is state-weighted (fraction of *distinct* test states for which the
/// prior returned any candidate), while `fallback_rate` is
/// observation-weighted (fraction of *test observations* whose state had no
/// candidates). One rarely-seen state with no candidates barely moves
/// `fallback_rate` but still costs a full point of `coverage`, and vice
/// versa. The raw counts below let you recompute either framing yourself.
///
/// `top1_hit_rate`, `topk_hit_rate`, `mean_reciprocal_rank`,
/// `avg_rank_when_found`, and the confidence/score-lift fields are all
/// conditioned on "evaluated" (the state had >=1 candidate) -- there is no
/// rank to score when there was no prediction at all. `coverage` /
/// `fallback_rate` already answer "did we even have a prediction?"
/// separately.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct EvalReport {
    pub num_train_observations: u64,
    pub num_test_observations: u64,
    /// Number of distinct states seen among test observations.
    pub num_test_states: u64,
    /// Test observations whose state had >=1 candidate in the prior.
    pub num_evaluated_observations: u64,
    /// Test observations whose state had zero candidates.
    pub num_fallback_observations: u64,
    /// Distinct test states for which the prior returned >=1 candidate.
    pub num_test_states_with_candidates: u64,
    /// State-weighted: `num_test_states_with_candidates / num_test_states`.
    pub coverage: Option<f64>,
    /// Observation-weighted: `num_fallback_observations / num_test_observations`.
    pub fallback_rate: Option<f64>,
    /// Among evaluated observations, fraction where the actual action was
    /// the prior's #1 ranked candidate.
    pub top1_hit_rate: Option<f64>,
    pub topk_hit_rate: Vec<TopKHitRate>,
    /// Mean of `1/rank` over evaluated observations (0 contribution when
    /// the actual action isn't among the candidates at all).
    pub mean_reciprocal_rank: Option<f64>,
    /// Mean rank of the actual action, over evaluated observations where it
    /// was found among the candidates (excludes not-found cases).
    pub avg_rank_when_found: Option<f64>,
    /// Mean confidence of the #1 candidate, restricted to evaluated
    /// observations where that #1 candidate matched the actual action.
    pub avg_confidence_on_hit: Option<f64>,
    /// Same, restricted to evaluated observations where it did not match.
    pub avg_confidence_on_miss: Option<f64>,
    /// `mean(observed score | #1 candidate matched actual action) -
    /// mean(observed score | it didn't)`, `None` unless both sides have at
    /// least one scored observation. Tests whether following the prior's
    /// top pick correlates with a better observed outcome.
    pub score_lift: Option<f64>,
    /// `top1_hit_rate`, but each evaluated observation is weighted by its
    /// outcome credit (win=1.0, draw=`BuildConfig::draw_value`, loss/unknown=0)
    /// instead of counted equally -- see [`crate::model::outcome_credit`]. A
    /// failed or unrecorded-outcome observation contributes to neither the
    /// numerator nor the denominator, so this reads as "agreement rate,
    /// restricted to trials that actually succeeded (or partially, drew)."
    /// `None` when no evaluated observation earned positive credit.
    pub success_weighted_top1_hit_rate: Option<f64>,
    /// `mean_reciprocal_rank`, outcome-credit-weighted the same way as
    /// [`Self::success_weighted_top1_hit_rate`].
    pub success_weighted_mean_reciprocal_rank: Option<f64>,
    /// `top1_hit_rate`, restricted to evaluated observations whose outcome
    /// was exactly [`crate::model::Outcome::Failure`]. The counterweight to
    /// the success-weighted metrics above: a high value here means the
    /// prior's top pick agrees with actions that are known to have failed.
    /// `None` when the test set has zero `Failure` observations.
    pub failure_agreement_top1_hit_rate: Option<f64>,
    /// `top1_hit_rate`, but each evaluated observation is looked up via
    /// [`crate::model::PriorBook::query_with_context`] (the sequence's own
    /// recent-action window, with backoff) instead of plain
    /// [`crate::model::PriorBook::query`]. `top1_hit_rate` itself always
    /// stays order-0 -- this is the direct, same-run comparison point:
    /// `context_top1_hit_rate - top1_hit_rate` is the lift (or cost)
    /// context provides. `None` when `BuildConfig::context_order == 0`.
    pub context_top1_hit_rate: Option<f64>,
    /// `mean_reciprocal_rank`, context-aware the same way as
    /// [`Self::context_top1_hit_rate`]. `None` when
    /// `BuildConfig::context_order == 0`.
    pub context_mean_reciprocal_rank: Option<f64>,
    /// Accuracy *at* each context depth backoff actually reached, not just
    /// how often it was reached -- answers "is deeper context more
    /// accurate when available, or just rarer." Empty when
    /// `BuildConfig::context_order == 0`.
    pub hit_rate_by_matched_order: Vec<MatchedOrderHitRate>,
    /// Ranking quality bucketed by the #1 candidate's confidence. Empty
    /// unless [`EvalConfig::calibration_bins`] was set.
    pub confidence_calibration: Vec<CalibrationBin>,
    /// Coverage/accuracy tradeoff at each requested confidence threshold.
    /// Empty unless [`EvalConfig::thresholds`] was non-empty.
    pub threshold_sweep: Vec<ThresholdSweepEntry>,
}

/// One entry of [`EvalReport::hit_rate_by_matched_order`]: accuracy among
/// evaluated observations whose context-aware query backed off to exactly
/// `order` (`0` meaning the plain state-only rung).
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct MatchedOrderHitRate {
    pub order: usize,
    pub num_evaluated: u64,
    pub top1_hit_rate: Option<f64>,
}

/// Result of [`evaluate`]: the report plus warnings from the train pass.
/// Warnings are collected from the train pass only -- when both readers
/// point at the same file (the only way the CLI uses this), a malformed
/// line is malformed identically in both passes, so a second collection
/// would just duplicate the first. The test pass still skips (non-strict)
/// or aborts (strict) on invalid records; it just doesn't re-report them.
#[derive(Debug)]
pub struct EvalOutput {
    pub report: EvalReport,
    pub warnings: Vec<Warning>,
}

/// Deterministically assigns `sequence_id` to the train split with
/// probability `train_ratio`, based purely on the id's own hash -- every
/// observation in the same sequence lands on the same side (no leakage)
/// without needing to look at the rest of the dataset, and streams fine
/// since each line can be classified independently. The train/test split
/// must stay reproducible if eval is re-run after a toolchain upgrade,
/// hence `crate::hash::fnv1a` rather than a stdlib hasher (see its doc
/// comment).
fn is_train(sequence_id: &str, train_ratio: f64) -> bool {
    let bucket = crate::hash::fnv1a(sequence_id.as_bytes()) % 100;
    let train_pct = (train_ratio * 100.0).round().clamp(0.0, 100.0) as u64;
    bucket < train_pct
}

/// Online per-bin totals for `confidence_calibration` -- sized to
/// `EvalConfig::calibration_bins`, never to the number of observations.
#[derive(Debug, Default, Clone, Copy)]
struct CalibrationBinAcc {
    num_evaluated: u64,
    hit_count: u64,
    reciprocal_rank_sum: f64,
}

/// Online per-threshold totals for `threshold_sweep` -- sized to
/// `EvalConfig::thresholds.len()`, never to the number of observations.
#[derive(Debug, Default, Clone, Copy)]
struct ThresholdAcc {
    covered_count: u64,
    hit_count: u64,
    reciprocal_rank_sum: f64,
}

/// Online per-matched-order totals for `hit_rate_by_matched_order`.
#[derive(Debug, Default, Clone, Copy)]
struct MatchedOrderAcc {
    num_evaluated: u64,
    hit_count: u64,
}

/// Pass-2 bookkeeping: ranks each test observation's actual action against
/// the trained prior's candidates for its state, accumulating the sums
/// [`EvalReport`] is built from. Mirrors [`PriorAccumulator`]'s
/// new/observe/finish shape. Memory stays bounded by `top_k.len()` +
/// `calibration_bins` + `thresholds.len()`, never by the number of
/// observations -- calibration/threshold-sweep bucketing happens online,
/// the same way every other metric here does.
struct EvalAccumulator<'a> {
    top_k: &'a [usize],
    draw_value: f64,
    context_order: usize,
    context_tracker: SequenceContextTracker,
    context_top1_hit_count: u64,
    context_reciprocal_rank_sum: f64,
    /// Keyed by matched order (`0` = order-0 rung). Small -- bounded by
    /// `context_order`, never by observation count.
    matched_order_counts: HashMap<usize, MatchedOrderAcc>,
    num_test_observations: u64,
    test_states_seen: HashSet<String>,
    states_with_candidates_count: u64,
    fallback_count: u64,
    evaluated_count: u64,
    top1_hit_count: u64,
    topk_hit_counts: HashMap<usize, u64>,
    reciprocal_rank_sum: f64,
    rank_sum_when_found: f64,
    found_count: u64,
    success_weight_sum: f64,
    success_weighted_hit_sum: f64,
    success_weighted_reciprocal_rank_sum: f64,
    failure_count: u64,
    failure_hit_count: u64,
    confidence_sum_on_hit: f64,
    confidence_count_on_hit: u64,
    confidence_sum_on_miss: f64,
    confidence_count_on_miss: u64,
    score_sum_on_hit: f64,
    score_count_on_hit: u64,
    score_sum_on_miss: f64,
    score_count_on_miss: u64,
    calibration_bin_width: f64,
    calibration: Vec<CalibrationBinAcc>,
    thresholds: &'a [f64],
    threshold_accs: Vec<ThresholdAcc>,
}

impl<'a> EvalAccumulator<'a> {
    fn new(
        top_k: &'a [usize],
        draw_value: f64,
        context_order: usize,
        calibration_bins: usize,
        thresholds: &'a [f64],
    ) -> Self {
        let calibration_bin_width = if calibration_bins > 0 {
            1.0 / calibration_bins as f64
        } else {
            0.0
        };
        Self {
            top_k,
            draw_value,
            context_order,
            context_tracker: SequenceContextTracker::new(context_order),
            context_top1_hit_count: 0,
            context_reciprocal_rank_sum: 0.0,
            matched_order_counts: HashMap::new(),
            num_test_observations: 0,
            test_states_seen: HashSet::new(),
            states_with_candidates_count: 0,
            fallback_count: 0,
            evaluated_count: 0,
            top1_hit_count: 0,
            topk_hit_counts: HashMap::new(),
            reciprocal_rank_sum: 0.0,
            rank_sum_when_found: 0.0,
            found_count: 0,
            success_weight_sum: 0.0,
            success_weighted_hit_sum: 0.0,
            success_weighted_reciprocal_rank_sum: 0.0,
            failure_count: 0,
            failure_hit_count: 0,
            confidence_sum_on_hit: 0.0,
            confidence_count_on_hit: 0,
            confidence_sum_on_miss: 0.0,
            confidence_count_on_miss: 0,
            score_sum_on_hit: 0.0,
            score_count_on_hit: 0,
            score_sum_on_miss: 0.0,
            score_count_on_miss: 0,
            calibration_bin_width,
            calibration: vec![CalibrationBinAcc::default(); calibration_bins],
            thresholds,
            threshold_accs: vec![ThresholdAcc::default(); thresholds.len()],
        }
    }

    fn observe(&mut self, book: &PriorBook, obs: &Observation) -> Result<()> {
        // Validated (and the window advanced) unconditionally, same as
        // PriorAccumulator::observe -- the test split needs its own
        // sortedness precondition, independent of the train split's.
        let window = self.context_tracker.advance(obs)?;

        self.num_test_observations += 1;
        let is_new_state = self.test_states_seen.insert(obs.state.clone());
        let candidates = book.query(&obs.state, None);

        if candidates.is_empty() {
            self.fallback_count += 1;
            return Ok(());
        }
        if is_new_state {
            self.states_with_candidates_count += 1;
        }
        self.evaluated_count += 1;

        let top1 = &candidates[0];
        let is_hit = top1.action == obs.action;
        if is_hit {
            self.top1_hit_count += 1;
            self.confidence_sum_on_hit += top1.confidence;
            self.confidence_count_on_hit += 1;
            if let Some(score) = obs.score {
                self.score_sum_on_hit += score;
                self.score_count_on_hit += 1;
            }
        } else {
            self.confidence_sum_on_miss += top1.confidence;
            self.confidence_count_on_miss += 1;
            if let Some(score) = obs.score {
                self.score_sum_on_miss += score;
                self.score_count_on_miss += 1;
            }
        }

        let rank = candidates
            .iter()
            .position(|c| c.action == obs.action)
            .map(|index| index + 1);
        // Same convention `mean_reciprocal_rank` uses: 0 contribution when
        // the action wasn't found among the candidates at all.
        let reciprocal_rank = rank.map_or(0.0, |r| 1.0 / r as f64);
        if let Some(rank) = rank {
            self.found_count += 1;
            self.rank_sum_when_found += rank as f64;
            self.reciprocal_rank_sum += reciprocal_rank;
            for &k in self.top_k {
                if rank <= k {
                    *self.topk_hit_counts.entry(k).or_insert(0) += 1;
                }
            }
        }

        let credit = outcome_credit(obs.outcome, self.draw_value);
        self.success_weight_sum += credit;
        if is_hit {
            self.success_weighted_hit_sum += credit;
        }
        self.success_weighted_reciprocal_rank_sum += credit * reciprocal_rank;
        if obs.outcome == Outcome::Failure {
            self.failure_count += 1;
            if is_hit {
                self.failure_hit_count += 1;
            }
        }

        if self.context_order > 0 {
            // `candidates` (order-0) is already known non-empty here, so
            // query_with_context's final backoff rung -- which is literally
            // `book.query(state, top_k)` -- can never come back empty
            // either.
            let context_result = book.query_with_context(&obs.state, &window, None);
            let context_top1 = &context_result.candidates[0];
            let context_is_hit = context_top1.action == obs.action;
            if context_is_hit {
                self.context_top1_hit_count += 1;
            }
            let context_rank = context_result
                .candidates
                .iter()
                .position(|c| c.action == obs.action)
                .map(|index| index + 1);
            self.context_reciprocal_rank_sum += context_rank.map_or(0.0, |r| 1.0 / r as f64);

            let order_acc = self
                .matched_order_counts
                .entry(context_result.matched_order)
                .or_default();
            order_acc.num_evaluated += 1;
            if context_is_hit {
                order_acc.hit_count += 1;
            }
        }

        if !self.calibration.is_empty() {
            let bins = self.calibration.len();
            let idx = ((top1.confidence / self.calibration_bin_width) as usize).min(bins - 1);
            let bin = &mut self.calibration[idx];
            bin.num_evaluated += 1;
            if is_hit {
                bin.hit_count += 1;
            }
            bin.reciprocal_rank_sum += reciprocal_rank;
        }

        for (acc, &threshold) in self.threshold_accs.iter_mut().zip(self.thresholds) {
            if top1.confidence >= threshold {
                acc.covered_count += 1;
                if is_hit {
                    acc.hit_count += 1;
                }
                acc.reciprocal_rank_sum += reciprocal_rank;
            }
        }

        Ok(())
    }

    fn finish(self, num_train_observations: u64) -> EvalReport {
        let num_test_states = self.test_states_seen.len() as u64;
        let coverage = ratio(
            self.states_with_candidates_count as f64,
            num_test_states as f64,
        );
        let fallback_rate = ratio(
            self.fallback_count as f64,
            self.num_test_observations as f64,
        );
        let evaluated = self.evaluated_count as f64;

        let topk_hit_rate = self
            .top_k
            .iter()
            .map(|&k| TopKHitRate {
                k,
                hit_rate: ratio(
                    *self.topk_hit_counts.get(&k).unwrap_or(&0) as f64,
                    evaluated,
                ),
            })
            .collect();

        let score_lift = match (
            ratio(self.score_sum_on_hit, self.score_count_on_hit as f64),
            ratio(self.score_sum_on_miss, self.score_count_on_miss as f64),
        ) {
            (Some(hit), Some(miss)) => Some(hit - miss),
            _ => None,
        };

        let confidence_calibration: Vec<CalibrationBin> = self
            .calibration
            .iter()
            .enumerate()
            .map(|(i, bin)| {
                let n = bin.num_evaluated as f64;
                CalibrationBin {
                    min_confidence: i as f64 * self.calibration_bin_width,
                    max_confidence: (i as f64 + 1.0) * self.calibration_bin_width,
                    num_evaluated: bin.num_evaluated,
                    top1_hit_rate: ratio(bin.hit_count as f64, n),
                    mean_reciprocal_rank: ratio(bin.reciprocal_rank_sum, n),
                }
            })
            .collect();

        let threshold_sweep: Vec<ThresholdSweepEntry> = self
            .thresholds
            .iter()
            .zip(self.threshold_accs.iter())
            .map(|(&threshold, acc)| {
                let covered_fraction =
                    ratio(acc.covered_count as f64, self.num_test_observations as f64)
                        .unwrap_or(0.0);
                ThresholdSweepEntry {
                    min_confidence: threshold,
                    covered_fraction,
                    abstained_fraction: 1.0 - covered_fraction,
                    top1_hit_rate: ratio(acc.hit_count as f64, acc.covered_count as f64),
                    mean_reciprocal_rank: ratio(acc.reciprocal_rank_sum, acc.covered_count as f64),
                }
            })
            .collect();

        // `None`/empty when context_order == 0: a context-aware query
        // always resolves immediately to the order-0 rung in that case, so
        // these would just duplicate top1_hit_rate/mean_reciprocal_rank
        // rather than carry any new information.
        let (context_top1_hit_rate, context_mean_reciprocal_rank, hit_rate_by_matched_order) =
            if self.context_order > 0 {
                let mut orders: Vec<usize> = self.matched_order_counts.keys().copied().collect();
                orders.sort_unstable();
                let by_order = orders
                    .into_iter()
                    .map(|order| {
                        let acc = self.matched_order_counts[&order];
                        MatchedOrderHitRate {
                            order,
                            num_evaluated: acc.num_evaluated,
                            top1_hit_rate: ratio(acc.hit_count as f64, acc.num_evaluated as f64),
                        }
                    })
                    .collect();
                (
                    ratio(self.context_top1_hit_count as f64, evaluated),
                    ratio(self.context_reciprocal_rank_sum, evaluated),
                    by_order,
                )
            } else {
                (None, None, Vec::new())
            };

        EvalReport {
            num_train_observations,
            num_test_observations: self.num_test_observations,
            num_test_states,
            num_evaluated_observations: self.evaluated_count,
            num_fallback_observations: self.fallback_count,
            num_test_states_with_candidates: self.states_with_candidates_count,
            coverage,
            fallback_rate,
            top1_hit_rate: ratio(self.top1_hit_count as f64, evaluated),
            topk_hit_rate,
            mean_reciprocal_rank: ratio(self.reciprocal_rank_sum, evaluated),
            avg_rank_when_found: ratio(self.rank_sum_when_found, self.found_count as f64),
            avg_confidence_on_hit: ratio(
                self.confidence_sum_on_hit,
                self.confidence_count_on_hit as f64,
            ),
            avg_confidence_on_miss: ratio(
                self.confidence_sum_on_miss,
                self.confidence_count_on_miss as f64,
            ),
            score_lift,
            success_weighted_top1_hit_rate: ratio(
                self.success_weighted_hit_sum,
                self.success_weight_sum,
            ),
            success_weighted_mean_reciprocal_rank: ratio(
                self.success_weighted_reciprocal_rank_sum,
                self.success_weight_sum,
            ),
            failure_agreement_top1_hit_rate: ratio(
                self.failure_hit_count as f64,
                self.failure_count as f64,
            ),
            context_top1_hit_rate,
            context_mean_reciprocal_rank,
            hit_rate_by_matched_order,
            confidence_calibration,
            threshold_sweep,
        }
    }
}

/// Builds a prior from a sequence-held-out train split and reports how well
/// it ranks the actual action taken on the held-out test split.
///
/// Two streaming passes, each bounded by unique `(state, action)` pairs /
/// unique test states rather than total observation count, matching
/// [`crate::build_prior_book_from_reader`]'s memory profile:
///
/// 1. Read `train_reader`; observations whose `sequence_id` hashes into the
///    train bucket (see [`is_train`]) fold into a [`PriorAccumulator`].
/// 2. Read `test_reader`; observations whose `sequence_id` hashes into the
///    test bucket are ranked against the now-finished prior book.
///
/// Splitting by `sequence_id` (not by individual observation) keeps every
/// step of the same sequence on one side -- otherwise later steps could
/// leak information about earlier ones across the train/test boundary.
///
/// `train_reader` and `test_reader` are independent parameters (not a
/// single reader read twice) so the core stays IO-agnostic, matching
/// `build_prior_book_from_reader`'s precedent; the CLI opens the same file
/// path twice to get this shape.
///
/// Strict mode aborts on the first invalid record in *either* pass.
/// Non-strict mode skips invalid records in both passes; only the train
/// pass's skips are collected as [`Warning`]s (see [`EvalOutput`]'s doc
/// comment for why).
pub fn evaluate(
    train_reader: impl Read,
    test_reader: impl Read,
    strict: bool,
    build_config: &BuildConfig,
    eval_config: &EvalConfig,
) -> Result<EvalOutput> {
    let mut acc = PriorAccumulator::new(build_config)?;
    let mut warnings = Vec::new();
    let mut num_train_observations = 0u64;

    for (index, line) in BufReader::new(train_reader).lines().enumerate() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        let line_no = index + 1;

        match parse_line(&line, line_no) {
            Ok(observation) => {
                if is_train(&observation.sequence_id, eval_config.train_ratio) {
                    acc.observe(&observation)?;
                    num_train_observations += 1;
                }
            }
            Err(err) if strict => return Err(err),
            Err(err) => warnings.push(Warning {
                line: line_no,
                message: err.to_string(),
            }),
        }
    }
    let book = acc.finish();

    let mut eval_acc = EvalAccumulator::new(
        &eval_config.top_k,
        build_config.draw_value,
        build_config.context_order,
        eval_config.calibration_bins.unwrap_or(0),
        &eval_config.thresholds,
    );
    for (index, line) in BufReader::new(test_reader).lines().enumerate() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        let line_no = index + 1;

        match parse_line(&line, line_no) {
            Ok(observation) => {
                if !is_train(&observation.sequence_id, eval_config.train_ratio) {
                    eval_acc.observe(&book, &observation)?;
                }
            }
            Err(err) if strict => return Err(err),
            Err(_) => {}
        }
    }

    Ok(EvalOutput {
        report: eval_acc.finish(num_train_observations),
        warnings,
    })
}