hermit-run 0.5.0

Hermit: a deterministic Linux execution engine for reproducible runs, record and replay, and concurrency-race search.
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
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

use std::ops::Range;

use anyhow::bail;
use colored::Colorize;
use detcore::edit_distance::NeedlemanWunsch;
use detcore::edit_distance::NeedlemanWunschError;
use detcore::edit_distance::generate_permutation;
use detcore::edit_distance::iterable_bubble_sort;
use detcore::types::SchedEvent;

/// User configurable settings.
pub struct Config {
    pub max_jitter_editdist: usize,
    pub max_jitter_swapdist: usize,
    pub max_event_level_search_passes: usize,
    pub max_unmatched_to_print: usize,
    /// Bound quadratic traceback work before falling back to event permutation search.
    pub max_needleman_matrix_cells: usize,
    /// Number of identical replays required to classify a jittered control schedule.
    pub max_replay_attempts: usize,
    /// Try to split a final adjacent event pair into a precise branch boundary.
    pub refine_sub_events: bool,
    pub verbose: bool,
    /// Activate a search that uses Needleman Wunsch alignment during each step.
    pub needleman_search: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            max_jitter_editdist: 0,
            max_jitter_swapdist: 0,
            max_event_level_search_passes: 100,
            max_unmatched_to_print: 10,
            max_needleman_matrix_cells: 4_000_000,
            max_replay_attempts: 2,
            refine_sub_events: true,
            verbose: false,
            needleman_search: false,
        }
    }
}

/// What one trial of the search reports: whether the replayed schedule passed,
/// and the schedule the run actually realized. An `Err` is a trial that could
/// not finish, for example one that `--max-log-bytes` ended; the search makes
/// no further trial and returns that error unchanged, so its type (such as
/// `LogCapExceeded`) still reaches the top-level handler.
pub type TrialOutcome = anyhow::Result<(bool, Vec<SchedEvent>)>;

struct EventLevelSearchResult {
    passing_schedule: Vec<SchedEvent>,
    failing_schedule: Vec<SchedEvent>,
}

#[derive(Debug)]
pub struct CriticalSchedule {
    pub failing_schedule: Vec<SchedEvent>,
    pub passing_schedule: Vec<SchedEvent>,

    /// The index of an event in the failing schedule. If you swap this event with the one before it, it
    /// changes the outcome to passing, and should in fact match the passing schedule.
    pub critical_event_index: usize,
}

/// return 2 if first == second (ignores end_time)
/// return -1 if only count is different
/// return -2 otherwise
pub fn scoring_function(first: SchedEvent, second: SchedEvent) -> i32 {
    let mut score = -2;
    if (first.dettid == second.dettid)
        && (first.op == second.op)
        && (first.start_rip == second.start_rip)
        && (first.end_rip == second.end_rip)
    {
        score += 1;
    } else {
        return score;
    }
    if first.count == second.count {
        score += 3;
    }
    score
}

#[allow(dead_code)]
/// Search for a schedule which is failing the criteria, but is edit distance one from succeeding.
///
/// A trial that returns `Err` ends the search: no further trial runs and the
/// error is returned as it is.
pub fn search_for_critical_schedule<F>(
    mut tester: F,
    initial_passing_schedule: Vec<SchedEvent>,
    initial_failing_schedule: Vec<SchedEvent>,
    cfg: &Config,
) -> anyhow::Result<CriticalSchedule>
where
    F: FnMut(&[SchedEvent]) -> TrialOutcome,
{
    eprintln!("Verifying pass/fail endpoints of the search, using schedule-trace replay:");
    let (passing_endpoint_passes, _) = tester(&initial_passing_schedule)?;
    if !passing_endpoint_passes {
        bail!("the passing schedule endpoint did not reproduce a passing outcome");
    }
    let (failing_endpoint_passes, _) = tester(&initial_failing_schedule)?;
    if failing_endpoint_passes {
        bail!("the failing schedule endpoint did not reproduce the target failure");
    }

    // Do the first level search at the event level
    let EventLevelSearchResult {
        passing_schedule,
        failing_schedule,
    } = if cfg.needleman_search {
        needleman_level_search(
            &mut tester,
            initial_passing_schedule,
            initial_failing_schedule,
            cfg,
        )?
    } else {
        event_level_search(
            &mut tester,
            initial_passing_schedule,
            initial_failing_schedule,
            cfg,
        )?
    };

    if cfg.refine_sub_events
        && let Some(critical_schedule) = sub_event_search(
            &mut tester,
            passing_schedule.clone(),
            failing_schedule.clone(),
        )?
    {
        return Ok(critical_schedule);
    }

    eprintln!(
        ":: {}",
        "Critical events found which exercise race bug."
            .green()
            .bold()
    );
    let critical_event_index = {
        let (common_prefix, _) = get_common_pre_and_postfix(&passing_schedule, &failing_schedule);
        common_prefix.len() + 1
    };
    eprintln!("Critical event index {}", critical_event_index);
    Ok(CriticalSchedule {
        failing_schedule,
        passing_schedule,
        critical_event_index,
    })
}

// Return edit distance and swap distance.
fn just_distance(sched1: &[SchedEvent], sched2: &[SchedEvent]) -> (usize, usize) {
    let bubbles = iterable_bubble_sort(sched1, sched2);
    (bubbles.edit_distance(), bubbles.swap_distance())
}

fn test_and_select_stable_point<F>(
    tester: &mut F,
    requested_schedule: &[SchedEvent],
    cfg: &Config,
) -> TrialOutcome
where
    F: FnMut(&[SchedEvent]) -> TrialOutcome,
{
    let (passes, actual_schedule) = tester(requested_schedule)?;
    let jitter = just_distance(requested_schedule, &actual_schedule);
    if jitter.0 <= cfg.max_jitter_editdist && jitter.1 <= cfg.max_jitter_swapdist {
        return Ok((passes, actual_schedule));
    }

    eprintln!(
        ":: {}",
        format!(
            "Replay jitter {}:{} exceeded threshold {}:{}; checking control-schedule stability",
            jitter.0, jitter.1, cfg.max_jitter_editdist, cfg.max_jitter_swapdist,
        )
        .yellow()
        .bold(),
    );

    for attempt in 2..=cfg.max_replay_attempts.max(2) {
        let (replayed_passes, replayed_actual) = tester(requested_schedule)?;
        if replayed_passes == passes && replayed_actual == actual_schedule {
            eprintln!(
                ":: Jittered control schedule reproduced the same outcome and realized trace on attempt {}",
                attempt,
            );
            return Ok((passes, requested_schedule.to_vec()));
        }
    }

    panic!(
        "Jittered schedule replay was not stable after {} attempts; refusing to attach an outcome to the requested control schedule",
        cfg.max_replay_attempts.max(2),
    );
}

/// Search of the schedule space to find the critical schedule
fn needleman_level_search<F>(
    tester: &mut F,
    mut passing_schedule: Vec<SchedEvent>,
    mut failing_schedule: Vec<SchedEvent>,
    cfg: &Config,
) -> anyhow::Result<EventLevelSearchResult>
where
    F: FnMut(&[SchedEvent]) -> TrialOutcome,
{
    for pass_number in 0..cfg.max_event_level_search_passes {
        let (edit_distance, swap_distance) = just_distance(&passing_schedule, &failing_schedule);
        if edit_distance == 1 && swap_distance == 1 {
            return Ok(EventLevelSearchResult {
                passing_schedule,
                failing_schedule,
            });
        }
        if edit_distance != swap_distance {
            eprintln!(
                ":: Needleman-Wunsch endpoints contain {} insertion/deletion edits; falling back to event permutation search",
                edit_distance - swap_distance,
            );
            return event_level_search(tester, passing_schedule, failing_schedule, cfg);
        }

        let mut needleman = NeedlemanWunsch {
            first_sequence: passing_schedule.clone(),
            second_sequence: failing_schedule.clone(),
            ..Default::default()
        };
        let (start_index, global_alignment) = match needleman.match_sequences_bounded(
            Some(scoring_function),
            None,
            Some(-2),
            cfg.max_needleman_matrix_cells,
        ) {
            Ok(alignment) => alignment,
            Err(NeedlemanWunschError::MatrixTooLarge { cells, max_cells }) => {
                eprintln!(
                    ":: Needleman-Wunsch alignment requires {} cells (limit {}); falling back to event permutation search",
                    cells, max_cells,
                );
                return event_level_search(tester, passing_schedule, failing_schedule, cfg);
            }
        };
        if global_alignment.is_empty() {
            eprintln!(
                ":: Needleman-Wunsch produced no alignment difference on pass {}; falling back to event permutation search",
                pass_number,
            );
            return event_level_search(tester, passing_schedule, failing_schedule, cfg);
        }
        let requested_midpoint_schedule =
            needleman.generate_midpoint_schedule(start_index, global_alignment);

        let distance_from_passing = just_distance(&passing_schedule, &requested_midpoint_schedule);
        let distance_from_failing = just_distance(&requested_midpoint_schedule, &failing_schedule);
        if distance_from_passing >= (edit_distance, swap_distance)
            || distance_from_failing >= (edit_distance, swap_distance)
        {
            eprintln!(
                ":: Needleman-Wunsch midpoint did not strictly reduce both sides of the {}:{} interval; falling back to event permutation search",
                edit_distance, swap_distance,
            );
            return event_level_search(tester, passing_schedule, failing_schedule, cfg);
        }

        let (midpoint_passes, selected_new_point) =
            test_and_select_stable_point(tester, &requested_midpoint_schedule, cfg)?;

        if midpoint_passes {
            passing_schedule = selected_new_point;
        } else {
            failing_schedule = selected_new_point;
        }
    }

    panic!(
        "Event-Level Search Failed - No convergence after {} passes",
        cfg.max_event_level_search_passes
    );
}

/// Generate a permutation between source and target and print unmatched events (up to a limit).
fn print_unmatched_events(
    passing_schedule: &[SchedEvent],
    failing_schedule: &[SchedEvent],
    max_to_print: usize,
) {
    let perm = generate_permutation(passing_schedule, failing_schedule);
    for ix in perm.unmatched_source_indices.iter().take(max_to_print) {
        eprintln!(
            " :: unmatched source evt #{}: {}",
            ix, passing_schedule[*ix]
        );
    }
    let unmatched_src = perm.unmatched_source_indices.len();
    if unmatched_src > max_to_print {
        eprintln!(
            " :: ... plus {} more unmatched events",
            unmatched_src - max_to_print,
        )
    }

    for ix in perm.unmatched_target_indices.iter().take(max_to_print) {
        eprintln!(
            " :: unmatched target evt #{}: {}",
            ix, failing_schedule[*ix]
        );
    }
    let unmatched_trg = perm.unmatched_target_indices.len();
    if unmatched_trg > max_to_print {
        eprintln!(
            " :: ... plus {} more unmatched events",
            unmatched_trg - max_to_print,
        )
    }
}

/// Perform a multi-level search of the schedule space to find the critical schedule
/// between the two starting schedules by evaluating the given function at each step.
/// The result will be a failing schedule and coordinates in that schedule for the
/// adjacent branches that when flipped will cause the test to fail
fn event_level_search<F>(
    tester: &mut F,
    mut passing_schedule: Vec<SchedEvent>,
    mut failing_schedule: Vec<SchedEvent>,
    cfg: &Config,
) -> anyhow::Result<EventLevelSearchResult>
where
    F: FnMut(&[SchedEvent]) -> TrialOutcome,
{
    let orig_passing_schedule = passing_schedule.clone();
    let orig_failing_schedule = failing_schedule.clone();

    for pass_number in 0..cfg.max_event_level_search_passes {
        let (swap_dist, edit_dist, requested_midpoint_schedule) = {
            let mut bubbles = iterable_bubble_sort(&passing_schedule, &failing_schedule);
            (
                bubbles.swap_distance(),
                bubbles.edit_distance(),
                bubbles.midpoint().cloned().collect::<Vec<_>>(),
            )
        };
        eprintln!(
            "\n:: Event-Level Search Pass {} => EditDistance = {}, Swap Distance = {} ({:.0}% matched, midpoint sched len = {})",
            pass_number,
            edit_dist,
            swap_dist,
            (100.0 * 2.0 * requested_midpoint_schedule.len() as f64
                / (passing_schedule.len() + failing_schedule.len()) as f64),
            requested_midpoint_schedule.len()
        );

        let unmatched_total =
            passing_schedule.len() + failing_schedule.len() - 2 * requested_midpoint_schedule.len();
        if cfg.verbose && unmatched_total > 0 {
            print_unmatched_events(
                &passing_schedule,
                &failing_schedule,
                cfg.max_unmatched_to_print,
            );
        }

        if swap_dist == 0 {
            panic!(
                "Aborting search: opposite-outcome schedules have no remaining reorderable event distance (edit distance {})",
                edit_dist,
            );
        }

        if swap_dist == 1 && edit_dist == 1 {
            return Ok(EventLevelSearchResult {
                passing_schedule,
                failing_schedule,
            });
        }

        if swap_dist == 1 {
            panic!(
                "Aborting search: schedules are one swap apart but still contain {} unmatched event edits",
                edit_dist - swap_dist,
            );
        }

        let (midpoint_passes, selected_new_point) =
            test_and_select_stable_point(tester, &requested_midpoint_schedule, cfg)?;
        if cfg.verbose {
            let (jitter_edit, jitter_swap) =
                just_distance(&requested_midpoint_schedule, &selected_new_point);
            if jitter_edit > 0 || jitter_swap > 0 {
                eprintln!(
                    ":: Jitter was {}:{} edit/swap distance (requested synthetic schedule vs actual schedule)",
                    jitter_edit, jitter_swap
                );
            } else {
                eprintln!(
                    ":: No jitter in this run (requested synthetic schedule identical to actual schedule)",
                );
            }
            let (edit1, swap1) = just_distance(&passing_schedule, &selected_new_point);
            let (edit2, swap2) = just_distance(&selected_new_point, &failing_schedule);
            eprintln!(
                ":: Including jitter, actual run was {}:{} from passing pole and {}:{} from failing one",
                edit1, swap1, edit2, swap2
            );
            let (edit1, swap1) = just_distance(&orig_passing_schedule, &passing_schedule);
            let (edit2, swap2) = just_distance(&failing_schedule, &orig_failing_schedule);
            eprintln!(
                ":: Note, those poles are {}:{} from original passing, and {}:{} from original failing respectively.",
                edit1, swap1, edit2, swap2
            );
        }

        if midpoint_passes {
            passing_schedule = selected_new_point;
        } else {
            failing_schedule = selected_new_point;
        }
    }

    panic!(
        "Event-Level Search Failed - No convergence after {} passes",
        cfg.max_event_level_search_passes
    );
}

/// Returns `(prefix, postfix)` respectively.
fn get_common_pre_and_postfix<'a, T>(sched_1: &'a [T], sched_2: &[T]) -> (&'a [T], &'a [T])
where
    T: Eq,
{
    let common_prefix_len = sched_1
        .iter()
        .zip(sched_2.iter())
        .take_while(|(e1, e2)| e1 == e2)
        .count();

    let common_postfix_len = if sched_1.len() == sched_2.len() && sched_1.len() == common_prefix_len
    {
        0
    } else {
        sched_1
            .iter()
            .rev()
            .zip(sched_2.iter().rev())
            .take_while(|(e1, e2)| e1 == e2)
            .count()
    };

    (
        &sched_1[0..common_prefix_len],
        &sched_1[(sched_1.len() - common_postfix_len)..],
    )
}

/// This function performs a search for the critical branch between two schedules that only differ
/// by swap-distance 1 (in terms of events).
///
/// Let's start with some definitions. We are going to represent the schedules' differeing ROIs as
/// [ {ThreadLetter}_{BranchCount}, .. ], thread A with 50 branches as A_50. Let's say the ROI for
/// the passing schedule is [ A_x, B_y ], and for the failing schedule it's [ B_z, A_w ].
///
/// That implies there is some branch `j` in thread B that when shifted to execute before a
/// branch `i` in thread A, the test will fail. Our job is to find the critical pair `i` and `j`
/// To accomplish this, we will perform 2 different binary searches. The first will search over all
/// schedules of the form
///
/// [A_i, B_q, A_k] where i + k = max(x, w) and q = max(y, z)
///
/// to find the minimum value of i where the executed schedule allows the test to pass. To find the
/// critical branch in thread A which (unfortunately) will be `i + 1`. Next, we do another binary
/// search on schedules of the form
///
/// [A_i, B_j, A_k, B_m] where i + k = max(x, w) and j + m = max(y, z) and i is held constant
///
/// to find the minimum value of j where the executed schedule causes a failure. This tells us the
/// critical branch in thread B which will (fortunately) be `j`. We will return the critical
/// schedule in the form that passes and coordinates into the schedule to indicate where a single
/// flipped pair of branches can cause the test to fail
fn sub_event_search<F>(
    tester: &mut F,
    passing_schedule: Vec<SchedEvent>,
    failing_schedule: Vec<SchedEvent>,
) -> anyhow::Result<Option<CriticalSchedule>>
where
    F: FnMut(&[SchedEvent]) -> TrialOutcome,
{
    let (prefix, postfix) = get_common_pre_and_postfix(&passing_schedule, &failing_schedule);
    if passing_schedule.len() != failing_schedule.len()
        || prefix.len() + postfix.len() + 2 != passing_schedule.len()
    {
        eprintln!(
            ":: Skipping sub-event refinement: final schedules are not a single exact adjacent event reversal"
        );
        return Ok(None);
    }

    let critical_range = Range {
        start: prefix.len(),
        end: prefix.len() + 2,
    };

    eprintln!(
        "Passing Size - {}, Failing Size - {}, Prefix Size - {}, Postfix Size - {}",
        passing_schedule.len(),
        failing_schedule.len(),
        prefix.len(),
        postfix.len(),
    );

    let passing_critical_events = &passing_schedule[critical_range.clone()];
    let failing_critical_events = &failing_schedule[critical_range];
    if !same_event_except_count(&passing_critical_events[0], &failing_critical_events[1])
        || !same_event_except_count(&passing_critical_events[1], &failing_critical_events[0])
    {
        eprintln!(
            ":: Skipping sub-event refinement: adjacent events do not form the same reversed pair"
        );
        return Ok(None);
    }

    let critical_pair_passing = [
        sched_event_with_new_count(
            &passing_critical_events[0],
            u32::max(
                passing_critical_events[0].count,
                failing_critical_events[1].count,
            ),
        ),
        sched_event_with_new_count(
            &passing_critical_events[1],
            u32::max(
                passing_critical_events[1].count,
                failing_critical_events[0].count,
            ),
        ),
    ];

    let i_max = critical_pair_passing[0].count;
    let j_max = critical_pair_passing[1].count;
    if !can_split_event(&critical_pair_passing[0])
        || !can_split_event(&critical_pair_passing[1])
        || !critical_pair_passing
            .iter()
            .any(|event| event.op == detcore::types::Op::Branch && event.count > 1)
    {
        eprintln!(
            ":: Skipping sub-event refinement: critical pair has no splittable branch interval"
        );
        return Ok(None);
    }

    // Find the first A branch count that passes. Its predecessor is the failing boundary.
    let Some(i_plus_one) = binary_search(0..i_max, &mut |i| {
        let schedule =
            create_schedule_with_critical_pair(prefix, postfix, &critical_pair_passing, i, j_max);

        let Some(passed) = test_exact_replay(tester, &schedule)? else {
            return Ok(None);
        };

        eprintln!("Binary Search of A at sample {} -> passed = {}", i, passed);

        Ok(Some(!passed))
    })?
    else {
        return Ok(None);
    };

    let Some(i) = i_plus_one.checked_sub(1) else {
        eprintln!(
            ":: Skipping sub-event refinement: A boundary is already passing at zero branches"
        );
        return Ok(None);
    };

    // Find the first B branch count that fails while holding A at its boundary.
    let Some(j) = binary_search(1..j_max, &mut |j| {
        let schedule =
            create_schedule_with_critical_pair(prefix, postfix, &critical_pair_passing, i, j);

        let Some(passed) = test_exact_replay(tester, &schedule)? else {
            return Ok(None);
        };
        eprintln!("Binary Search of B at sample {} -> passed = {}", j, passed);

        Ok(Some(passed))
    })?
    else {
        return Ok(None);
    };

    // We are defining the critical event as the event index in the passing schedule
    // where the first branch in the event must come after the last branch in the previous
    // event in order for the schedule to fail. The calculation below for that index is a little
    // weird, but all it's doing is saying is:
    //
    // if no branches from the first event in the critical pair are used, the ciritical event
    // will appear one index sooner becase events with zero count are filtered
    let critical_event_index = prefix.len() + 1 + usize::from(i > 0);

    let failing_schedule =
        create_schedule_with_critical_pair(prefix, postfix, &critical_pair_passing, i, j);
    let mut passing_schedule = failing_schedule.clone();
    {
        let tmp = passing_schedule[critical_event_index - 1].clone();
        passing_schedule[critical_event_index - 1] = passing_schedule[critical_event_index].clone();
        passing_schedule[critical_event_index] = tmp;
    }

    if just_distance(&passing_schedule, &failing_schedule) != (1, 1) {
        eprintln!(
            ":: Skipping sub-event refinement: final schedules are not one verified adjacent swap apart"
        );
        return Ok(None);
    }
    // The passing schedule is replayed first, and the failing one only when
    // the passing one still passes.
    let outcomes_preserved = match test_exact_replay(tester, &passing_schedule)? {
        None => return Ok(None),
        Some(false) => false,
        Some(true) => match test_exact_replay(tester, &failing_schedule)? {
            None => return Ok(None),
            Some(failing_passes) => !failing_passes,
        },
    };
    if !outcomes_preserved {
        eprintln!(
            ":: Skipping sub-event refinement: final A/B replay did not preserve passing/failing outcomes"
        );
        return Ok(None);
    }

    eprintln!(
        ":: {}",
        "Critical branch boundary found and verified."
            .green()
            .bold()
    );
    Ok(Some(CriticalSchedule {
        failing_schedule,
        passing_schedule,
        critical_event_index,
    }))
}

fn same_event_except_count(first: &SchedEvent, second: &SchedEvent) -> bool {
    let mut first = first.clone();
    let mut second = second.clone();
    first.count = 0;
    second.count = 0;
    first == second
}

fn can_split_event(event: &SchedEvent) -> bool {
    event.count > 0 && (event.op == detcore::types::Op::Branch || event.count == 1)
}

fn test_exact_replay<F>(tester: &mut F, requested: &[SchedEvent]) -> anyhow::Result<Option<bool>>
where
    F: FnMut(&[SchedEvent]) -> TrialOutcome,
{
    let (passes, actual) = tester(requested)?;
    if actual != requested {
        eprintln!(
            ":: Skipping sub-event refinement: replay did not realize a requested branch boundary exactly (requested {} events, realized {})",
            requested.len(),
            actual.len(),
        );
        Ok(None)
    } else {
        Ok(Some(passes))
    }
}

/// Binary search implementation specific to our problem. This will return the smallest value
/// where the predicate returns false. `Ok(None)` means the predicate gave up on a sample; an
/// `Err` from the predicate ends the search and is returned unchanged.
fn binary_search<F>(range: Range<u32>, predicate: &mut F) -> anyhow::Result<Option<u32>>
where
    F: FnMut(u32) -> anyhow::Result<Option<bool>>,
{
    let mut left = range.start;
    let mut right = range.end;
    let mut size = right - left;

    while size > 0 {
        let mid = left + size / 2;
        let Some(test_res) = predicate(mid)? else {
            return Ok(None);
        };

        if test_res {
            left = mid + 1;
        } else {
            right = mid;
        }

        size = right - left;
    }

    Ok(Some(left))
}

/// Create a new SchedEvent with the size replaced with the given value
fn sched_event_with_new_count(original: &SchedEvent, new_count: u32) -> SchedEvent {
    SchedEvent {
        count: new_count,
        ..*original
    }
}

fn sched_event_fragment(
    original: &SchedEvent,
    count: u32,
    keeps_start: bool,
    keeps_end: bool,
) -> SchedEvent {
    SchedEvent {
        count,
        start_rip: keeps_start.then_some(original.start_rip).flatten(),
        end_rip: keeps_end.then_some(original.end_rip).flatten(),
        ..*original
    }
}

/// Create a schedule by slicing and mixing the critical section and inserting it
/// into a vec between the given common prefix and postfix. the values i and j determine
/// how many branches from the ciritical pair to keep before swapping to the other for the
/// remainder. Visually, if we have the ciritical pair A_8 and B_9, then with i=4 and j=7,
/// we get:
///                       <- A8 -><- B9 -->
/// Original Branches  => AAAAAAAABBBBBBBBB
/// Synthetic Branches => AAAABBBBBBBAAAABB
///                       <A4><- B7-><A4>B2
fn create_schedule_with_critical_pair(
    prefix: &[SchedEvent],
    postfix: &[SchedEvent],
    critical_pair_passing: &[SchedEvent],
    i: u32,
    j: u32,
) -> Vec<SchedEvent> {
    let i_remainder = critical_pair_passing[0].count - i;
    let j_remainder = critical_pair_passing[1].count - j;
    let critical_section = [
        sched_event_fragment(&critical_pair_passing[0], i, true, i_remainder == 0),
        sched_event_fragment(&critical_pair_passing[1], j, true, j_remainder == 0),
        sched_event_fragment(&critical_pair_passing[0], i_remainder, i == 0, true),
        sched_event_fragment(&critical_pair_passing[1], j_remainder, j == 0, true),
    ];

    eprintln!(
        "Critical Section -> A{} B{} A{} B{}",
        i, j, i_remainder, j_remainder
    );

    prefix
        .iter()
        .cloned()
        .chain(critical_section.into_iter().filter(|event| event.count > 0))
        .chain(postfix.iter().cloned())
        .collect()
}

#[cfg(test)]
mod tests {

    use detcore::preemptions::PreemptionRecord;
    use detcore::types::DetTid;
    use detcore::types::LogicalTime;
    use detcore::types::Op;
    use detcore::types::SyscallPhase;
    use reverie::syscalls::Sysno;

    use super::*;

    #[test]
    fn test_common_pre_and_postfix() {
        assert_eq!(
            get_common_pre_and_postfix(b"abABcde", b"abBAcde"),
            (b"ab".as_slice(), b"cde".as_slice())
        );
    }

    #[test]
    fn test_binary_search() {
        // Check a bunch of close values to make sure we don't have an off-by-one problem.
        // I also did an exhaustive search up to 100,000 because I was sure this wouldn't work,
        // but it does. Thanks, Rust std library
        let search = |range: Range<u32>, below: u32| {
            binary_search(range, &mut |i| Ok(Some(i < below))).unwrap()
        };
        assert_eq!(search(0..10, 4), Some(4));
        assert_eq!(search(0..11, 4), Some(4));
        assert_eq!(search(0..10, 5), Some(5));
        assert_eq!(search(0..11, 5), Some(5));
        assert_eq!(search(1..100, 49), Some(49));
        assert_eq!(search(2..151, 49), Some(49));
        assert_eq!(search(3..100, 58), Some(58));
        assert_eq!(search(4..151, 58), Some(58));
        assert_eq!(binary_search(0..10, &mut |_| Ok(None)).unwrap(), None);
    }

    #[test]
    fn syscall_pair_stays_at_event_granularity() {
        let first = SchedEvent::syscall(DetTid::from_raw(3), Sysno::write, SyscallPhase::Prehook);
        let second = SchedEvent::syscall(DetTid::from_raw(5), Sysno::read, SyscallPhase::Prehook);
        let passing = vec![first.clone(), second.clone()];
        let failing = vec![second, first.clone()];
        let tester = |schedule: &[SchedEvent]| -> TrialOutcome {
            Ok((schedule.first() == Some(&first), schedule.to_vec()))
        };

        let critical = search_for_critical_schedule(
            tester,
            passing.clone(),
            failing.clone(),
            &Config::default(),
        )
        .unwrap();

        assert_eq!(critical.passing_schedule, passing);
        assert_eq!(critical.failing_schedule, failing);
        assert_eq!(critical.critical_event_index, 1);
    }

    #[test]
    fn endpoint_outcomes_are_validated() {
        let first = SchedEvent::syscall(DetTid::from_raw(3), Sysno::write, SyscallPhase::Prehook);
        let second = SchedEvent::syscall(DetTid::from_raw(5), Sysno::read, SyscallPhase::Prehook);
        let good = vec![first.clone(), second.clone()];
        let bad = vec![second, first];

        let error = search_for_critical_schedule(
            |schedule| Ok((false, schedule.to_vec())),
            good.clone(),
            bad.clone(),
            &Config::default(),
        )
        .unwrap_err();
        assert!(error.to_string().contains("passing schedule endpoint"));

        let error = search_for_critical_schedule(
            |schedule| Ok((true, schedule.to_vec())),
            good,
            bad,
            &Config::default(),
        )
        .unwrap_err();
        assert!(error.to_string().contains("failing schedule endpoint"));
    }

    #[test]
    fn sub_event_search_rejects_jittered_replay() {
        let branch = SchedEvent::branches(DetTid::from_raw(3), 5);
        let syscall = SchedEvent::syscall(DetTid::from_raw(5), Sysno::write, SyscallPhase::Prehook);
        let passing = vec![branch.clone(), syscall.clone()];
        let failing = vec![syscall, branch];
        let extra = SchedEvent::syscall(DetTid::from_raw(7), Sysno::read, SyscallPhase::Prehook);
        let mut tester = |schedule: &[SchedEvent]| -> TrialOutcome {
            let mut actual = schedule.to_vec();
            actual.push(extra.clone());
            Ok((false, actual))
        };

        assert!(
            sub_event_search(&mut tester, passing, failing)
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn jittered_control_point_requires_stable_replay() {
        let first = SchedEvent::syscall(DetTid::from_raw(3), Sysno::write, SyscallPhase::Prehook);
        let second = SchedEvent::syscall(DetTid::from_raw(5), Sysno::read, SyscallPhase::Prehook);
        let requested = vec![first, second];
        let extra = SchedEvent::syscall(DetTid::from_raw(7), Sysno::getpid, SyscallPhase::Prehook);
        let mut calls = 0;
        let mut tester = |schedule: &[SchedEvent]| -> TrialOutcome {
            calls += 1;
            let mut actual = schedule.to_vec();
            actual.push(extra.clone());
            Ok((true, actual))
        };

        let (passes, selected) =
            test_and_select_stable_point(&mut tester, &requested, &Config::default()).unwrap();

        assert!(passes);
        assert_eq!(selected, requested);
        assert_eq!(calls, 2);
    }

    #[test]
    fn oversized_needleman_alignment_falls_back() {
        let first = SchedEvent::syscall(DetTid::from_raw(3), Sysno::write, SyscallPhase::Prehook);
        let second = SchedEvent::syscall(DetTid::from_raw(5), Sysno::read, SyscallPhase::Prehook);
        let third = SchedEvent::syscall(DetTid::from_raw(7), Sysno::getpid, SyscallPhase::Prehook);
        let passing = vec![first.clone(), second.clone(), third.clone()];
        let failing = vec![third, second, first.clone()];
        let tester = |schedule: &[SchedEvent]| -> TrialOutcome {
            Ok((schedule.first() == Some(&first), schedule.to_vec()))
        };
        let cfg = Config {
            max_needleman_matrix_cells: 0,
            needleman_search: true,
            refine_sub_events: false,
            ..Default::default()
        };

        let critical = search_for_critical_schedule(tester, passing, failing, &cfg).unwrap();

        assert_eq!(
            just_distance(&critical.passing_schedule, &critical.failing_schedule),
            (1, 1)
        );
    }

    /// The flaky_cas fixture endpoints, `(passing, failing)`, with the two
    /// critical events marked: `end_time` 0 on the first and 1 on the second.
    fn flaky_cas_endpoints() -> (Vec<SchedEvent>, Vec<SchedEvent>) {
        let passing_preemptions: PreemptionRecord = serde_json::from_slice(include_bytes!(
            "../../../test-resources/flaky_cas_sequence_schedules-passing.json"
        ))
        .expect("Failed to parse passing schedule");
        let failing_preemptions: PreemptionRecord = serde_json::from_slice(include_bytes!(
            "../../../test-resources/flaky_cas_sequence_schedules-failing.json"
        ))
        .expect("Failed to parse failing schedule");

        let mut passing_sched = passing_preemptions.into_global();
        let mut failing_sched = failing_preemptions.into_global();

        let critical_event_1_index_in_passing_schedule = 385;
        let critical_event_2_index_in_passing_schedule = 401;

        let critical_event_1_index_in_failing_schedule = 400;
        let critical_event_2_index_in_failing_schedule = 379;

        passing_sched.iter_mut().enumerate().for_each(|(i, e)| {
            e.end_time = if i == critical_event_1_index_in_passing_schedule {
                Some(LogicalTime::from_nanos(0))
            } else if i == critical_event_2_index_in_passing_schedule {
                Some(LogicalTime::from_nanos(1))
            } else {
                None
            }
        });

        failing_sched.iter_mut().enumerate().for_each(|(i, e)| {
            e.end_time = if i == critical_event_1_index_in_failing_schedule {
                Some(LogicalTime::from_nanos(0))
            } else if i == critical_event_2_index_in_failing_schedule {
                Some(LogicalTime::from_nanos(1))
            } else {
                None
            }
        });

        (passing_sched, failing_sched)
    }

    /// The mocked run's outcome: a schedule passes when the first marked event
    /// it reaches is the first critical event.
    fn flaky_cas_passes(sched: &[SchedEvent]) -> bool {
        let criticals = sched
            .iter()
            .filter(|e| e.end_time.is_some())
            .collect::<Vec<_>>();

        criticals[0].end_time.unwrap().as_nanos() == 0
    }

    #[test]
    /// This test runs a real search but with mocked out actual hermit runs.
    fn flaky_cas_sequence_schedules() {
        let (passing_sched, failing_sched) = flaky_cas_endpoints();

        let mock_tester = |sched: &[SchedEvent]| -> TrialOutcome {
            Ok((flaky_cas_passes(sched), sched.to_owned()))
        };

        let CriticalSchedule {
            failing_schedule: critical_failing_schedule,
            critical_event_index,
            ..
        } = search_for_critical_schedule(
            mock_tester,
            passing_sched,
            failing_sched,
            &Default::default(),
        )
        .unwrap();

        assert_eq!(critical_event_index, 379);

        let thread_5_syscall = &critical_failing_schedule[critical_event_index];
        let thread_7_one_branch = &critical_failing_schedule[critical_event_index - 1];
        let thread_7_other_branches = &critical_failing_schedule[critical_event_index + 1];

        assert_eq!(thread_5_syscall.dettid.as_raw(), 5);
        assert_eq!(
            thread_5_syscall.op,
            Op::Syscall(Sysno::futex, SyscallPhase::Posthook),
        );

        assert_eq!(thread_7_one_branch.dettid.as_raw(), 7);
        assert_eq!(thread_7_one_branch.op, Op::Branch,);
        assert_eq!(thread_7_one_branch.count, 1);

        assert_eq!(thread_7_other_branches.dettid.as_raw(), 7);
        assert_eq!(thread_7_other_branches.op, Op::Branch,);
        assert_eq!(thread_7_other_branches.count, 16);
    }

    /// A trial that `--max-log-bytes` ended, as `classify_container_result`
    /// reports it to the trial's caller.
    fn log_cap_trial_error() -> anyhow::Error {
        anyhow::Error::new(crate::container::LogCapExceeded)
    }

    /// The search over the flaky_cas fixture, with a trial that fails at every
    /// position in turn: the two endpoint checks, the event-level midpoints,
    /// and the sub-event binary searches and final checks. Each time the search
    /// stops at the failing trial and returns its error, still a
    /// `LogCapExceeded`. Before trials could fail, the analyze tester had to
    /// panic instead (`expect("New run to succeed")`).
    #[test]
    fn a_failing_trial_ends_the_schedule_search_with_its_error() {
        let (passing, failing) = flaky_cas_endpoints();
        let mut total_trials = 0;
        let critical = search_for_critical_schedule(
            |sched| {
                total_trials += 1;
                Ok((flaky_cas_passes(sched), sched.to_vec()))
            },
            passing.clone(),
            failing.clone(),
            &Config::default(),
        )
        .unwrap();
        // The sweep below covers the sub-event search only if this search
        // reached it, as flaky_cas_sequence_schedules shows it does.
        assert_eq!(critical.critical_event_index, 379);
        assert!(
            total_trials > 2,
            "the fixture search made only {total_trials} trials"
        );

        for failing_trial in 1..=total_trials {
            let mut trials = 0;
            let result = search_for_critical_schedule(
                |sched| {
                    trials += 1;
                    if trials == failing_trial {
                        return Err(log_cap_trial_error());
                    }
                    Ok((flaky_cas_passes(sched), sched.to_vec()))
                },
                passing.clone(),
                failing.clone(),
                &Config::default(),
            );
            let error = result.expect_err("a failed trial must end the search with an error");
            assert!(
                error
                    .downcast_ref::<crate::container::LogCapExceeded>()
                    .is_some(),
                "trial {failing_trial} of {total_trials}: the error lost its type: {error:#}"
            );
            assert_eq!(
                trials, failing_trial,
                "the search ran more trials after trial {failing_trial} failed"
            );
        }
    }

    /// The replay of a jittered control schedule is a trial too: when that
    /// replay fails, no further replay runs and its error is returned,
    /// still a `LogCapExceeded`. The flaky_cas search above never needs this
    /// replay, so this is the test that covers it.
    #[test]
    fn a_failing_jitter_replay_returns_its_error() {
        let first = SchedEvent::syscall(DetTid::from_raw(3), Sysno::write, SyscallPhase::Prehook);
        let second = SchedEvent::syscall(DetTid::from_raw(5), Sysno::read, SyscallPhase::Prehook);
        let requested = vec![first, second];
        let extra = SchedEvent::syscall(DetTid::from_raw(7), Sysno::getpid, SyscallPhase::Prehook);
        let mut calls = 0;
        let mut tester = |schedule: &[SchedEvent]| -> TrialOutcome {
            calls += 1;
            if calls == 2 {
                return Err(log_cap_trial_error());
            }
            let mut actual = schedule.to_vec();
            actual.push(extra.clone());
            Ok((true, actual))
        };

        let error = test_and_select_stable_point(&mut tester, &requested, &Config::default())
            .expect_err("a failed replay must be returned");

        assert!(
            error
                .downcast_ref::<crate::container::LogCapExceeded>()
                .is_some(),
            "{error:#}"
        );
        assert_eq!(calls, 2);
    }
}