nextest-runner 0.114.0

Core runner logic for cargo nextest.
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
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Serializable summary types for test events.
//!
//! This module provides types that can be serialized to JSON for recording test runs.
//! The types here mirror the runtime types in [`crate::reporter::events`] but are
//! designed for serialization rather than runtime use.
//!
//! The `S` type parameter specifies how output is stored (see
//! [`OutputSpec`](crate::output_spec::OutputSpec)):
//! - [`LiveSpec`](crate::output_spec::LiveSpec): output stored in memory with
//!   lazy string conversion.
//! - [`RecordingSpec`](crate::output_spec::RecordingSpec): reference to a file stored
//!   in the zip archive.

#[cfg(test)]
use crate::output_spec::ArbitraryOutputSpec;
use crate::{
    config::{elements::JunitFlakyFailStatus, scripts::ScriptId},
    list::OwnedTestInstanceId,
    output_spec::{LiveSpec, OutputSpec, SerializableOutputSpec},
    reporter::{
        TestOutputDisplay,
        events::{
            CancelReason, ExecuteStatus, ExecutionStatuses, RetryData, RunFinishedStats, RunStats,
            SetupScriptExecuteStatus, StressIndex, StressProgress, TestEvent, TestEventKind,
            TestSlotAssignment,
        },
    },
    run_mode::NextestRunMode,
    runner::StressCondition,
};
use chrono::{DateTime, FixedOffset};
use nextest_metadata::MismatchReason;
use quick_junit::ReportUuid;
use serde::{Deserialize, Serialize};
use std::{fmt, num::NonZero, time::Duration};

// ---
// Record options
// ---

/// Options that affect how test results are interpreted during replay.
///
/// These options are captured at record time and stored in the archive,
/// allowing replay to produce the same exit code as the original run.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct RecordOpts {
    /// The run mode (test or benchmark).
    #[serde(default)]
    pub run_mode: NextestRunMode,
}

impl RecordOpts {
    /// Creates a new `RecordOpts` with the given settings.
    pub fn new(run_mode: NextestRunMode) -> Self {
        Self { run_mode }
    }
}

// ---
// Test event summaries
// ---

/// A serializable form of a test event.
///
/// The `S` parameter specifies how test outputs are stored (see
/// [`OutputSpec`]).
#[derive_where::derive_where(Debug, PartialEq; S::ChildOutputDesc)]
#[derive(Deserialize, Serialize)]
#[serde(
    rename_all = "kebab-case",
    bound(
        serialize = "S: SerializableOutputSpec",
        deserialize = "S: SerializableOutputSpec"
    )
)]
#[cfg_attr(
    test,
    derive(test_strategy::Arbitrary),
    arbitrary(bound(S: ArbitraryOutputSpec))
)]
pub struct TestEventSummary<S: OutputSpec> {
    /// The timestamp of the event.
    #[cfg_attr(
        test,
        strategy(crate::reporter::test_helpers::arb_datetime_fixed_offset())
    )]
    pub timestamp: DateTime<FixedOffset>,

    /// The time elapsed since the start of the test run.
    #[cfg_attr(test, strategy(crate::reporter::test_helpers::arb_duration()))]
    pub elapsed: Duration,

    /// The kind of test event this is.
    pub kind: TestEventKindSummary<S>,
}

impl TestEventSummary<LiveSpec> {
    /// Converts a [`TestEvent`] to a serializable summary.
    ///
    /// Returns `None` for events that should not be recorded (informational and
    /// interactive events like `InfoStarted`, `InputEnter`, etc.).
    pub(crate) fn from_test_event(event: TestEvent<'_>) -> Option<Self> {
        let kind = TestEventKindSummary::from_test_event_kind(event.kind)?;
        Some(Self {
            timestamp: event.timestamp,
            elapsed: event.elapsed,
            kind,
        })
    }
}

/// The kind of test event.
///
/// This is a combined enum that wraps either a [`CoreEventKind`] (events
/// without output) or an [`OutputEventKind`] (events with output). The split
/// design allows conversion between output representations to only touch the
/// output-carrying variants.
///
/// The type parameter `S` specifies how test output is stored (see
/// [`OutputSpec`]).
#[derive_where::derive_where(Debug, PartialEq; S::ChildOutputDesc)]
#[derive(Deserialize, Serialize)]
#[serde(
    tag = "type",
    rename_all = "kebab-case",
    bound(
        serialize = "S: SerializableOutputSpec",
        deserialize = "S: SerializableOutputSpec"
    )
)]
#[cfg_attr(
    test,
    derive(test_strategy::Arbitrary),
    arbitrary(bound(S: ArbitraryOutputSpec))
)]
pub enum TestEventKindSummary<S: OutputSpec> {
    /// An event that doesn't carry output.
    Core(CoreEventKind),
    /// An event that carries output.
    Output(OutputEventKind<S>),
}

/// Events that don't carry test output.
///
/// These events pass through unchanged during conversion between output
/// representations (e.g., from [`LiveSpec`] to
/// [`RecordingSpec`](crate::output_spec::RecordingSpec)).
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(tag = "kind", rename_all = "kebab-case")]
#[cfg_attr(test, derive(test_strategy::Arbitrary))]
pub enum CoreEventKind {
    /// A test run started.
    #[serde(rename_all = "kebab-case")]
    RunStarted {
        /// The run ID.
        run_id: ReportUuid,
        /// The profile name.
        profile_name: String,
        /// The CLI arguments.
        cli_args: Vec<String>,
        /// The stress condition, if any.
        stress_condition: Option<StressConditionSummary>,
    },

    /// A stress sub-run started.
    #[serde(rename_all = "kebab-case")]
    StressSubRunStarted {
        /// The stress progress.
        progress: StressProgress,
    },

    /// A setup script started.
    #[serde(rename_all = "kebab-case")]
    SetupScriptStarted {
        /// The stress index, if running a stress test.
        stress_index: Option<StressIndexSummary>,
        /// The index of this setup script.
        index: usize,
        /// The total number of setup scripts.
        total: usize,
        /// The script ID.
        script_id: ScriptId,
        /// The program being run.
        program: String,
        /// The arguments to the program.
        args: Vec<String>,
        /// Whether output capture is disabled.
        no_capture: bool,
    },

    /// A setup script is slow.
    #[serde(rename_all = "kebab-case")]
    SetupScriptSlow {
        /// The stress index, if running a stress test.
        stress_index: Option<StressIndexSummary>,
        /// The script ID.
        script_id: ScriptId,
        /// The program being run.
        program: String,
        /// The arguments to the program.
        args: Vec<String>,
        /// The time elapsed.
        #[cfg_attr(test, strategy(crate::reporter::test_helpers::arb_duration()))]
        elapsed: Duration,
        /// Whether the script will be terminated.
        will_terminate: bool,
    },

    /// A test started.
    #[serde(rename_all = "kebab-case")]
    TestStarted {
        /// The stress index, if running a stress test.
        stress_index: Option<StressIndexSummary>,
        /// The test instance.
        test_instance: OwnedTestInstanceId,
        /// Scheduling information (slot and group assignment).
        slot_assignment: TestSlotAssignment,
        /// The current run statistics.
        current_stats: RunStats,
        /// The number of tests currently running.
        running: usize,
        /// The command line used to run this test.
        command_line: Vec<String>,
    },

    /// A test is slow.
    #[serde(rename_all = "kebab-case")]
    TestSlow {
        /// The stress index, if running a stress test.
        stress_index: Option<StressIndexSummary>,
        /// The test instance.
        test_instance: OwnedTestInstanceId,
        /// Retry data.
        retry_data: RetryData,
        /// The time elapsed.
        #[cfg_attr(test, strategy(crate::reporter::test_helpers::arb_duration()))]
        elapsed: Duration,
        /// Whether the test will be terminated.
        will_terminate: bool,
    },

    /// A test retry started.
    #[serde(rename_all = "kebab-case")]
    TestRetryStarted {
        /// The stress index, if running a stress test.
        stress_index: Option<StressIndexSummary>,
        /// The test instance.
        test_instance: OwnedTestInstanceId,
        /// Scheduling information (slot and group assignment).
        slot_assignment: TestSlotAssignment,
        /// Retry data.
        retry_data: RetryData,
        /// The number of tests currently running.
        running: usize,
        /// The command line used to run this test.
        command_line: Vec<String>,
    },

    /// A test was skipped.
    #[serde(rename_all = "kebab-case")]
    TestSkipped {
        /// The stress index, if running a stress test.
        stress_index: Option<StressIndexSummary>,
        /// The test instance.
        test_instance: OwnedTestInstanceId,
        /// The reason the test was skipped.
        reason: MismatchReason,
    },

    /// A run began being cancelled.
    #[serde(rename_all = "kebab-case")]
    RunBeginCancel {
        /// The number of setup scripts currently running.
        setup_scripts_running: usize,
        /// The number of tests currently running.
        running: usize,
        /// The reason for cancellation.
        reason: CancelReason,
    },

    /// A run was paused.
    #[serde(rename_all = "kebab-case")]
    RunPaused {
        /// The number of setup scripts currently running.
        setup_scripts_running: usize,
        /// The number of tests currently running.
        running: usize,
    },

    /// A run was continued after being paused.
    #[serde(rename_all = "kebab-case")]
    RunContinued {
        /// The number of setup scripts currently running.
        setup_scripts_running: usize,
        /// The number of tests currently running.
        running: usize,
    },

    /// A stress sub-run finished.
    #[serde(rename_all = "kebab-case")]
    StressSubRunFinished {
        /// The stress progress.
        progress: StressProgress,
        /// The time taken for this sub-run.
        #[cfg_attr(test, strategy(crate::reporter::test_helpers::arb_duration()))]
        sub_elapsed: Duration,
        /// The run statistics for this sub-run.
        sub_stats: RunStats,
    },

    /// A run finished.
    #[serde(rename_all = "kebab-case")]
    RunFinished {
        /// The run ID.
        run_id: ReportUuid,
        /// The start time.
        #[cfg_attr(
            test,
            strategy(crate::reporter::test_helpers::arb_datetime_fixed_offset())
        )]
        start_time: DateTime<FixedOffset>,
        /// The total elapsed time.
        #[cfg_attr(test, strategy(crate::reporter::test_helpers::arb_duration()))]
        elapsed: Duration,
        /// The final run statistics.
        run_stats: RunFinishedStats,
        /// Tests that were expected to run but were not seen during this run.
        outstanding_not_seen: Option<TestsNotSeenSummary>,
    },
}

/// Tests that were expected to run but were not seen during a rerun.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(test, derive(test_strategy::Arbitrary))]
pub struct TestsNotSeenSummary {
    /// A sample of test instance IDs that were not seen.
    pub not_seen: Vec<OwnedTestInstanceId>,
    /// The total number of tests not seen.
    pub total_not_seen: usize,
}

/// Events that carry test output.
///
/// These events require conversion when changing output representations
/// (e.g., from [`LiveSpec`] to
/// [`RecordingSpec`](crate::output_spec::RecordingSpec)).
///
/// The type parameter `S` specifies how test output is stored (see
/// [`OutputSpec`]).
#[derive_where::derive_where(Debug, PartialEq; S::ChildOutputDesc)]
#[derive(Deserialize, Serialize)]
#[serde(
    tag = "kind",
    rename_all = "kebab-case",
    bound(
        serialize = "S: SerializableOutputSpec",
        deserialize = "S: SerializableOutputSpec"
    )
)]
#[cfg_attr(
    test,
    derive(test_strategy::Arbitrary),
    arbitrary(bound(S: ArbitraryOutputSpec))
)]
pub enum OutputEventKind<S: OutputSpec> {
    /// A setup script finished.
    #[serde(rename_all = "kebab-case")]
    SetupScriptFinished {
        /// The stress index, if running a stress test.
        stress_index: Option<StressIndexSummary>,
        /// The index of this setup script.
        index: usize,
        /// The total number of setup scripts.
        total: usize,
        /// The script ID.
        script_id: ScriptId,
        /// The program that was run.
        program: String,
        /// The arguments to the program.
        args: Vec<String>,
        /// Whether output capture was disabled.
        no_capture: bool,
        /// The execution status.
        run_status: SetupScriptExecuteStatus<S>,
    },

    /// A test attempt failed and will be retried.
    #[serde(rename_all = "kebab-case")]
    TestAttemptFailedWillRetry {
        /// The stress index, if running a stress test.
        stress_index: Option<StressIndexSummary>,
        /// The test instance.
        test_instance: OwnedTestInstanceId,
        /// The execution status.
        run_status: ExecuteStatus<S>,
        /// The delay before the next attempt.
        #[cfg_attr(test, strategy(crate::reporter::test_helpers::arb_duration()))]
        delay_before_next_attempt: Duration,
        /// How to display failure output.
        failure_output: TestOutputDisplay,
        /// The number of tests currently running.
        running: usize,
    },

    /// A test finished.
    #[serde(rename_all = "kebab-case")]
    TestFinished {
        /// The stress index, if running a stress test.
        stress_index: Option<StressIndexSummary>,
        /// The test instance.
        test_instance: OwnedTestInstanceId,
        /// How to display success output.
        success_output: TestOutputDisplay,
        /// How to display failure output.
        failure_output: TestOutputDisplay,
        /// Whether to store success output in JUnit.
        junit_store_success_output: bool,
        /// Whether to store failure output in JUnit.
        junit_store_failure_output: bool,
        /// How flaky-fail tests should be reported in JUnit.
        #[serde(default)]
        junit_flaky_fail_status: JunitFlakyFailStatus,
        /// The execution statuses.
        run_statuses: ExecutionStatuses<S>,
        /// The current run statistics.
        current_stats: RunStats,
        /// The number of tests currently running.
        running: usize,
    },
}

impl TestEventKindSummary<LiveSpec> {
    fn from_test_event_kind(kind: TestEventKind<'_>) -> Option<Self> {
        Some(match kind {
            TestEventKind::RunStarted {
                run_id,
                test_list: _,
                profile_name,
                cli_args,
                stress_condition,
            } => Self::Core(CoreEventKind::RunStarted {
                run_id,
                profile_name,
                cli_args,
                stress_condition: stress_condition.map(StressConditionSummary::from),
            }),
            TestEventKind::StressSubRunStarted { progress } => {
                Self::Core(CoreEventKind::StressSubRunStarted { progress })
            }
            TestEventKind::SetupScriptStarted {
                stress_index,
                index,
                total,
                script_id,
                program,
                args,
                no_capture,
            } => Self::Core(CoreEventKind::SetupScriptStarted {
                stress_index: stress_index.map(StressIndexSummary::from),
                index,
                total,
                script_id,
                program,
                args: args.to_vec(),
                no_capture,
            }),
            TestEventKind::SetupScriptSlow {
                stress_index,
                script_id,
                program,
                args,
                elapsed,
                will_terminate,
            } => Self::Core(CoreEventKind::SetupScriptSlow {
                stress_index: stress_index.map(StressIndexSummary::from),
                script_id,
                program,
                args: args.to_vec(),
                elapsed,
                will_terminate,
            }),
            TestEventKind::TestStarted {
                stress_index,
                test_instance,
                slot_assignment,
                current_stats,
                running,
                command_line,
            } => Self::Core(CoreEventKind::TestStarted {
                stress_index: stress_index.map(StressIndexSummary::from),
                test_instance: test_instance.to_owned(),
                slot_assignment,
                current_stats,
                running,
                command_line,
            }),
            TestEventKind::TestSlow {
                stress_index,
                test_instance,
                retry_data,
                elapsed,
                will_terminate,
            } => Self::Core(CoreEventKind::TestSlow {
                stress_index: stress_index.map(StressIndexSummary::from),
                test_instance: test_instance.to_owned(),
                retry_data,
                elapsed,
                will_terminate,
            }),
            TestEventKind::TestRetryStarted {
                stress_index,
                test_instance,
                slot_assignment,
                retry_data,
                running,
                command_line,
            } => Self::Core(CoreEventKind::TestRetryStarted {
                stress_index: stress_index.map(StressIndexSummary::from),
                test_instance: test_instance.to_owned(),
                slot_assignment,
                retry_data,
                running,
                command_line,
            }),
            TestEventKind::TestSkipped {
                stress_index,
                test_instance,
                reason,
            } => Self::Core(CoreEventKind::TestSkipped {
                stress_index: stress_index.map(StressIndexSummary::from),
                test_instance: test_instance.to_owned(),
                reason,
            }),
            TestEventKind::RunBeginCancel {
                setup_scripts_running,
                current_stats,
                running,
            } => Self::Core(CoreEventKind::RunBeginCancel {
                setup_scripts_running,
                running,
                reason: current_stats
                    .cancel_reason
                    .expect("RunBeginCancel event has cancel reason"),
            }),
            TestEventKind::RunPaused {
                setup_scripts_running,
                running,
            } => Self::Core(CoreEventKind::RunPaused {
                setup_scripts_running,
                running,
            }),
            TestEventKind::RunContinued {
                setup_scripts_running,
                running,
            } => Self::Core(CoreEventKind::RunContinued {
                setup_scripts_running,
                running,
            }),
            TestEventKind::StressSubRunFinished {
                progress,
                sub_elapsed,
                sub_stats,
            } => Self::Core(CoreEventKind::StressSubRunFinished {
                progress,
                sub_elapsed,
                sub_stats,
            }),
            TestEventKind::RunFinished {
                run_id,
                start_time,
                elapsed,
                run_stats,
                outstanding_not_seen,
            } => Self::Core(CoreEventKind::RunFinished {
                run_id,
                start_time,
                elapsed,
                run_stats,
                outstanding_not_seen: outstanding_not_seen.map(|t| TestsNotSeenSummary {
                    not_seen: t.not_seen,
                    total_not_seen: t.total_not_seen,
                }),
            }),

            TestEventKind::SetupScriptFinished {
                stress_index,
                index,
                total,
                script_id,
                program,
                args,
                junit_store_success_output: _,
                junit_store_failure_output: _,
                no_capture,
                run_status,
            } => Self::Output(OutputEventKind::SetupScriptFinished {
                stress_index: stress_index.map(StressIndexSummary::from),
                index,
                total,
                script_id,
                program,
                args: args.to_vec(),
                no_capture,
                run_status,
            }),
            TestEventKind::TestAttemptFailedWillRetry {
                stress_index,
                test_instance,
                run_status,
                delay_before_next_attempt,
                failure_output,
                running,
            } => Self::Output(OutputEventKind::TestAttemptFailedWillRetry {
                stress_index: stress_index.map(StressIndexSummary::from),
                test_instance: test_instance.to_owned(),
                run_status,
                delay_before_next_attempt,
                failure_output,
                running,
            }),
            TestEventKind::TestFinished {
                stress_index,
                test_instance,
                success_output,
                failure_output,
                junit_store_success_output,
                junit_store_failure_output,
                junit_flaky_fail_status,
                run_statuses,
                current_stats,
                running,
            } => Self::Output(OutputEventKind::TestFinished {
                stress_index: stress_index.map(StressIndexSummary::from),
                test_instance: test_instance.to_owned(),
                success_output,
                failure_output,
                junit_store_success_output,
                junit_store_failure_output,
                junit_flaky_fail_status,
                run_statuses,
                current_stats,
                running,
            }),

            TestEventKind::InfoStarted { .. }
            | TestEventKind::InfoResponse { .. }
            | TestEventKind::InfoFinished { .. }
            | TestEventKind::InputEnter { .. }
            | TestEventKind::RunBeginKill { .. } => return None,
        })
    }
}

/// Serializable version of [`StressIndex`].
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(test, derive(test_strategy::Arbitrary))]
pub struct StressIndexSummary {
    /// The current stress index (0-indexed).
    pub current: u32,
    /// The total number of stress runs, if known.
    pub total: Option<NonZero<u32>>,
}

impl From<StressIndex> for StressIndexSummary {
    fn from(index: StressIndex) -> Self {
        Self {
            current: index.current,
            total: index.total,
        }
    }
}

/// Serializable version of [`StressCondition`].
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "kebab-case")]
#[cfg_attr(test, derive(test_strategy::Arbitrary))]
pub enum StressConditionSummary {
    /// Run for a specific count.
    Count {
        /// The count value, or None for infinite.
        count: Option<u32>,
    },
    /// Run for a specific duration.
    Duration {
        /// The duration to run for.
        #[cfg_attr(test, strategy(crate::reporter::test_helpers::arb_duration()))]
        duration: Duration,
    },
}

impl From<StressCondition> for StressConditionSummary {
    fn from(condition: StressCondition) -> Self {
        use crate::runner::StressCount;
        match condition {
            StressCondition::Count(count) => Self::Count {
                count: match count {
                    StressCount::Count { count: n } => Some(n.get()),
                    StressCount::Infinite => None,
                },
            },
            StressCondition::Duration(duration) => Self::Duration { duration },
        }
    }
}

/// Output kind for content-addressed file names.
///
/// Used to determine which dictionary to use for compression and to construct
/// content-addressed file names.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum OutputKind {
    /// Standard output.
    Stdout,
    /// Standard error.
    Stderr,
    /// Combined stdout and stderr.
    Combined,
}

impl OutputKind {
    /// Returns the string suffix for this output kind.
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Stdout => "stdout",
            Self::Stderr => "stderr",
            Self::Combined => "combined",
        }
    }
}

/// A validated output file name in the zip archive.
///
/// File names use content-addressed format: `{content_hash}-{stdout|stderr|combined}`
/// where `content_hash` is a 16-digit hex XXH3 hash of the output content.
///
/// This enables deduplication: identical outputs produce identical file names,
/// so stress runs with many iterations store only one copy of each unique output.
///
/// This type validates the format during deserialization to prevent path
/// traversal attacks from maliciously crafted archives.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OutputFileName(String);

impl OutputFileName {
    /// Creates a content-addressed file name from output bytes and kind.
    ///
    /// The file name is based on a hash of the content, enabling deduplication
    /// of identical outputs across stress iterations, retries, and tests.
    pub(crate) fn from_content(content: &[u8], kind: OutputKind) -> Self {
        let hash = xxhash_rust::xxh3::xxh3_64(content);
        Self(format!("{hash:016x}-{}", kind.as_str()))
    }

    /// Returns the file name as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Validates that a string is a valid output file name.
    ///
    /// Content-addressed format: `{16_hex_chars}-{stdout|stderr|combined}`
    fn validate(s: &str) -> bool {
        if s.contains('/') || s.contains('\\') || s.contains("..") {
            return false;
        }

        let valid_suffixes = ["-stdout", "-stderr", "-combined"];
        for suffix in valid_suffixes {
            if let Some(hash_part) = s.strip_suffix(suffix)
                && hash_part.len() == 16
                && hash_part
                    .chars()
                    .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c))
            {
                return true;
            }
        }

        false
    }
}

impl fmt::Display for OutputFileName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for OutputFileName {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Serialize for OutputFileName {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.0.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for OutputFileName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        if Self::validate(&s) {
            Ok(Self(s))
        } else {
            Err(serde::de::Error::custom(format!(
                "invalid output file name: {s}"
            )))
        }
    }
}

/// Output stored as a reference to a file in the zip archive.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(tag = "status", rename_all = "kebab-case")]
pub enum ZipStoreOutput {
    /// The output was empty or not captured.
    Empty,

    /// The output was stored in full.
    #[serde(rename_all = "kebab-case")]
    Full {
        /// The file name in the archive.
        file_name: OutputFileName,
    },

    /// The output was truncated to fit within size limits.
    #[serde(rename_all = "kebab-case")]
    Truncated {
        /// The file name in the archive.
        file_name: OutputFileName,
        /// The original size in bytes before truncation.
        original_size: u64,
    },
}

impl ZipStoreOutput {
    /// Returns the file name if output was stored, or `None` if empty.
    pub fn file_name(&self) -> Option<&OutputFileName> {
        match self {
            ZipStoreOutput::Empty => None,
            ZipStoreOutput::Full { file_name } | ZipStoreOutput::Truncated { file_name, .. } => {
                Some(file_name)
            }
        }
    }
}

/// A description of child process output stored in a recording.
///
/// This is the recording-side counterpart to [`ChildOutputDescription`]. Unlike
/// `ChildOutputDescription`, this type does not have a `NotLoaded` variant,
/// because recorded output is always present in the archive.
///
/// [`ChildOutputDescription`]: crate::reporter::events::ChildOutputDescription
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
#[cfg_attr(test, derive(test_strategy::Arbitrary))]
pub enum ZipStoreOutputDescription {
    /// The output was split into stdout and stderr.
    Split {
        /// Standard output, or `None` if not captured.
        stdout: Option<ZipStoreOutput>,
        /// Standard error, or `None` if not captured.
        stderr: Option<ZipStoreOutput>,
    },

    /// The output was combined into a single stream.
    Combined {
        /// The combined output.
        output: ZipStoreOutput,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output_spec::RecordingSpec;
    use test_strategy::proptest;

    #[proptest]
    fn test_event_summary_roundtrips(value: TestEventSummary<RecordingSpec>) {
        let json = serde_json::to_string(&value).expect("serialization succeeds");
        let roundtrip: TestEventSummary<RecordingSpec> =
            serde_json::from_str(&json).expect("deserialization succeeds");
        proptest::prop_assert_eq!(value, roundtrip);
    }

    #[test]
    fn test_output_file_name_from_content_stdout() {
        let content = b"hello world";
        let file_name = OutputFileName::from_content(content, OutputKind::Stdout);

        let s = file_name.as_str();
        assert!(s.ends_with("-stdout"), "should end with -stdout: {s}");
        assert_eq!(s.len(), 16 + 1 + 6, "should be 16 hex + hyphen + 'stdout'");

        let hash_part = &s[..16];
        assert!(
            hash_part.chars().all(|c| c.is_ascii_hexdigit()),
            "hash portion should be hex: {hash_part}"
        );
    }

    #[test]
    fn test_output_file_name_from_content_stderr() {
        let content = b"error message";
        let file_name = OutputFileName::from_content(content, OutputKind::Stderr);

        let s = file_name.as_str();
        assert!(s.ends_with("-stderr"), "should end with -stderr: {s}");
        assert_eq!(s.len(), 16 + 1 + 6, "should be 16 hex + hyphen + 'stderr'");
    }

    #[test]
    fn test_output_file_name_from_content_combined() {
        let content = b"combined output";
        let file_name = OutputFileName::from_content(content, OutputKind::Combined);

        let s = file_name.as_str();
        assert!(s.ends_with("-combined"), "should end with -combined: {s}");
        assert_eq!(
            s.len(),
            16 + 1 + 8,
            "should be 16 hex + hyphen + 'combined'"
        );
    }

    #[test]
    fn test_output_file_name_deterministic() {
        let content = b"deterministic content";
        let name1 = OutputFileName::from_content(content, OutputKind::Stdout);
        let name2 = OutputFileName::from_content(content, OutputKind::Stdout);
        assert_eq!(name1.as_str(), name2.as_str());
    }

    #[test]
    fn test_output_file_name_different_content_different_hash() {
        let content1 = b"content one";
        let content2 = b"content two";
        let name1 = OutputFileName::from_content(content1, OutputKind::Stdout);
        let name2 = OutputFileName::from_content(content2, OutputKind::Stdout);
        assert_ne!(name1.as_str(), name2.as_str());
    }

    #[test]
    fn test_output_file_name_same_content_different_kind() {
        let content = b"same content";
        let stdout = OutputFileName::from_content(content, OutputKind::Stdout);
        let stderr = OutputFileName::from_content(content, OutputKind::Stderr);
        assert_ne!(stdout.as_str(), stderr.as_str());

        let stdout_hash = &stdout.as_str()[..16];
        let stderr_hash = &stderr.as_str()[..16];
        assert_eq!(stdout_hash, stderr_hash);
    }

    #[test]
    fn test_output_file_name_empty_content() {
        let file_name = OutputFileName::from_content(b"", OutputKind::Stdout);
        let s = file_name.as_str();
        assert!(s.ends_with("-stdout"), "should end with -stdout: {s}");
        assert!(OutputFileName::validate(s), "should be valid: {s}");
    }

    #[test]
    fn test_output_file_name_validate_valid_content_addressed() {
        // Valid content-addressed patterns.
        assert!(OutputFileName::validate("0123456789abcdef-stdout"));
        assert!(OutputFileName::validate("fedcba9876543210-stderr"));
        assert!(OutputFileName::validate("aaaaaaaaaaaaaaaa-combined"));
        assert!(OutputFileName::validate("0000000000000000-stdout"));
        assert!(OutputFileName::validate("ffffffffffffffff-stderr"));
    }

    #[test]
    fn test_output_file_name_validate_invalid_patterns() {
        // Too short hash.
        assert!(!OutputFileName::validate("0123456789abcde-stdout"));
        assert!(!OutputFileName::validate("abc-stdout"));

        // Too long hash.
        assert!(!OutputFileName::validate("0123456789abcdef0-stdout"));

        // Invalid suffix.
        assert!(!OutputFileName::validate("0123456789abcdef-unknown"));
        assert!(!OutputFileName::validate("0123456789abcdef-out"));
        assert!(!OutputFileName::validate("0123456789abcdef"));

        // Non-hex characters in hash.
        assert!(!OutputFileName::validate("0123456789abcdeg-stdout"));
        assert!(!OutputFileName::validate("0123456789ABCDEF-stdout")); // uppercase not allowed

        // Path traversal attempts.
        assert!(!OutputFileName::validate("../0123456789abcdef-stdout"));
        assert!(!OutputFileName::validate("0123456789abcdef-stdout/"));
        assert!(!OutputFileName::validate("foo/0123456789abcdef-stdout"));
        assert!(!OutputFileName::validate("..\\0123456789abcdef-stdout"));
    }

    #[test]
    fn test_output_file_name_validate_rejects_old_format() {
        // Old identity-based format should be rejected.
        assert!(!OutputFileName::validate("test-abc123-1-stdout"));
        assert!(!OutputFileName::validate("test-abc123-s5-1-stderr"));
        assert!(!OutputFileName::validate("script-def456-stdout"));
        assert!(!OutputFileName::validate("script-def456-s3-stderr"));
    }

    #[test]
    fn test_output_file_name_serde_round_trip() {
        let content = b"test content for serde";
        let original = OutputFileName::from_content(content, OutputKind::Stdout);

        let json = serde_json::to_string(&original).expect("serialization failed");
        let deserialized: OutputFileName =
            serde_json::from_str(&json).expect("deserialization failed");

        assert_eq!(original.as_str(), deserialized.as_str());
    }

    #[test]
    fn test_output_file_name_deserialize_invalid() {
        // Invalid patterns should fail deserialization.
        let json = r#""invalid-file-name""#;
        let result: Result<OutputFileName, _> = serde_json::from_str(json);
        assert!(
            result.is_err(),
            "should fail to deserialize invalid pattern"
        );

        let json = r#""test-abc123-1-stdout""#; // Old format.
        let result: Result<OutputFileName, _> = serde_json::from_str(json);
        assert!(result.is_err(), "should reject old format");
    }

    #[test]
    fn test_zip_store_output_file_name() {
        let content = b"some output";
        let file_name = OutputFileName::from_content(content, OutputKind::Stdout);

        let empty = ZipStoreOutput::Empty;
        assert!(empty.file_name().is_none());

        let full = ZipStoreOutput::Full {
            file_name: file_name.clone(),
        };
        assert_eq!(
            full.file_name().map(|f| f.as_str()),
            Some(file_name.as_str())
        );

        let truncated = ZipStoreOutput::Truncated {
            file_name: file_name.clone(),
            original_size: 1000,
        };
        assert_eq!(
            truncated.file_name().map(|f| f.as_str()),
            Some(file_name.as_str())
        );
    }
}