ktstr 0.6.0

Test harness for Linux process schedulers
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
//! BPF-axis projection for [`SampleSeries`].
//!
//! Each [`Sample`](super::Sample) carries a frozen [`Snapshot`] over
//! BPF program state captured at the freeze rendezvous. This module
//! exposes the closure-based [`SampleSeries::bpf`] projection (manual
//! field access via the Snapshot accessor surface) and the auto-
//! discovering [`SampleSeries::bpf_map`] → [`BpfMapProjector`] pair
//! that enumerates a map's struct members and projects each as
//! `SeriesField<u64>` / `SeriesField<i64>` / `SeriesField<f64>`.
//!
//! Orthogonal to [`super::stats`]: the BPF axis sources its values
//! from the kernel-side BPF state (counters, ringbuf items, struct
//! members); the stats axis sources from the userspace scheduler's
//! `scx_stats` JSON. Tests typically use both — BPF for low-level
//! state, stats for scheduler-author-defined metrics.

use crate::assert::temporal::SeriesField;
use crate::scenario::snapshot::{Snapshot, SnapshotField, SnapshotResult};

use super::{SampleSeries, build_series_field};

impl SampleSeries {
    /// Project the series along the BPF axis. The closure receives
    /// each sample's [`Snapshot`] and returns a
    /// [`SnapshotResult<T>`] — typically a typed value extracted
    /// via `snap.var(...).as_u64()` or
    /// `snap.map(...).at(...).get(...).as_u64()`. Errors flow
    /// through into the resulting [`SeriesField`] as per-sample
    /// `Err` slots so a temporal-assertion pattern can decide
    /// whether to fail or skip on a missing field.
    ///
    /// `label` is owned (`impl Into<String>`) and lands in
    /// [`crate::assert::temporal::SeriesField::label`] for failure-
    /// message rendering. Callers may pass a `&'static str` literal
    /// or a runtime-built `String` (for auto-discovered struct or
    /// JSON key names).
    pub fn bpf<T, F>(&self, label: impl Into<String>, project: F) -> SeriesField<T>
    where
        F: Fn(&Snapshot<'_>) -> SnapshotResult<T>,
    {
        build_series_field(&self.rows, label, |row| {
            // Placeholder reports carry no real BPF state — the
            // freeze rendezvous timed out (or the capture pipeline
            // otherwise failed). Surface a dedicated PlaceholderSample
            // error variant BEFORE invoking the projection closure
            // so the temporal-assertion patterns can branch on
            // "placeholder, skip" distinctly from "field missing,
            // skip" when rendering the verdict's skip-Note.
            if row.report.is_placeholder {
                return Err(
                    crate::scenario::snapshot::SnapshotError::PlaceholderSample {
                        tag: row.tag.clone(),
                        reason: row
                            .report
                            .scx_walker_unavailable
                            .clone()
                            .unwrap_or_else(|| "placeholder report".to_string()),
                    },
                );
            }
            let snap = Snapshot::new(&row.report);
            project(&snap)
        })
    }

    /// Project the live scheduler's `<obj>.<section>` global
    /// variable named `name` as `u64`. Per-row equivalent of
    /// `snap.live_var(name).as_u64()`, but with the placeholder
    /// short-circuit baked in.
    ///
    /// **Why this exists.** Single-binary tests can use
    /// `series.bpf("label", |s| s.var(name).as_u64())` directly —
    /// `var()` auto-disambiguates via the active-scheduler walker
    /// when multiple maps share a global symbol (e.g. post-
    /// `Op::ReplaceScheduler` with two scheduler instances). The
    /// `bpf_live_u64` helper saves the closure boilerplate AND
    /// makes the live-resolution semantics visible in the call
    /// site's NAME, not buried in a projector body. The label on
    /// the resulting [`SeriesField`] is the `name` argument
    /// verbatim.
    pub fn bpf_live_u64(&self, name: &str) -> SeriesField<u64> {
        self.bpf_live_phase_stable(name, |f| f.as_u64())
    }

    /// Sibling of [`Self::bpf_live_u64`] projecting as `i64`.
    pub fn bpf_live_i64(&self, name: &str) -> SeriesField<i64> {
        self.bpf_live_phase_stable(name, |f| f.as_i64())
    }

    /// Sibling of [`Self::bpf_live_u64`] projecting as `f64`.
    pub fn bpf_live_f64(&self, name: &str) -> SeriesField<f64> {
        self.bpf_live_phase_stable(name, |f| f.as_f64())
    }

    /// Shared phase-stable projector for the `bpf_live_*` trio.
    ///
    /// Per-snapshot the underlying [`Snapshot::live_var`] correctly
    /// disambiguates between bss copies via the walker-populated
    /// [`crate::monitor::dump::FailureDumpReport::active_map_kvas`].
    /// But across snapshots in the same phase, the walker can
    /// re-publish (typical cause: post-`Op::ReplaceScheduler` swap
    /// window) and successive snapshots can correctly pick
    /// DIFFERENT bss copies — producing a non-monotonic counter
    /// series that downstream reducers like
    /// [`crate::assert::temporal::SeriesField::counter_delta_per_phase`]
    /// can't reason about.
    ///
    /// This projector adds a phase-stability gate on top of the
    /// per-snapshot pick. Two checks fire per phase:
    ///
    /// 1. **KVA drift within a walker-resolved set.** For each
    ///    phase, pin to the FIRST sample whose
    ///    `active_map_kvas` is non-empty. Later same-phase
    ///    samples whose `active_map_kvas` matches the pin pass
    ///    through. Later same-phase samples whose `active_map_kvas`
    ///    differs surface as
    ///    [`crate::scenario::snapshot::SnapshotError::WalkerDriftedWithinPhase`]
    ///    (the walker re-published mid-phase, typically because
    ///    an `Op::ReplaceScheduler` swap fired between snapshots).
    /// 2. **Cross-scheduler leak via walker-absent samples.** If
    ///    a phase contains at least one walker-resolved sample
    ///    (non-empty `active_map_kvas`), every OTHER same-phase
    ///    sample MUST also be walker-resolved. An empty-kvas
    ///    sample in such a phase came from a pre-walker capture
    ///    window OR a different scheduler instance entirely —
    ///    its `Snapshot::live_var` read cannot be proven to come
    ///    from the same bss as the pinned samples, so the value
    ///    is non-comparable. Surface as
    ///    `WalkerDriftedWithinPhase` with `sample_kvas = []`
    ///    (the empty vec signals "this sample had no walker
    ///    output" as distinct from "the walker output disagreed").
    ///    The temporal patterns' standard error-skip semantics
    ///    drop these samples from per-phase reducers like
    ///    `counter_delta_per_phase`.
    ///
    /// Samples in a phase with NO walker-resolved siblings pass
    /// through unchanged — the single-scheduler / pre-walker
    /// case where the consumer's per-snapshot
    /// [`Snapshot::active`] resolution is the only signal
    /// available.
    fn bpf_live_phase_stable<T, P>(&self, name: &str, project: P) -> SeriesField<T>
    where
        P: Fn(&SnapshotField<'_>) -> SnapshotResult<T>,
    {
        let label = name.to_string();
        let name_owned = name.to_string();
        // Pre-scan: identify phases that ever have a walker-resolved
        // sample (non-empty active_map_kvas). Walker-absent samples
        // in those phases are flagged as cross-scheduler-leak risks
        // by the main loop below.
        let mut phases_with_walker: std::collections::BTreeSet<crate::assert::Phase> =
            std::collections::BTreeSet::new();
        for row in &self.rows {
            if row.report.is_placeholder {
                continue;
            }
            if !row.report.active_map_kvas.is_empty()
                && let Some(ph) = row.step_index.map(crate::assert::Phase::from)
            {
                phases_with_walker.insert(ph);
            }
        }
        let mut values: Vec<SnapshotResult<T>> = Vec::with_capacity(self.rows.len());
        let mut tags: Vec<String> = Vec::with_capacity(self.rows.len());
        let mut elapsed: Vec<u64> = Vec::with_capacity(self.rows.len());
        let mut phases: Vec<Option<crate::assert::Phase>> = Vec::with_capacity(self.rows.len());
        let mut phase_kva_pin: std::collections::BTreeMap<crate::assert::Phase, Vec<u64>> =
            std::collections::BTreeMap::new();
        for row in &self.rows {
            tags.push(row.tag.clone());
            elapsed.push(row.elapsed_ms);
            let phase = row.step_index.map(crate::assert::Phase::from);
            phases.push(phase);

            if row.report.is_placeholder {
                values.push(Err(
                    crate::scenario::snapshot::SnapshotError::PlaceholderSample {
                        tag: row.tag.clone(),
                        reason: row
                            .report
                            .scx_walker_unavailable
                            .clone()
                            .unwrap_or_else(|| "placeholder report".to_string()),
                    },
                ));
                continue;
            }
            let snap = Snapshot::new(&row.report);
            let field = snap.live_var(&name_owned);
            let value = project(&field);
            let sample_kvas: &[u64] = row.report.active_map_kvas.as_slice();

            match (value, phase) {
                (Ok(v), Some(ph)) if !sample_kvas.is_empty() => {
                    let pin = phase_kva_pin
                        .entry(ph)
                        .or_insert_with(|| sample_kvas.to_vec());
                    if pin.as_slice() == sample_kvas {
                        values.push(Ok(v));
                    } else {
                        values.push(Err(
                            crate::scenario::snapshot::SnapshotError::WalkerDriftedWithinPhase {
                                phase: ph,
                                pinned_kvas: pin.clone(),
                                sample_kvas: sample_kvas.to_vec(),
                                requested: name_owned.clone(),
                            },
                        ));
                    }
                }
                (Ok(_v), Some(ph))
                    if sample_kvas.is_empty() && phases_with_walker.contains(&ph) =>
                {
                    // Cross-scheduler leak guard: this sample had
                    // no walker output but a sibling sample in the
                    // same phase did. The Ok value cannot be proven
                    // to come from the same scheduler as the pinned
                    // siblings — surface as drift with empty
                    // sample_kvas to disambiguate from "walker
                    // output disagreed".
                    let pinned = phase_kva_pin.get(&ph).cloned().unwrap_or_default();
                    values.push(Err(
                        crate::scenario::snapshot::SnapshotError::WalkerDriftedWithinPhase {
                            phase: ph,
                            pinned_kvas: pinned,
                            sample_kvas: Vec::new(),
                            requested: name_owned.clone(),
                        },
                    ));
                }
                (other, _) => values.push(other),
            }
        }
        SeriesField::from_parts_with_phases(label, tags, elapsed, values, phases)
    }

    /// Per-snapshot co-picked BPF projection of N counters from the
    /// SAME global-section map. Lifts [`Snapshot::live_vars_via`] to
    /// the series level: for each sample, calls the picker ONCE per
    /// snapshot and projects the resulting `N` `SnapshotField`s as
    /// `u64` into `N` parallel [`SeriesField`]s.
    ///
    /// **Why this exists.** The single-name `Self::bpf` closure shape
    /// forces tests that need two co-picked counters (e.g.
    /// `nr_cross_dispatch` + `nr_same_dispatch` from the same
    /// scheduler bss copy after `Op::ReplaceScheduler`) to call the
    /// picker TWICE per snapshot — once for each derived
    /// `SeriesField` — paying picker cost `2N` instead of `N`. The
    /// per-snapshot dedup happens here: one `live_vars_via` call per
    /// row, eagerly split into `N` u64 vectors before any
    /// `SeriesField` materializes.
    ///
    /// **Lifetime / coverage gaps surface per field.** If a snapshot
    /// is a placeholder, every field's slot for that row carries the
    /// same [`crate::scenario::snapshot::SnapshotError::PlaceholderSample`].
    /// If `live_vars_via` fails (no candidate map has all `N` names,
    /// or the picker returns `None`), every field's slot carries the
    /// same underlying [`crate::scenario::snapshot::SnapshotError`] —
    /// the failure is shared, not split. Per-field `.as_u64()` casts
    /// that fail (the picked field doesn't render as a u64) surface
    /// as per-field
    /// [`crate::scenario::snapshot::SnapshotError::TypeMismatch`]
    /// without contaminating sibling fields.
    ///
    /// The label routed onto each resulting [`SeriesField`] is the
    /// caller-supplied name from `names` at the matching position.
    pub fn live_bpf_vars_via<const N: usize, P>(
        &self,
        names: [&str; N],
        picker: P,
    ) -> [SeriesField<u64>; N]
    where
        P: for<'a> Fn(&[(&'a str, Vec<SnapshotField<'a>>)]) -> Option<usize> + Copy,
    {
        let mut per_field: [Vec<crate::scenario::snapshot::SnapshotResult<u64>>; N] =
            std::array::from_fn(|_| Vec::with_capacity(self.rows.len()));
        let mut tags: Vec<String> = Vec::with_capacity(self.rows.len());
        let mut elapsed: Vec<u64> = Vec::with_capacity(self.rows.len());
        let mut phases: Vec<Option<crate::assert::Phase>> = Vec::with_capacity(self.rows.len());

        for row in &self.rows {
            tags.push(row.tag.clone());
            elapsed.push(row.elapsed_ms);
            phases.push(row.step_index.map(crate::assert::Phase::from));

            if row.report.is_placeholder {
                let err = crate::scenario::snapshot::SnapshotError::PlaceholderSample {
                    tag: row.tag.clone(),
                    reason: row
                        .report
                        .scx_walker_unavailable
                        .clone()
                        .unwrap_or_else(|| "placeholder report".to_string()),
                };
                for slot in &mut per_field {
                    slot.push(Err(err.clone()));
                }
                continue;
            }

            let snap = Snapshot::new(&row.report);
            // Slice cast: live_vars_via takes &[&str], we hold [&str; N].
            match snap.live_vars_via(&names, picker) {
                Ok(fields) => {
                    debug_assert_eq!(fields.len(), N);
                    for (i, field) in fields.into_iter().enumerate() {
                        per_field[i].push(field.as_u64());
                    }
                }
                Err(e) => {
                    for slot in &mut per_field {
                        slot.push(Err(e.clone()));
                    }
                }
            }
        }

        // Build N SeriesFields, each consuming its own per-field
        // value vector. Tags / elapsed / phases share the same
        // sample identity across fields — clone for each output.
        std::array::from_fn(|i| {
            crate::assert::temporal::SeriesField::from_parts_with_phases(
                names[i].to_string(),
                tags.clone(),
                elapsed.clone(),
                std::mem::take(&mut per_field[i]),
                phases.clone(),
            )
        })
    }

    /// Auto-project a top-level BPF map's struct members. The
    /// returned [`BpfMapProjector`] auto-discovers struct member
    /// names at sample 0 and exposes them via `.field_u64(name)` /
    /// `.field_i64(name)` / `.field_f64(name)` — a caller that
    /// wants every scalar field of a BSS struct without
    /// enumerating each one by hand calls
    /// `series.bpf_map("scx_obj.bss").at(0)` and then
    /// `.field_u64("nr_dispatched")` for the field of interest.
    ///
    /// **Top-level scalar fields only.** The auto-projector reads
    /// directly-named struct members (e.g. `"nr_dispatched"`,
    /// `"stall"`). Nested struct members (e.g. `"ctx.weight"`) and
    /// deeper paths are NOT auto-discoverable through the typed
    /// `field_*` helpers — for those, use the manual closure
    /// projection [`SampleSeries::bpf`] with
    /// `|snap| snap.var("ctx").get("weight").as_u64()` (or the
    /// equivalent map-walking shape). Per-CPU maps are also out
    /// of scope: they require an explicit `.cpu(N)` narrow on
    /// the [`Snapshot`] accessor surface, so callers route
    /// through the manual closure path for those as well.
    pub fn bpf_map<'a>(&'a self, map_name: &'a str) -> BpfMapProjector<'a> {
        BpfMapProjector {
            series: self,
            map_name,
            entry_index: 0,
        }
    }
}

/// Auto-projector handle returned by [`SampleSeries::bpf_map`].
/// Lazily resolves the named map's value at the requested entry
/// index when `Self::field` is invoked.
pub struct BpfMapProjector<'a> {
    series: &'a SampleSeries,
    map_name: &'a str,
    entry_index: usize,
}

impl<'a> BpfMapProjector<'a> {
    /// Pin the entry index for the projection. Defaults to `0`
    /// (typical for ARRAY / `.bss` / `.data` / `.rodata` maps,
    /// which carry a single value at index 0). Use this to walk
    /// into a HASH map at a specific ordinal.
    pub fn at(mut self, index: usize) -> Self {
        self.entry_index = index;
        self
    }

    /// Project a single named struct field as `u64` (the most
    /// common temporal-assertion shape — counters, byte counts).
    /// The label routed onto the resulting [`SeriesField`] is the
    /// caller-supplied field name; combined with the map name in
    /// the diagnostic the failure message reads
    /// `"<map>.<entry_index>.<field>"`.
    pub fn field_u64(&self, field: &str) -> SeriesField<u64> {
        let map_name = self.map_name.to_string();
        let entry_index = self.entry_index;
        let field_owned = field.to_string();
        self.series.bpf(field, move |snap| {
            let entry = match snap.map(&map_name) {
                Ok(m) => m.at(entry_index),
                Err(e) => return Err(e),
            };
            entry.get(&field_owned).as_u64()
        })
    }

    /// Project a single named struct field as `i64`.
    pub fn field_i64(&self, field: &str) -> SeriesField<i64> {
        let map_name = self.map_name.to_string();
        let entry_index = self.entry_index;
        let field_owned = field.to_string();
        self.series.bpf(field, move |snap| {
            let entry = match snap.map(&map_name) {
                Ok(m) => m.at(entry_index),
                Err(e) => return Err(e),
            };
            entry.get(&field_owned).as_i64()
        })
    }

    /// Project a single named struct field as `f64`.
    pub fn field_f64(&self, field: &str) -> SeriesField<f64> {
        let map_name = self.map_name.to_string();
        let entry_index = self.entry_index;
        let field_owned = field.to_string();
        self.series.bpf(field, move |snap| {
            let entry = match snap.map(&map_name) {
                Ok(m) => m.at(entry_index),
                Err(e) => return Err(e),
            };
            entry.get(&field_owned).as_f64()
        })
    }

    /// Discover the struct member names of the map's first
    /// rendered value. Empty when the map is missing in sample 0
    /// or its value is not a struct. Useful for tests that want
    /// to enumerate every scalar field for a blanket assertion.
    pub fn member_names(&self) -> Vec<String> {
        let row = match self.series.rows.first() {
            Some(r) => r,
            None => return Vec::new(),
        };
        let snap = Snapshot::new(&row.report);
        let map = match snap.map(self.map_name) {
            Ok(m) => m,
            Err(_) => return Vec::new(),
        };
        let entry = map.at(self.entry_index);
        // Walk the entry's value — SnapshotEntry doesn't expose
        // its struct members directly, but the rendered_value()
        // accessor on the field-with-empty-path does.
        let field = entry.get("");
        match field {
            SnapshotField::Value(crate::monitor::btf_render::RenderedValue::Struct {
                members,
                ..
            }) => members.iter().map(|m| m.name.clone()).collect(),
            _ => Vec::new(),
        }
    }

    /// Project every struct member that resolves as `u64` for at
    /// least one sample. Iterates [`Self::member_names`], calls
    /// [`Self::field_u64`] for each, and keeps the entries whose
    /// resulting [`SeriesField`] has at least one `Ok` value —
    /// non-numeric members (strings, nested structs, floats) drop
    /// out because their `as_u64()` cast always errors.
    pub fn u64_fields(&self) -> Vec<(String, SeriesField<u64>)> {
        self.member_names()
            .into_iter()
            .filter_map(|name| {
                let field = self.field_u64(&name);
                // Bind the predicate result and drop the
                // values_iter borrow before moving `field`. A
                // chained `.values_iter().any(...).then_some(...)`
                // keeps the iterator alive across the move and
                // fails the borrow check.
                let any_ok = field.values_iter().any(|r| r.is_ok());
                any_ok.then_some((name, field))
            })
            .collect()
    }

    /// Project every struct member that resolves as `f64` for at
    /// least one sample. Mirrors [`Self::u64_fields`] using
    /// [`Self::field_f64`].
    pub fn f64_fields(&self) -> Vec<(String, SeriesField<f64>)> {
        self.member_names()
            .into_iter()
            .filter_map(|name| {
                let field = self.field_f64(&name);
                let any_ok = field.values_iter().any(|r| r.is_ok());
                any_ok.then_some((name, field))
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::monitor::btf_render::{RenderedMember, RenderedValue};
    use crate::monitor::dump::{FailureDumpMap, FailureDumpReport, SCHEMA_SINGLE};

    fn synthetic_report(value: u64) -> FailureDumpReport {
        let bss_value = RenderedValue::Struct {
            type_name: Some(".bss".into()),
            members: vec![
                RenderedMember {
                    name: "nr_dispatched".into(),
                    value: RenderedValue::Uint { bits: 64, value },
                },
                RenderedMember {
                    name: "stall".into(),
                    value: RenderedValue::Uint { bits: 8, value: 0 },
                },
            ],
        };
        let bss_map = FailureDumpMap {
            name: "scx_obj.bss".into(),
            map_kva: 0,
            map_type: 2,
            value_size: 16,
            max_entries: 1,
            value: Some(bss_value),
            entries: Vec::new(),
            percpu_entries: Vec::new(),
            percpu_hash_entries: Vec::new(),
            arena: None,
            ringbuf: None,
            stack_trace: None,
            fd_array: None,
            error: None,
        };
        FailureDumpReport {
            schema: SCHEMA_SINGLE.to_string(),
            active_map_kvas: Vec::new(),
            maps: vec![bss_map],
            ..Default::default()
        }
    }

    /// Build a synthetic report with mixed-shape members so the
    /// `u64_fields` / `f64_fields` auto-projectors exercise the
    /// "at least one Ok" filter:
    ///   - `nr_dispatched`: Uint — projects Ok as u64.
    ///   - `stall`: Uint — projects Ok as u64.
    ///   - `balance`: Float — projects Err as u64 (TypeMismatch),
    ///     Ok as f64.
    ///   - `flag_str`: Bytes — projects Err as both u64 and f64.
    fn mixed_shape_report(disp: u64, balance: f64) -> FailureDumpReport {
        let bss_value = RenderedValue::Struct {
            type_name: Some(".bss".into()),
            members: vec![
                RenderedMember {
                    name: "nr_dispatched".into(),
                    value: RenderedValue::Uint {
                        bits: 64,
                        value: disp,
                    },
                },
                RenderedMember {
                    name: "stall".into(),
                    value: RenderedValue::Uint { bits: 8, value: 0 },
                },
                RenderedMember {
                    name: "balance".into(),
                    value: RenderedValue::Float {
                        bits: 64,
                        value: balance,
                    },
                },
                RenderedMember {
                    name: "flag_str".into(),
                    value: RenderedValue::Bytes {
                        hex: "de ad".into(),
                    },
                },
            ],
        };
        let bss_map = FailureDumpMap {
            name: "scx_obj.bss".into(),
            map_kva: 0,
            map_type: 2,
            value_size: 32,
            max_entries: 1,
            value: Some(bss_value),
            entries: Vec::new(),
            percpu_entries: Vec::new(),
            percpu_hash_entries: Vec::new(),
            arena: None,
            ringbuf: None,
            stack_trace: None,
            fd_array: None,
            error: None,
        };
        FailureDumpReport {
            schema: SCHEMA_SINGLE.to_string(),
            active_map_kvas: Vec::new(),
            maps: vec![bss_map],
            ..Default::default()
        }
    }

    #[test]
    fn bpf_projection_extracts_field_per_sample() {
        let drained = vec![
            (
                "periodic_000".to_string(),
                synthetic_report(10),
                None,
                Some(100),
            ),
            (
                "periodic_001".to_string(),
                synthetic_report(20),
                None,
                Some(200),
            ),
        ];
        let series = SampleSeries::from_drained(drained, None);
        let field: SeriesField<u64> =
            series.bpf("nr_dispatched", |snap| snap.var("nr_dispatched").as_u64());
        let values: Vec<u64> = field
            .values_iter()
            .filter_map(|v| v.as_ref().ok().copied())
            .collect();
        assert_eq!(values, vec![10, 20]);
    }

    #[test]
    fn bpf_map_projector_field_u64_extracts_field() {
        let drained = vec![
            (
                "periodic_000".to_string(),
                synthetic_report(10),
                None,
                Some(100),
            ),
            (
                "periodic_001".to_string(),
                synthetic_report(20),
                None,
                Some(200),
            ),
        ];
        let series = SampleSeries::from_drained(drained, None);
        let field = series
            .bpf_map("scx_obj.bss")
            .at(0)
            .field_u64("nr_dispatched");
        let values: Vec<u64> = field
            .values_iter()
            .filter_map(|v| v.as_ref().ok().copied())
            .collect();
        assert_eq!(values, vec![10, 20]);
    }

    #[test]
    fn bpf_map_projector_member_names_lists_struct_fields() {
        let drained = vec![(
            "periodic_000".to_string(),
            synthetic_report(10),
            None,
            Some(100),
        )];
        let series = SampleSeries::from_drained(drained, None);
        let names = series.bpf_map("scx_obj.bss").at(0).member_names();
        assert!(names.contains(&"nr_dispatched".to_string()));
        assert!(names.contains(&"stall".to_string()));
    }

    /// `BpfMapProjector::u64_fields` keeps every member that yields
    /// at least one `Ok` u64 across the series and drops members
    /// whose every-sample projection errors. The mixed-shape report
    /// above carries two u64 members (`nr_dispatched`, `stall`),
    /// one f64-only member (`balance`) that errors on every u64
    /// projection, and one bytes member (`flag_str`) that also
    /// errors on every u64 projection. The returned vec must
    /// surface only the two u64 names. The `SeriesField::label`
    /// is set to the field name (see `BpfMapProjector::field_u64`),
    /// so the tuple's first slot matches the struct member name
    /// exactly.
    #[test]
    fn bpf_map_projector_u64_fields_keeps_at_least_one_ok_excludes_all_err() {
        let drained = vec![
            (
                "periodic_000".to_string(),
                mixed_shape_report(10, 1.5),
                None,
                Some(100),
            ),
            (
                "periodic_001".to_string(),
                mixed_shape_report(20, 2.5),
                None,
                Some(200),
            ),
        ];
        let series = SampleSeries::from_drained(drained, None);
        let fields = series.bpf_map("scx_obj.bss").at(0).u64_fields();
        let names: Vec<&str> = fields.iter().map(|(n, _)| n.as_str()).collect();
        assert!(
            names.contains(&"nr_dispatched"),
            "u64-shaped member must be kept: {names:?}",
        );
        assert!(
            names.contains(&"stall"),
            "u64-shaped member must be kept: {names:?}",
        );
        assert!(
            !names.contains(&"balance"),
            "Float-shaped member must be excluded — every u64 projection errors: {names:?}",
        );
        assert!(
            !names.contains(&"flag_str"),
            "Bytes-shaped member must be excluded — every u64 projection errors: {names:?}",
        );
        // The kept fields must carry the projected u64 values
        // verbatim — the tuple's SeriesField is the same object
        // `field_u64(name)` would return.
        let dispatched = fields
            .iter()
            .find(|(n, _)| n == "nr_dispatched")
            .expect("nr_dispatched kept above");
        let values: Vec<u64> = dispatched
            .1
            .values_iter()
            .filter_map(|r| r.as_ref().ok().copied())
            .collect();
        assert_eq!(
            values,
            vec![10, 20],
            "kept SeriesField must carry the per-sample u64 projection",
        );
    }

    /// Mirror of the u64 test for `f64_fields`. Float, Uint, Int,
    /// and Enum members coerce to f64 (see `SnapshotField::as_f64`),
    /// so all three numeric members are kept; the Bytes member
    /// errors and is dropped. This pins the "at least one Ok"
    /// filter for the f64 axis distinctly from the u64 axis.
    #[test]
    fn bpf_map_projector_f64_fields_keeps_at_least_one_ok_excludes_all_err() {
        let drained = vec![
            (
                "periodic_000".to_string(),
                mixed_shape_report(10, 1.5),
                None,
                Some(100),
            ),
            (
                "periodic_001".to_string(),
                mixed_shape_report(20, 2.5),
                None,
                Some(200),
            ),
        ];
        let series = SampleSeries::from_drained(drained, None);
        let fields = series.bpf_map("scx_obj.bss").at(0).f64_fields();
        let names: Vec<&str> = fields.iter().map(|(n, _)| n.as_str()).collect();
        assert!(
            names.contains(&"nr_dispatched"),
            "Uint coerces to f64 — must be kept: {names:?}",
        );
        assert!(
            names.contains(&"stall"),
            "Uint coerces to f64 — must be kept: {names:?}",
        );
        assert!(
            names.contains(&"balance"),
            "Float coerces to f64 — must be kept: {names:?}",
        );
        assert!(
            !names.contains(&"flag_str"),
            "Bytes does not coerce to f64 — must be excluded: {names:?}",
        );
        let balance = fields
            .iter()
            .find(|(n, _)| n == "balance")
            .expect("balance kept above");
        let values: Vec<f64> = balance
            .1
            .values_iter()
            .filter_map(|r| r.as_ref().ok().copied())
            .collect();
        assert_eq!(values.len(), 2, "balance must surface one f64 per sample",);
        assert!((values[0] - 1.5).abs() < f64::EPSILON);
        assert!((values[1] - 2.5).abs() < f64::EPSILON);
    }

    /// Empty series — no rows to discover member names from, so
    /// `member_names()` returns an empty vec and both auto-projectors
    /// yield empty results without panicking. Pins the "no first
    /// row" branch in `BpfMapProjector::member_names`.
    #[test]
    fn bpf_map_projector_field_helpers_empty_series_yields_empty_vec() {
        let series = SampleSeries::empty();
        let u64s = series.bpf_map("scx_obj.bss").at(0).u64_fields();
        assert!(
            u64s.is_empty(),
            "empty series must yield empty u64_fields, got {} entries",
            u64s.len(),
        );
        let f64s = series.bpf_map("scx_obj.bss").at(0).f64_fields();
        assert!(
            f64s.is_empty(),
            "empty series must yield empty f64_fields, got {} entries",
            f64s.len(),
        );
    }

    /// Build a synthetic two-bss report: `scx_obj.bss` with `cross
    /// = a` + `same = b`, and OPTIONALLY a second `scx_other.bss`
    /// with `cross = c` + `same = d`. Mirrors the post-
    /// `Op::ReplaceScheduler` shape where two scheduler obj bss
    /// copies coexist in the same snapshot and `live_vars_via`'s
    /// picker resolves which one is live by max-sum.
    fn two_bss_report(primary: (u64, u64), secondary: Option<(u64, u64)>) -> FailureDumpReport {
        fn make_bss(name: &str, cross: u64, same: u64) -> FailureDumpMap {
            FailureDumpMap {
                name: name.into(),
                map_kva: 0,
                map_type: 2,
                value_size: 16,
                max_entries: 1,
                value: Some(RenderedValue::Struct {
                    type_name: Some(name.into()),
                    members: vec![
                        RenderedMember {
                            name: "cross".into(),
                            value: RenderedValue::Uint {
                                bits: 64,
                                value: cross,
                            },
                        },
                        RenderedMember {
                            name: "same".into(),
                            value: RenderedValue::Uint {
                                bits: 64,
                                value: same,
                            },
                        },
                    ],
                }),
                entries: Vec::new(),
                percpu_entries: Vec::new(),
                percpu_hash_entries: Vec::new(),
                arena: None,
                ringbuf: None,
                stack_trace: None,
                fd_array: None,
                error: None,
            }
        }
        let mut maps = vec![make_bss("scx_obj.bss", primary.0, primary.1)];
        if let Some((c, s)) = secondary {
            maps.push(make_bss("scx_other.bss", c, s));
        }
        FailureDumpReport {
            schema: SCHEMA_SINGLE.to_string(),
            active_map_kvas: Vec::new(),
            maps,
            ..Default::default()
        }
    }

    /// Single-candidate map: `live_bpf_vars_via` should resolve
    /// both names from `scx_obj.bss` per sample and produce two
    /// parallel `SeriesField<u64>`s carrying the per-sample
    /// `cross` and `same` values.
    #[test]
    fn live_bpf_vars_via_single_map_co_picks_both_names() {
        let drained = vec![
            (
                "periodic_000".to_string(),
                two_bss_report((10, 20), None),
                None,
                Some(100),
            ),
            (
                "periodic_001".to_string(),
                two_bss_report((30, 40), None),
                None,
                Some(200),
            ),
        ];
        let series = SampleSeries::from_drained(drained, None);
        let [cross, same] = series.live_bpf_vars_via(
            ["cross", "same"],
            crate::scenario::snapshot::pickers::max_by_sum_u64,
        );
        let cross_values: Vec<u64> = cross
            .values_iter()
            .filter_map(|r| r.as_ref().ok().copied())
            .collect();
        let same_values: Vec<u64> = same
            .values_iter()
            .filter_map(|r| r.as_ref().ok().copied())
            .collect();
        assert_eq!(cross_values, vec![10, 30]);
        assert_eq!(same_values, vec![20, 40]);
    }

    /// Placeholder-mid-series: when one snapshot's report is a
    /// placeholder (freeze rendezvous failed, walker unavailable),
    /// EVERY field slot for that row gets the same
    /// `PlaceholderSample` error — not just one. Pins that the
    /// per-field substitution at bpf.rs:111-124 doesn't silently
    /// drop a sample from one field while keeping it in another.
    #[test]
    fn live_bpf_vars_via_placeholder_substitutes_into_all_field_slots() {
        // Build a synthetic placeholder report: is_placeholder=true,
        // no maps populated. The construction mirrors what
        // freeze_coord stores when a rendezvous times out.
        let placeholder = FailureDumpReport {
            schema: SCHEMA_SINGLE.to_string(),
            is_placeholder: true,
            scx_walker_unavailable: Some("rendezvous timed out".to_string()),
            ..Default::default()
        };
        let drained = vec![
            (
                "periodic_000".to_string(),
                two_bss_report((10, 20), None),
                None,
                Some(100),
            ),
            ("periodic_001".to_string(), placeholder, None, Some(200)),
            (
                "periodic_002".to_string(),
                two_bss_report((30, 40), None),
                None,
                Some(300),
            ),
        ];
        let series = SampleSeries::from_drained(drained, None);
        let [cross, same] = series.live_bpf_vars_via(
            ["cross", "same"],
            crate::scenario::snapshot::pickers::max_by_sum_u64,
        );
        let cross_results: Vec<bool> = cross.values_iter().map(|r| r.is_ok()).collect();
        let same_results: Vec<bool> = same.values_iter().map(|r| r.is_ok()).collect();
        // Sample 0 + 2: ok. Sample 1 (placeholder): err in BOTH
        // fields. The two fields' Ok/Err patterns must match —
        // otherwise the per-field split lost coherence.
        assert_eq!(cross_results, vec![true, false, true]);
        assert_eq!(same_results, vec![true, false, true]);
        // The placeholder slot's error must carry the
        // PlaceholderSample variant (not a generic catch-all).
        let cross_err = cross
            .values_iter()
            .nth(1)
            .unwrap()
            .as_ref()
            .expect_err("placeholder row produces Err");
        assert!(
            matches!(
                cross_err,
                crate::scenario::snapshot::SnapshotError::PlaceholderSample { .. }
            ),
            "placeholder row must surface PlaceholderSample; got {cross_err:?}",
        );
    }

    /// When `live_vars_via` itself fails for a row (no candidate
    /// map has all the names, or the picker returned None), the
    /// SAME error MUST be substituted into all N field slots for
    /// that row — not split or dropped. Pins the bpf.rs:135-139
    /// error-substitution path.
    #[test]
    fn live_bpf_vars_via_picker_none_substitutes_into_all_field_slots() {
        let drained = vec![(
            "periodic_000".to_string(),
            two_bss_report((10, 20), Some((30, 40))),
            None,
            Some(100),
        )];
        let series = SampleSeries::from_drained(drained, None);
        // Picker that always returns None — forces live_vars_via
        // to surface ProjectionFailed for the row.
        let always_none =
            |_rows: &[(&str, Vec<crate::scenario::snapshot::SnapshotField<'_>>)]| None;
        let [a, b] = series.live_bpf_vars_via(["cross", "same"], always_none);
        let a_err = a
            .values_iter()
            .next()
            .unwrap()
            .as_ref()
            .expect_err("picker-None must surface as Err");
        let b_err = b
            .values_iter()
            .next()
            .unwrap()
            .as_ref()
            .expect_err("picker-None must surface as Err — same row → same Err");
        // The two field slots' errors must carry the SAME variant.
        assert!(
            matches!(
                a_err,
                crate::scenario::snapshot::SnapshotError::ProjectionFailed { .. }
            ),
            "field 0 must carry ProjectionFailed; got {a_err:?}",
        );
        assert!(
            matches!(
                b_err,
                crate::scenario::snapshot::SnapshotError::ProjectionFailed { .. }
            ),
            "field 1 must carry ProjectionFailed; got {b_err:?}",
        );
    }

    /// When the picker returns an out-of-range index, `live_vars_via`
    /// returns `ProjectionFailed` and the SAME error is substituted
    /// into every field slot for that row. Sibling of the
    /// picker-None case, distinct underlying failure mode.
    #[test]
    fn live_bpf_vars_via_picker_oor_substitutes_into_all_field_slots() {
        let drained = vec![(
            "periodic_000".to_string(),
            two_bss_report((10, 20), Some((30, 40))),
            None,
            Some(100),
        )];
        let series = SampleSeries::from_drained(drained, None);
        // Picker that returns an index way past the candidate count.
        let always_oor =
            |_rows: &[(&str, Vec<crate::scenario::snapshot::SnapshotField<'_>>)]| Some(999_usize);
        let [a, b] = series.live_bpf_vars_via(["cross", "same"], always_oor);
        let a_err = a.values_iter().next().unwrap().as_ref().err().unwrap();
        let b_err = b.values_iter().next().unwrap().as_ref().err().unwrap();
        assert!(
            matches!(
                a_err,
                crate::scenario::snapshot::SnapshotError::ProjectionFailed { .. }
            ),
            "picker-OOR must surface ProjectionFailed in field 0; got {a_err:?}",
        );
        assert!(
            matches!(
                b_err,
                crate::scenario::snapshot::SnapshotError::ProjectionFailed { .. }
            ),
            "picker-OOR must surface ProjectionFailed in field 1; got {b_err:?}",
        );
    }

    /// Duplicate names in the request slice: `live_vars_via` pushes
    /// one field per name (no dedup), so the resulting per-field
    /// SeriesFields each carry the SAME projected values. Both
    /// fields are still well-formed (length matches sample count);
    /// the only "skew" is the trivial one where dup names produce
    /// dup values. Pins that the per-field split honors `names.len()`
    /// rather than a deduplicated set.
    #[test]
    fn live_bpf_vars_via_duplicate_names_yields_parallel_duplicates() {
        let drained = vec![(
            "periodic_000".to_string(),
            two_bss_report((10, 20), None),
            None,
            Some(100),
        )];
        let series = SampleSeries::from_drained(drained, None);
        let [a, b] = series.live_bpf_vars_via(
            ["cross", "cross"],
            crate::scenario::snapshot::pickers::max_by_sum_u64,
        );
        let av: Vec<u64> = a
            .values_iter()
            .filter_map(|r| r.as_ref().ok().copied())
            .collect();
        let bv: Vec<u64> = b
            .values_iter()
            .filter_map(|r| r.as_ref().ok().copied())
            .collect();
        assert_eq!(av, vec![10], "first slot carries 'cross' = 10");
        assert_eq!(bv, vec![10], "second slot (duplicate) carries 'cross' = 10");
        // Pin field-count parity with names.len(): no silent drop.
        assert_eq!(
            av.len(),
            bv.len(),
            "duplicate-names must not skew per-field length"
        );
    }

    /// Multi-candidate map: `live_bpf_vars_via` must route both
    /// names through the SAME picker-selected candidate so the
    /// downstream ratio's numerator and denominator can't be
    /// split across two different scheduler obj bss copies. The
    /// `max_by_sum_u64` picker selects whichever bss has the
    /// larger `cross + same` sum.
    #[test]
    fn live_bpf_vars_via_two_maps_picker_routes_both_through_winner() {
        let drained = vec![
            // Sample 0: primary sum 30, secondary sum 1100 → secondary wins
            (
                "periodic_000".to_string(),
                two_bss_report((10, 20), Some((500, 600))),
                None,
                Some(100),
            ),
            // Sample 1: primary sum 10000, secondary sum 100 → primary wins
            (
                "periodic_001".to_string(),
                two_bss_report((4000, 6000), Some((50, 50))),
                None,
                Some(200),
            ),
        ];
        let series = SampleSeries::from_drained(drained, None);
        let [cross, same] = series.live_bpf_vars_via(
            ["cross", "same"],
            crate::scenario::snapshot::pickers::max_by_sum_u64,
        );
        let cross_values: Vec<u64> = cross
            .values_iter()
            .filter_map(|r| r.as_ref().ok().copied())
            .collect();
        let same_values: Vec<u64> = same
            .values_iter()
            .filter_map(|r| r.as_ref().ok().copied())
            .collect();
        // Sample 0: secondary wins → (500, 600). Sample 1: primary
        // wins → (4000, 6000). Both names came from the SAME map
        // per sample, never split.
        assert_eq!(cross_values, vec![500, 4000]);
        assert_eq!(same_values, vec![600, 6000]);
    }

    /// Build a single-bss report stamped with the given
    /// `active_map_kvas` so phase-stability tests can simulate the
    /// walker resolving to one specific KVA set per snapshot.
    fn single_bss_report_with_kvas(value: u64, active_kvas: Vec<u64>) -> FailureDumpReport {
        let bss = FailureDumpMap {
            name: "scx_obj.bss".into(),
            map_kva: active_kvas.first().copied().unwrap_or(0),
            map_type: 2,
            value_size: 8,
            max_entries: 1,
            value: Some(RenderedValue::Struct {
                type_name: Some("scx_obj.bss".into()),
                members: vec![RenderedMember {
                    name: "counter".into(),
                    value: RenderedValue::Uint { bits: 64, value },
                }],
            }),
            entries: Vec::new(),
            percpu_entries: Vec::new(),
            percpu_hash_entries: Vec::new(),
            arena: None,
            ringbuf: None,
            stack_trace: None,
            fd_array: None,
            error: None,
        };
        FailureDumpReport {
            schema: crate::monitor::dump::SCHEMA_SINGLE.to_string(),
            active_obj_name: Some("scx_obj".to_string()),
            active_map_kvas: active_kvas,
            maps: vec![bss],
            ..Default::default()
        }
    }

    fn drained_entry(
        tag: &str,
        report: FailureDumpReport,
        step_index: Option<u16>,
        elapsed_ms: u64,
    ) -> crate::scenario::snapshot::DrainedSnapshotEntry {
        crate::scenario::snapshot::DrainedSnapshotEntry {
            tag: tag.to_string(),
            report,
            stats: Err(crate::scenario::snapshot::MissingStatsReason::NoSchedulerBinary),
            elapsed_ms: Some(elapsed_ms),
            step_index,
        }
    }

    /// Walker drift within a phase: sample 0 and sample 1 are in
    /// the same phase but their `active_map_kvas` differ (the
    /// walker re-published mid-phase, simulating the post-swap
    /// settle window). Sample 0 pins the phase to its KVA set;
    /// sample 1 must surface `WalkerDriftedWithinPhase` so the
    /// downstream counter-delta reducer sees a single-source
    /// monotonic series.
    #[test]
    fn bpf_live_u64_walker_drift_within_phase_surfaces_drift_error() {
        let drained = vec![
            drained_entry(
                "p001",
                single_bss_report_with_kvas(100, vec![0x1000]),
                Some(1),
                100,
            ),
            drained_entry(
                "p002",
                single_bss_report_with_kvas(200, vec![0x2000]),
                Some(1),
                200,
            ),
        ];
        let series = SampleSeries::from_drained_typed(drained, None);
        let f = series.bpf_live_u64("counter");
        let results: Vec<&SnapshotResult<u64>> = f.values_iter().collect();
        assert_eq!(results.len(), 2);
        assert!(
            matches!(results[0], Ok(100)),
            "first sample pins, got {:?}",
            results[0]
        );
        match results[1] {
            Err(crate::scenario::snapshot::SnapshotError::WalkerDriftedWithinPhase {
                pinned_kvas,
                sample_kvas,
                requested,
                ..
            }) => {
                assert_eq!(pinned_kvas, &vec![0x1000]);
                assert_eq!(sample_kvas, &vec![0x2000]);
                assert_eq!(requested, "counter");
            }
            other => panic!("expected WalkerDriftedWithinPhase, got {other:?}"),
        }
    }

    /// Walker re-publishes the SAME KVA across same-phase
    /// samples — no drift. Both samples pass through with Ok
    /// values.
    #[test]
    fn bpf_live_u64_walker_stable_within_phase_passes_through() {
        let drained = vec![
            drained_entry(
                "p001",
                single_bss_report_with_kvas(100, vec![0x1000]),
                Some(1),
                100,
            ),
            drained_entry(
                "p002",
                single_bss_report_with_kvas(150, vec![0x1000]),
                Some(1),
                200,
            ),
        ];
        let series = SampleSeries::from_drained_typed(drained, None);
        let f = series.bpf_live_u64("counter");
        let results: Vec<&SnapshotResult<u64>> = f.values_iter().collect();
        assert!(matches!(results[0], Ok(100)));
        assert!(matches!(results[1], Ok(150)));
    }

    /// Walker output is empty (pre-walker capture) for both
    /// samples — no pin established, no drift detection, both
    /// pass through unchanged (the per-snapshot AmbiguousVar
    /// guard at the Snapshot::var layer covers the
    /// multi-bss-with-empty-walker case separately).
    #[test]
    fn bpf_live_u64_empty_walker_output_passes_through() {
        let drained = vec![
            drained_entry(
                "p001",
                single_bss_report_with_kvas(100, vec![]),
                Some(1),
                100,
            ),
            drained_entry(
                "p002",
                single_bss_report_with_kvas(150, vec![]),
                Some(1),
                200,
            ),
        ];
        let series = SampleSeries::from_drained_typed(drained, None);
        let f = series.bpf_live_u64("counter");
        let results: Vec<&SnapshotResult<u64>> = f.values_iter().collect();
        assert!(matches!(results[0], Ok(100)));
        assert!(matches!(results[1], Ok(150)));
    }

    /// Different phases get independent pins — drift detection
    /// resets at phase boundaries. Phase 1 pins to 0x1000;
    /// phase 2 pins to 0x2000 fresh.
    #[test]
    fn bpf_live_u64_pins_reset_at_phase_boundaries() {
        let drained = vec![
            drained_entry(
                "p001",
                single_bss_report_with_kvas(100, vec![0x1000]),
                Some(1),
                100,
            ),
            drained_entry(
                "p002",
                single_bss_report_with_kvas(150, vec![0x1000]),
                Some(1),
                200,
            ),
            drained_entry(
                "p003",
                single_bss_report_with_kvas(50, vec![0x2000]),
                Some(2),
                300,
            ),
            drained_entry(
                "p004",
                single_bss_report_with_kvas(75, vec![0x2000]),
                Some(2),
                400,
            ),
        ];
        let series = SampleSeries::from_drained_typed(drained, None);
        let f = series.bpf_live_u64("counter");
        let results: Vec<&SnapshotResult<u64>> = f.values_iter().collect();
        assert!(matches!(results[0], Ok(100)));
        assert!(matches!(results[1], Ok(150)));
        assert!(matches!(results[2], Ok(50)));
        assert!(matches!(results[3], Ok(75)));
    }
}