oxide-update-engine-types 0.1.2

Serializable types for the oxide-update-engine framework.
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Integration tests for [`EventBuffer`].
//!
//! These live outside the crate because `generate_test_events` requires the
//! engine, and adding the engine as a dev-dependency of the types crate would
//! create a duplicate-crate issue (the types crate would appear twice in the
//! dependency graph).

use anyhow::{Context, bail, ensure};
use indexmap::IndexSet;
use oxide_update_engine_test_utils::{
    GenerateTestEventsKind, TestSpec, generate_test_events,
};
use oxide_update_engine_types::{
    buffer::{
        EventBuffer, ExecutionStatus, RootEventIndex, StepKey, TerminalKind,
    },
    events::{
        Event, EventReport, ExecutionUuid, ProgressCounter, ProgressEvent,
        ProgressEventKind, StepEvent, StepEventKind, StepEventPriority,
    },
    spec::EngineSpec,
};
use serde::{Deserialize, de::IntoDeserializer};
use std::collections::{HashMap, HashSet};

#[tokio::test]
async fn test_buffer() {
    let log = slog::Logger::root(slog::Discard, slog::o!());
    let generated_events =
        generate_test_events(&log, GenerateTestEventsKind::Completed).await;

    let test_cx = BufferTestContext::new(generated_events);

    test_cx
        .run_all_elements_test(
            "all events passed in one-by-one",
            |buffer, event| buffer.add_event(event.clone()),
            1,
        )
        .unwrap();

    test_cx
        .run_all_elements_test(
            "all events duplicated (1)",
            |buffer, event| {
                buffer.add_event(event.clone());
                buffer.add_event(event.clone());
            },
            1,
        )
        .unwrap();

    test_cx
        .run_all_elements_test(
            "all events duplicated (2)",
            |buffer, event| {
                buffer.add_event(event.clone());
            },
            2,
        )
        .unwrap();

    test_cx
        .run_filtered_test(
            "all events passed in",
            |buffer, event| {
                buffer.add_event(event.clone());
                true
            },
            WithDeltas::No,
        )
        .unwrap();

    test_cx
        .run_filtered_test(
            "progress events skipped",
            |buffer, event| match event {
                Event::Step(event) => {
                    buffer.add_step_event(event.clone());
                    true
                }
                Event::Progress(_) => false,
            },
            WithDeltas::Both,
        )
        .unwrap();

    test_cx
        .run_filtered_test(
            "low-priority events skipped",
            |buffer, event| match event {
                Event::Step(event) => match event.kind.priority() {
                    StepEventPriority::High => {
                        buffer.add_step_event(event.clone());
                        true
                    }
                    StepEventPriority::Low => false,
                },
                Event::Progress(event) => {
                    buffer.add_progress_event(event.clone());
                    true
                }
            },
            WithDeltas::Both,
        )
        .unwrap();

    test_cx
        .run_filtered_test(
            "low-priority and progress events skipped",
            |buffer, event| match event {
                Event::Step(event) => match event.kind.priority() {
                    StepEventPriority::High => {
                        buffer.add_step_event(event.clone());
                        true
                    }
                    StepEventPriority::Low => false,
                },
                Event::Progress(_) => {
                    // Don't add progress events.
                    false
                }
            },
            WithDeltas::Both,
        )
        .unwrap();
}

/// This number is small enough that it will cause low-priority events to be
/// dropped in some cases.
const MAX_LOW_PRIORITY: usize = 4;

#[derive(Debug)]
struct BufferTestContext {
    root_execution_id: ExecutionUuid,
    generated_events: Vec<Event<TestSpec>>,

    // Data derived from generated_events.
    generated_step_events: Vec<StepEvent<TestSpec>>,
}

impl BufferTestContext {
    fn new(generated_events: Vec<Event<TestSpec>>) -> Self {
        // The first event is always a root event.
        let root_execution_id =
            match generated_events.first().expect("at least one event") {
                Event::Step(event) => event.execution_id,
                Event::Progress(_) => {
                    panic!("first event should always be a step event")
                }
            };

        // Ensure that nested step 2 produces progress events in the
        // expected order and in succession.
        let mut progress_check = NestedProgressCheck::new();
        for event in &generated_events {
            if let Event::Progress(event) = event {
                let progress_counter = event.kind.progress_counter();
                if progress_counter
                    == Some(&ProgressCounter::new(2, 3, "steps"))
                {
                    progress_check.two_out_of_three_seen();
                } else if progress_check
                    == NestedProgressCheck::TwoOutOfThreeSteps
                {
                    assert_eq!(
                        progress_counter,
                        Some(&ProgressCounter::current(50, "units"))
                    );
                    progress_check.fifty_units_seen();
                } else if progress_check == NestedProgressCheck::FiftyUnits {
                    assert_eq!(
                        progress_counter,
                        Some(&ProgressCounter::new(3, 3, "steps"))
                    );
                    progress_check.three_out_of_three_seen();
                }
            }
        }
        progress_check.assert_done();

        // Ensure that events are never seen twice.
        let mut event_indexes_seen = HashSet::new();
        let mut leaf_event_indexes_seen = HashSet::new();
        let generated_step_events: Vec<_> = generated_events
            .iter()
            .filter_map(|event| match event {
                Event::Step(event) => {
                    if event_indexes_seen.contains(&event.event_index) {
                        panic!(
                            "duplicate event seen for index {}",
                            event.event_index
                        );
                    }
                    event_indexes_seen.insert(event.event_index);

                    let leaf_event_key =
                        (event.leaf_execution_id(), event.leaf_event_index());
                    if leaf_event_indexes_seen.contains(&leaf_event_key) {
                        panic!(
                            "duplicate leaf event seen \
                             for key {leaf_event_key:?}",
                        );
                    }
                    leaf_event_indexes_seen.insert(leaf_event_key);

                    Some(event.clone())
                }
                Event::Progress(_) => None,
            })
            .collect();

        // Create two buffers and feed events.
        // * The incremental buffer has each event fed into it one-by-one.
        // * The "idempotent" buffer has events 0, 0..1, 0..2, 0..3, etc
        //   fed into it one by one. The name is because this is really
        //   testing the idempotency of the event buffer.

        println!("** generating incremental and idempotent buffers **");
        let mut incremental_buffer = EventBuffer::default();
        let mut idempotent_buffer = EventBuffer::default();
        for event in &generated_events {
            incremental_buffer.add_event(event.clone());
            let report = incremental_buffer.generate_report();
            idempotent_buffer.add_event_report(report);
        }

        // Check that the two buffers above are similar.
        ensure_buffers_similar(&incremental_buffer, &idempotent_buffer)
            .expect("idempotent buffer is similar to incremental buffer");

        // Also generate a buffer with a single event report.
        println!("** generating oneshot buffer **");
        let mut oneshot_buffer = EventBuffer::default();
        oneshot_buffer.add_event_report(incremental_buffer.generate_report());

        ensure_buffers_similar(&incremental_buffer, &oneshot_buffer)
            .expect("oneshot buffer is similar to incremental buffer");

        Self { root_execution_id, generated_events, generated_step_events }
    }

    /// Runs a test in a scenario where all elements should be seen.
    ///
    /// Each event is added `times` times.
    fn run_all_elements_test(
        &self,
        description: &str,
        mut event_fn: impl FnMut(&mut EventBuffer<TestSpec>, &Event<TestSpec>),
        times: usize,
    ) -> anyhow::Result<()> {
        let mut buffer: EventBuffer<TestSpec> =
            EventBuffer::new(MAX_LOW_PRIORITY);
        let mut reported_step_events = Vec::new();
        let mut last_seen = None;

        for (i, event) in self.generated_events.iter().enumerate() {
            for time in 0..times {
                (event_fn)(&mut buffer, event);
                let report = buffer.generate_report_since(&mut last_seen);
                let is_last_event = i == self.generated_events.len() - 1;
                self.assert_general_properties(&buffer, &report, is_last_event)
                    .with_context(|| {
                        format!(
                            "{description}, at index {i} (time {time}), \
                            properties not met"
                        )
                    })
                    .unwrap();
                reported_step_events.extend(report.step_events);

                // Ensure that the last root index was updated for this
                // event's corresponding steps, but not for any others.
                if let Event::Step(event) = event {
                    check_last_root_event_index(event, &buffer).with_context(
                        || {
                            format!(
                                "{description}, at index {i} (time {time}):\
                                 error with last root event index"
                            )
                        },
                    )?;
                }

                // Call last_seen without feeding a new event in to ensure that
                // a report with no step events is produced.
                let mut last_seen_2 = last_seen;
                let report = buffer.generate_report_since(&mut last_seen_2);
                ensure!(
                    report.step_events.is_empty(),
                    "{description}, at index {i} (time {time}),\
                    no step events are seen"
                );
                ensure!(
                    report.last_seen == last_seen,
                    "{description}, at index {i} (time {time}), \
                    report.last_seen {:?} matches last_seen {:?}",
                    report.last_seen,
                    last_seen,
                );
            }
        }

        ensure!(
            self.generated_step_events == reported_step_events,
            "all generated step events were reported"
        );

        Ok(())
    }

    /// Runs a test in a scenario where not all events might be replayed.
    fn run_filtered_test(
        &self,
        event_fn_description: &str,
        mut event_fn: impl FnMut(
            &mut EventBuffer<TestSpec>,
            &Event<TestSpec>,
        ) -> bool,
        with_deltas: WithDeltas,
    ) -> anyhow::Result<()> {
        match with_deltas {
            WithDeltas::Yes => {
                self.run_filtered_test_inner(&mut event_fn, true)
                    .context(event_fn_description.to_owned())?;
            }
            WithDeltas::No => {
                self.run_filtered_test_inner(&mut event_fn, false)
                    .context(event_fn_description.to_owned())?;
            }
            WithDeltas::Both => {
                self.run_filtered_test_inner(&mut event_fn, true)
                    .context(event_fn_description.to_owned())?;
                self.run_filtered_test_inner(&mut event_fn, false)
                    .context(event_fn_description.to_owned())?;
            }
        }

        Ok(())
    }

    fn run_filtered_test_inner(
        &self,
        mut event_fn: impl FnMut(
            &mut EventBuffer<TestSpec>,
            &Event<TestSpec>,
        ) -> bool,
        with_deltas: bool,
    ) -> anyhow::Result<()> {
        let description = format!("with deltas = {with_deltas}");
        let mut buffer = EventBuffer::new(MAX_LOW_PRIORITY);
        let mut last_high_priority = Vec::new();

        // This buffer has a large enough capacity that it never drops
        // events.
        let mut receive_buffer = EventBuffer::new(1024);
        // last_seen_opt is None if with_deltas is false.
        //
        // Some(None) if with_deltas is true and no events have been seen
        // so far.
        //
        // Some(Some(index)) if with_deltas is true and events have been
        // seen.
        let mut last_seen_opt = with_deltas.then_some(None);

        for (i, event) in self.generated_events.iter().enumerate() {
            let event_added = (event_fn)(&mut buffer, event);

            let report = match &mut last_seen_opt {
                Some(last_seen) => buffer.generate_report_since(last_seen),
                None => buffer.generate_report(),
            };

            let is_last_event = i == self.generated_events.len() - 1;
            self.assert_general_properties(&buffer, &report, is_last_event)
                .with_context(|| {
                    format!("{description}, at index {i}, properties not met")
                })
                .unwrap();

            if let Event::Step(event) = event
                && event_added
            {
                check_last_root_event_index(event, &buffer).with_context(
                    || {
                        format!(
                            "{description}, at index {i}: \
                            error with last root event index"
                        )
                    },
                )?;
            }

            receive_buffer.add_event_report(report.clone());
            let this_step_events = receive_buffer.generate_report().step_events;
            let this_high_priority: Vec<_> = this_step_events
                .iter()
                .filter(|event| {
                    event.kind.priority() == StepEventPriority::High
                })
                .cloned()
                .collect();

            if !with_deltas {
                let report_high_priority: Vec<_> = report
                    .step_events
                    .iter()
                    .filter(|event| {
                        event.kind.priority() == StepEventPriority::High
                    })
                    .cloned()
                    .collect();
                ensure!(
                    this_high_priority == report_high_priority,
                    "{description}, at index {i}, \
                     all high-priority events reported"
                );
            }

            if this_high_priority.len() == last_high_priority.len() {
                // event is not a high-priority event. All old high-priority
                // events must be reported as well.
                ensure!(
                    this_high_priority == last_high_priority,
                    "{description}, at index {i}, \
                     all old high-priority events reported (1)"
                );
            } else if this_high_priority.len() == last_high_priority.len() + 1 {
                // The first N events must match.
                ensure!(
                    this_high_priority[0..last_high_priority.len()]
                        == last_high_priority,
                    "{description}, at index {i}, \
                     all old high-priority events reported (2)"
                );
            }

            last_high_priority = this_high_priority;
        }

        Ok(())
    }

    fn assert_general_properties<S: EngineSpec>(
        &self,
        buffer: &EventBuffer<TestSpec>,
        report: &EventReport<S>,
        is_last_event: bool,
    ) -> anyhow::Result<()> {
        let mut progress_keys_seen = HashSet::new();
        for event in &report.progress_events {
            let key = progress_event_key(event);
            // Ensure that there's one progress event per report.
            if progress_keys_seen.contains(&key) {
                bail!("progress event key {key:?} seen twice in event map")
            }
            progress_keys_seen.insert(key);
            // Check that the buffer has an event in the tree and map
            // corresponding to any reports seen.
            if !buffer.__test_step_key_in_event_tree(&key) {
                bail!("progress event key {key:?} not found in event tree");
            }
            if !buffer.__test_step_key_in_map(&key) {
                bail!("progress event key {key:?} not found in event map");
            }
        }

        // Assert that steps are always in order. To check this, we use step
        // IDs, which we externally define to be in order.
        let steps = buffer.steps();
        for window in steps.as_slice().windows(2) {
            let (_, data1) = window[0];
            let (_, data2) = window[1];
            let data1_id: usize = Deserialize::deserialize(
                data1.step_info().id.clone().into_deserializer(),
            )
            .expect("data1.id is a usize");
            let data2_id: usize = Deserialize::deserialize(
                data2.step_info().id.clone().into_deserializer(),
            )
            .expect("data2.id is a usize");
            ensure!(
                data1_id < data2_id,
                "data 1 ID {data1_id} < data 2 ID {data2_id}"
            );
        }

        // iter_steps_for_execution and child_execution_ids must match what
        // inverting iter_steps_recursive via parent_key_and_child_index
        // produces.
        let mut steps_by_execution: HashMap<ExecutionUuid, Vec<StepKey>> =
            HashMap::new();
        let mut child_execs: HashMap<StepKey, Vec<(usize, ExecutionUuid)>> =
            HashMap::new();
        for (key, _data) in buffer.iter_steps_recursive() {
            steps_by_execution.entry(key.execution_id).or_default().push(key);
            if let Some(exec_data) =
                buffer.get_execution_data(&key.execution_id)
                && let Some((parent_key, child_index)) =
                    exec_data.parent_key_and_child_index()
            {
                let entry = child_execs.entry(parent_key).or_default();
                if !entry
                    .iter()
                    .any(|(_, exec_id)| *exec_id == key.execution_id)
                {
                    entry.push((child_index, key.execution_id));
                }
            }
        }
        for (execution_id, expected_keys) in &mut steps_by_execution {
            expected_keys.sort_by_key(|key| key.index);
            let actual_keys: Vec<_> = buffer
                .iter_steps_for_execution(*execution_id)
                .map(|(key, _)| key)
                .collect();
            ensure!(
                &actual_keys == expected_keys,
                "iter_steps_for_execution({execution_id:?}) matches \
                 recursive iteration: {actual_keys:?} vs {expected_keys:?}"
            );
        }
        for (key, data) in buffer.iter_steps_recursive() {
            let mut expected = child_execs.remove(&key).unwrap_or_default();
            expected.sort_by_key(|(child_index, _)| *child_index);
            let expected: Vec<_> =
                expected.into_iter().map(|(_, exec_id)| exec_id).collect();
            ensure!(
                data.child_execution_ids() == expected,
                "child_execution_ids for {key:?} matches \
                 parent_key_and_child_index inversion: {:?} vs {expected:?}",
                data.child_execution_ids(),
            );
        }

        // The root execution ID should have a summary associated with it.
        let root_execution_id = buffer
            .root_execution_id()
            .expect("at least one event => root execution ID exists");
        ensure!(
            root_execution_id == self.root_execution_id,
            "root execution ID matches"
        );
        let summary = steps.summarize();
        ensure!(
            summary.contains_key(&root_execution_id),
            "summary contains root execution ID {root_execution_id:?}"
        );

        if is_last_event {
            ensure!(
                matches!(
                    &summary[&root_execution_id].execution_status,
                    ExecutionStatus::Terminal(info)
                        if info.kind == TerminalKind::Completed
                ),
                "this is the last event so ExecutionStatus must be completed"
            );
            // There are three nested engines.
            ensure!(
                summary.len() == 4,
                "three nested engines (plus one root engine) must be defined"
            );

            let (_, nested_summary) =
                summary.get_index(1).expect("this is the first nested engine");
            ensure!(
                matches!(
                    &nested_summary.execution_status,
                    ExecutionStatus::Terminal(info)
                        if info.kind == TerminalKind::Failed
                ),
                "for this engine, the ExecutionStatus must be failed"
            );

            let (_, nested_summary) =
                summary.get_index(2).expect("this is the second nested engine");
            ensure!(
                matches!(
                    &nested_summary.execution_status,
                    ExecutionStatus::Terminal(info)
                        if info.kind == TerminalKind::Failed
                ),
                "for this engine, the ExecutionStatus must be failed"
            );

            let (_, nested_summary) =
                summary.get_index(3).expect("this is the third nested engine");
            ensure!(
                matches!(
                    &nested_summary.execution_status,
                    ExecutionStatus::Terminal(info)
                        if info.kind == TerminalKind::Completed
                ),
                "for this engine, the ExecutionStatus must be succeeded"
            );
        } else {
            ensure!(
                matches!(
                    summary[&root_execution_id].execution_status,
                    ExecutionStatus::Running { .. },
                ),
                "not the last event so ExecutionStatus must be running"
            );
        }

        // The root execution ID should be the only root in the event tree.
        buffer
            .__test_verify_single_root(root_execution_id)
            .map_err(|msg| anyhow::anyhow!(msg))?;

        Ok(())
    }
}

fn ensure_buffers_similar<S: EngineSpec>(
    buf1: &EventBuffer<S>,
    buf2: &EventBuffer<S>,
) -> anyhow::Result<()> {
    // The two should have the same step keys.
    let buf1_steps = buf1.steps();
    let buf2_steps = buf2.steps();

    ensure!(
        buf1_steps.as_slice().len() == buf2_steps.as_slice().len(),
        "buffers have same number of steps ({} vs {})",
        buf1_steps.as_slice().len(),
        buf2_steps.as_slice().len()
    );

    // Collect unique execution IDs to compare per-execution data.
    let mut execution_ids_seen = HashSet::new();

    for (ix, ((k1, data1), (k2, data2))) in buf1_steps
        .as_slice()
        .iter()
        .zip(buf2_steps.as_slice().iter())
        .enumerate()
    {
        ensure!(
            k1 == k2,
            "buffers have same step keys at index {} ({:?} vs {:?})",
            ix,
            k1,
            k2
        );
        ensure!(
            data1.__test_sort_key() == data2.__test_sort_key(),
            "buffers have same sort key at index {} ({:?} vs {:?})",
            ix,
            data1.__test_sort_key(),
            data2.__test_sort_key()
        );

        // Compare per-execution data once per unique execution ID.
        if execution_ids_seen.insert(k1.execution_id) {
            let exec1 = buf1
                .get_execution_data(&k1.execution_id)
                .expect("execution data must exist in buf1");
            let exec2 = buf2
                .get_execution_data(&k1.execution_id)
                .expect("execution data must exist in buf2");
            ensure!(
                exec1.parent_key_and_child_index()
                    == exec2.parent_key_and_child_index(),
                "buffers have same parent key and child index \
                 for execution {:?} ({:?} vs {:?})",
                k1.execution_id,
                exec1.parent_key_and_child_index(),
                exec2.parent_key_and_child_index(),
            );
            ensure!(
                exec1.nest_level() == exec2.nest_level(),
                "buffers have same nest level \
                 for execution {:?} ({:?} vs {:?})",
                k1.execution_id,
                exec1.nest_level(),
                exec2.nest_level(),
            );
            ensure!(
                exec1.total_steps() == exec2.total_steps(),
                "buffers have same total steps \
                 for execution {:?} ({:?} vs {:?})",
                k1.execution_id,
                exec1.total_steps(),
                exec2.total_steps(),
            );
        }
    }

    Ok(())
}

fn check_last_root_event_index(
    event: &StepEvent<TestSpec>,
    buffer: &EventBuffer<TestSpec>,
) -> anyhow::Result<()> {
    let root_event_index = RootEventIndex(event.event_index);
    let event_step_keys = step_keys(event);
    let steps = buffer.steps();
    for (step_key, data) in steps.as_slice() {
        let data_index = data.last_root_event_index();
        if event_step_keys.contains(step_key) {
            ensure!(
                data_index == root_event_index,
                "last_root_event_index should have been updated \
                 but wasn't (actual: {data_index}, expected: {root_event_index}) \
                 for step {step_key:?} (event: {event:?})",
            );
        } else {
            ensure!(
                data_index < root_event_index,
                "last_root_event_index should *not* have been updated \
                 but was (current: {data_index}, new: {root_event_index}) \
                 for step {step_key:?} (event: {event:?})",
            );
        }
    }

    Ok(())
}

/// Returns the step keys that this step event would cause updates against,
/// in order from root to leaf.
fn step_keys<S: EngineSpec>(event: &StepEvent<S>) -> IndexSet<StepKey> {
    let mut out = IndexSet::new();
    step_keys_impl(event, &mut out);
    out
}

fn step_keys_impl<S: EngineSpec>(
    event: &StepEvent<S>,
    out: &mut IndexSet<StepKey>,
) {
    match &event.kind {
        StepEventKind::NoStepsDefined | StepEventKind::Unknown => {}
        StepEventKind::ExecutionStarted { steps, .. } => {
            for step in steps {
                out.insert(StepKey {
                    execution_id: event.execution_id,
                    index: step.index,
                });
            }
        }
        StepEventKind::ProgressReset { step, .. }
        | StepEventKind::AttemptRetry { step, .. }
        | StepEventKind::StepCompleted { step, .. }
        | StepEventKind::ExecutionCompleted { last_step: step, .. }
        | StepEventKind::ExecutionFailed { failed_step: step, .. }
        | StepEventKind::ExecutionAborted { aborted_step: step, .. } => {
            out.insert(StepKey {
                execution_id: event.execution_id,
                index: step.info.index,
            });
        }
        StepEventKind::Nested { step, event, .. } => {
            out.insert(StepKey {
                execution_id: event.execution_id,
                index: step.info.index,
            });
            step_keys_impl(event, out);
        }
    }
}

#[derive(Copy, Clone, Debug)]
enum WithDeltas {
    #[expect(unused)]
    Yes,
    No,
    Both,
}

fn progress_event_key<S: EngineSpec>(event: &ProgressEvent<S>) -> StepKey {
    match &event.kind {
        ProgressEventKind::WaitingForProgress { step, .. }
        | ProgressEventKind::Progress { step, .. } => {
            StepKey { execution_id: event.execution_id, index: step.info.index }
        }
        ProgressEventKind::Nested { event: nested_event, .. } => {
            progress_event_key(nested_event)
        }
        ProgressEventKind::Unknown => {
            panic!("we should never generate an unknown key")
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NestedProgressCheck {
    Initial,
    TwoOutOfThreeSteps,
    FiftyUnits,
    ThreeOutOfThreeSteps,
}

impl NestedProgressCheck {
    fn new() -> Self {
        Self::Initial
    }

    fn two_out_of_three_seen(&mut self) {
        assert_eq!(
            *self,
            Self::Initial,
            "two_out_of_three_seen: expected Initial",
        );
        *self = Self::TwoOutOfThreeSteps;
    }

    fn fifty_units_seen(&mut self) {
        assert_eq!(
            *self,
            Self::TwoOutOfThreeSteps,
            "fifty_units_seen: expected TwoOutOfThreeSteps",
        );
        *self = Self::FiftyUnits;
    }

    fn three_out_of_three_seen(&mut self) {
        assert_eq!(
            *self,
            Self::FiftyUnits,
            "three_out_of_three_seen: expected FiftyUnits",
        );
        *self = Self::ThreeOutOfThreeSteps;
    }

    fn assert_done(&self) {
        assert_eq!(
            *self,
            Self::ThreeOutOfThreeSteps,
            "assert_done: expected ThreeOutOfThreeSteps",
        );
    }
}