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
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Recording format metadata shared between recorder and reader.

use super::{
    CompletedRunStats, ComponentSizes, RecordedRunInfo, RecordedRunStatus, RecordedSizes,
    StressCompletedRunStats,
};
use camino::Utf8Path;
use chrono::{DateTime, FixedOffset, Utc};
use eazip::{CompressionMethod, write::FileOptions};
use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
use nextest_metadata::{RustBinaryId, TestCaseName};
use quick_junit::ReportUuid;
use semver::Version;
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, BTreeSet},
    fmt,
    num::NonZero,
};

// ---
// Format version newtypes
// ---

/// Defines a newtype wrapper around `u32` for format versions.
///
/// Use `@default` variant to also derive `Default` (defaults to 0).
macro_rules! define_format_version {
    (
        $(#[$attr:meta])*
        $vis:vis struct $name:ident;
    ) => {
        $(#[$attr])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
        #[serde(transparent)]
        $vis struct $name(u32);

        impl $name {
            #[doc = concat!("Creates a new `", stringify!($name), "`.")]
            pub const fn new(version: u32) -> Self {
                Self(version)
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}", self.0)
            }
        }
    };

    (
        @default
        $(#[$attr:meta])*
        $vis:vis struct $name:ident;
    ) => {
        $(#[$attr])*
        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
        #[serde(transparent)]
        $vis struct $name(u32);

        impl $name {
            #[doc = concat!("Creates a new `", stringify!($name), "`.")]
            pub const fn new(version: u32) -> Self {
                Self(version)
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}", self.0)
            }
        }
    };
}

define_format_version! {
    /// Version of the `runs.json.zst` outer format.
    ///
    /// Increment this when adding new semantically important fields to `runs.json.zst`.
    /// Readers can read newer versions (assuming append-only evolution with serde
    /// defaults), but writers must refuse to write if the file version is higher
    /// than this.
    pub struct RunsJsonFormatVersion;
}

define_format_version! {
    /// Major version of the `store.zip` archive format for breaking changes to the
    /// archive structure.
    pub struct StoreFormatMajorVersion;
}

define_format_version! {
    @default
    /// Minor version of the `store.zip` archive format for additive changes.
    pub struct StoreFormatMinorVersion;
}

/// Combined major and minor version of the `store.zip` archive format.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StoreFormatVersion {
    /// The major version (breaking changes).
    pub major: StoreFormatMajorVersion,
    /// The minor version (additive changes).
    pub minor: StoreFormatMinorVersion,
}

impl StoreFormatVersion {
    /// Creates a new `StoreFormatVersion`.
    pub const fn new(major: StoreFormatMajorVersion, minor: StoreFormatMinorVersion) -> Self {
        Self { major, minor }
    }

    /// Checks if an archive with version `self` can be read by a reader that
    /// supports `supported`.
    pub fn check_readable_by(self, supported: Self) -> Result<(), StoreVersionIncompatibility> {
        if self.major < supported.major {
            return Err(StoreVersionIncompatibility::RecordingTooOld {
                recording_major: self.major,
                supported_major: supported.major,
                last_nextest_version: self.major.last_nextest_version(),
            });
        }
        if self.major > supported.major {
            return Err(StoreVersionIncompatibility::RecordingTooNew {
                recording_major: self.major,
                supported_major: supported.major,
            });
        }
        if self.minor > supported.minor {
            return Err(StoreVersionIncompatibility::MinorTooNew {
                recording_minor: self.minor,
                supported_minor: supported.minor,
            });
        }
        Ok(())
    }
}

impl fmt::Display for StoreFormatVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}", self.major, self.minor)
    }
}

impl StoreFormatMajorVersion {
    /// Returns the last nextest version that supported this store format major
    /// version, if known.
    ///
    /// This is used to provide actionable guidance when an archive is too old
    /// for the current nextest.
    pub fn last_nextest_version(self) -> Option<&'static str> {
        match self.0 {
            1 => Some("0.9.130"),
            _ => None,
        }
    }
}

/// An incompatibility between a recording's store format version and what the
/// reader supports.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StoreVersionIncompatibility {
    /// The recording's major version is older than the supported major version.
    RecordingTooOld {
        /// The major version in the recording.
        recording_major: StoreFormatMajorVersion,
        /// The major version this nextest supports.
        supported_major: StoreFormatMajorVersion,
        /// The last nextest version that supported the recording's major version,
        /// if known.
        last_nextest_version: Option<&'static str>,
    },
    /// The recording's major version is newer than the supported major version.
    RecordingTooNew {
        /// The major version in the recording.
        recording_major: StoreFormatMajorVersion,
        /// The major version this nextest supports.
        supported_major: StoreFormatMajorVersion,
    },
    /// The recording's minor version is newer than the supported minor version.
    MinorTooNew {
        /// The minor version in the recording.
        recording_minor: StoreFormatMinorVersion,
        /// The maximum minor version this nextest supports.
        supported_minor: StoreFormatMinorVersion,
    },
}

impl fmt::Display for StoreVersionIncompatibility {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RecordingTooOld {
                recording_major,
                supported_major,
                last_nextest_version,
            } => {
                write!(
                    f,
                    "recording has major version {recording_major}, \
                     but this nextest requires version {supported_major}"
                )?;
                if let Some(version) = last_nextest_version {
                    write!(f, " (use nextest <= {version} to replay this recording)")?;
                }
                Ok(())
            }
            Self::RecordingTooNew {
                recording_major,
                supported_major,
            } => {
                write!(
                    f,
                    "recording has major version {recording_major}, \
                     but this nextest only supports version {supported_major} \
                     (upgrade nextest to replay this recording)"
                )
            }
            Self::MinorTooNew {
                recording_minor,
                supported_minor,
            } => {
                write!(
                    f,
                    "minor version {} is newer than supported version {}",
                    recording_minor, supported_minor
                )
            }
        }
    }
}

// ---
// runs.json.zst format types
// ---

/// The current format version for runs.json.zst.
pub(super) const RUNS_JSON_FORMAT_VERSION: RunsJsonFormatVersion = RunsJsonFormatVersion::new(2);

/// The current format version for recorded test runs (store.zip and run.log).
///
/// This combines a major version (for breaking changes) and a minor version
/// (for additive changes). Readers check compatibility via
/// [`StoreFormatVersion::check_readable_by`].
///
/// Changelog:
///
/// - 1.1: Addition of the `flaky_result` field to `ExecutionStatuses`.
/// - 2.0: `slot_assignment` is now mandatory in `TestStarted` and
///   `TestRetryStarted` events.
pub const STORE_FORMAT_VERSION: StoreFormatVersion = StoreFormatVersion::new(
    StoreFormatMajorVersion::new(2),
    StoreFormatMinorVersion::new(0),
);

/// Whether a runs.json.zst file can be written to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunsJsonWritePermission {
    /// Writing is allowed.
    Allowed,
    /// Writing is not allowed because the file has a newer format version.
    Denied {
        /// The format version in the file.
        file_version: RunsJsonFormatVersion,
        /// The maximum version this nextest can write.
        max_supported_version: RunsJsonFormatVersion,
    },
}

/// The list of recorded runs (serialization format for runs.json.zst).
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(super) struct RecordedRunList {
    /// The format version of this file.
    pub(super) format_version: RunsJsonFormatVersion,

    /// When the store was last pruned.
    ///
    /// Used to implement once-daily implicit pruning. Explicit pruning via CLI
    /// always runs regardless of this value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) last_pruned_at: Option<DateTime<Utc>>,

    /// The list of runs.
    #[serde(default)]
    pub(super) runs: Vec<RecordedRun>,
}

/// Data extracted from a `RecordedRunList`.
pub(super) struct RunListData {
    pub(super) runs: Vec<RecordedRunInfo>,
    pub(super) last_pruned_at: Option<DateTime<Utc>>,
}

impl RecordedRunList {
    /// Creates a new, empty run list with the current format version.
    #[cfg(test)]
    fn new() -> Self {
        Self {
            format_version: RUNS_JSON_FORMAT_VERSION,
            last_pruned_at: None,
            runs: Vec::new(),
        }
    }

    /// Converts the serialization format to internal representation.
    pub(super) fn into_data(self) -> RunListData {
        RunListData {
            runs: self.runs.into_iter().map(RecordedRunInfo::from).collect(),
            last_pruned_at: self.last_pruned_at,
        }
    }

    /// Creates a serialization format from internal representation.
    ///
    /// Always uses the current format version. If the file had an older version,
    /// this effectively upgrades it when written back.
    pub(super) fn from_data(
        runs: &[RecordedRunInfo],
        last_pruned_at: Option<DateTime<Utc>>,
    ) -> Self {
        Self {
            format_version: RUNS_JSON_FORMAT_VERSION,
            last_pruned_at,
            runs: runs.iter().map(RecordedRun::from).collect(),
        }
    }

    /// Returns whether this runs.json.zst can be written to by this nextest version.
    ///
    /// If the file has a newer format version than we support, writing is denied
    /// to avoid data loss.
    pub(super) fn write_permission(&self) -> RunsJsonWritePermission {
        if self.format_version > RUNS_JSON_FORMAT_VERSION {
            RunsJsonWritePermission::Denied {
                file_version: self.format_version,
                max_supported_version: RUNS_JSON_FORMAT_VERSION,
            }
        } else {
            RunsJsonWritePermission::Allowed
        }
    }
}

/// Metadata about a recorded run (serialization format for runs.json.zst and portable recordings).
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(super) struct RecordedRun {
    /// The unique identifier for this run.
    pub(super) run_id: ReportUuid,
    /// The major format version of this run's store.zip and run.log.
    ///
    /// Runs with a different major version cannot be replayed by this nextest
    /// version.
    pub(super) store_format_version: StoreFormatMajorVersion,
    /// The minor format version of this run's store.zip and run.log.
    ///
    /// Runs with a newer minor version (same major) cannot be replayed by this
    /// nextest version. Older minor versions are compatible.
    #[serde(default)]
    pub(super) store_format_minor_version: StoreFormatMinorVersion,
    /// The version of nextest that created this run.
    pub(super) nextest_version: Version,
    /// When the run started.
    pub(super) started_at: DateTime<FixedOffset>,
    /// When this run was last written to.
    ///
    /// Used for LRU eviction. Updated when the run is created, when the run
    /// completes, and in the future when operations like `rerun` reference
    /// this run.
    pub(super) last_written_at: DateTime<FixedOffset>,
    /// Duration of the run in seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) duration_secs: Option<f64>,
    /// The command-line arguments used to invoke nextest.
    #[serde(default)]
    pub(super) cli_args: Vec<String>,
    /// Build scope arguments (package and target selection).
    ///
    /// These determine which packages and targets are built. In a rerun chain,
    /// these are inherited from the original run unless explicitly overridden.
    #[serde(default)]
    pub(super) build_scope_args: Vec<String>,
    /// Environment variables that affect nextest behavior (NEXTEST_* and CARGO_*).
    ///
    /// This has a default for deserializing old runs.json.zst files that don't have this field.
    #[serde(default)]
    pub(super) env_vars: BTreeMap<String, String>,
    /// The parent run ID.
    #[serde(default)]
    pub(super) parent_run_id: Option<ReportUuid>,
    /// Sizes broken down by component (log and store).
    ///
    /// This is all zeros until the run completes successfully.
    pub(super) sizes: RecordedSizesFormat,
    /// Status and statistics for the run.
    pub(super) status: RecordedRunStatusFormat,
}

/// Sizes broken down by component (serialization format for runs.json.zst).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(super) struct RecordedSizesFormat {
    /// Sizes for the run log (run.log.zst).
    pub(super) log: ComponentSizesFormat,
    /// Sizes for the store archive (store.zip).
    pub(super) store: ComponentSizesFormat,
}

/// Compressed and uncompressed sizes for a single component (serialization format).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(super) struct ComponentSizesFormat {
    /// Compressed size in bytes.
    pub(super) compressed: u64,
    /// Uncompressed size in bytes.
    pub(super) uncompressed: u64,
    /// Number of entries (records for log, files for store).
    #[serde(default)]
    pub(super) entries: u64,
}

impl From<RecordedSizes> for RecordedSizesFormat {
    fn from(sizes: RecordedSizes) -> Self {
        Self {
            log: ComponentSizesFormat {
                compressed: sizes.log.compressed,
                uncompressed: sizes.log.uncompressed,
                entries: sizes.log.entries,
            },
            store: ComponentSizesFormat {
                compressed: sizes.store.compressed,
                uncompressed: sizes.store.uncompressed,
                entries: sizes.store.entries,
            },
        }
    }
}

impl From<RecordedSizesFormat> for RecordedSizes {
    fn from(sizes: RecordedSizesFormat) -> Self {
        Self {
            log: ComponentSizes {
                compressed: sizes.log.compressed,
                uncompressed: sizes.log.uncompressed,
                entries: sizes.log.entries,
            },
            store: ComponentSizes {
                compressed: sizes.store.compressed,
                uncompressed: sizes.store.uncompressed,
                entries: sizes.store.entries,
            },
        }
    }
}

/// Status of a recorded run (serialization format).
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "status", rename_all = "kebab-case")]
pub(super) enum RecordedRunStatusFormat {
    /// The run was interrupted before completion.
    Incomplete,
    /// A normal test run completed.
    #[serde(rename_all = "kebab-case")]
    Completed {
        /// The number of tests that were expected to run.
        initial_run_count: usize,
        /// The number of tests that passed.
        passed: usize,
        /// The number of tests that failed.
        failed: usize,
        /// The exit code from the run.
        exit_code: i32,
    },
    /// A normal test run was cancelled.
    #[serde(rename_all = "kebab-case")]
    Cancelled {
        /// The number of tests that were expected to run.
        initial_run_count: usize,
        /// The number of tests that passed.
        passed: usize,
        /// The number of tests that failed.
        failed: usize,
        /// The exit code from the run.
        exit_code: i32,
    },
    /// A stress test run completed.
    #[serde(rename_all = "kebab-case")]
    StressCompleted {
        /// The number of stress iterations that were expected to run, if known.
        initial_iteration_count: Option<NonZero<u32>>,
        /// The number of stress iterations that succeeded.
        success_count: u32,
        /// The number of stress iterations that failed.
        failed_count: u32,
        /// The exit code from the run.
        exit_code: i32,
    },
    /// A stress test run was cancelled.
    #[serde(rename_all = "kebab-case")]
    StressCancelled {
        /// The number of stress iterations that were expected to run, if known.
        initial_iteration_count: Option<NonZero<u32>>,
        /// The number of stress iterations that succeeded.
        success_count: u32,
        /// The number of stress iterations that failed.
        failed_count: u32,
        /// The exit code from the run.
        exit_code: i32,
    },
    /// An unknown status from a newer version of nextest.
    ///
    /// This variant is used for forward compatibility when reading runs.json.zst
    /// files created by newer nextest versions that may have new status types.
    #[serde(other)]
    Unknown,
}

impl From<RecordedRun> for RecordedRunInfo {
    fn from(run: RecordedRun) -> Self {
        Self {
            run_id: run.run_id,
            store_format_version: StoreFormatVersion::new(
                run.store_format_version,
                run.store_format_minor_version,
            ),
            nextest_version: run.nextest_version,
            started_at: run.started_at,
            last_written_at: run.last_written_at,
            duration_secs: run.duration_secs,
            cli_args: run.cli_args,
            build_scope_args: run.build_scope_args,
            env_vars: run.env_vars,
            parent_run_id: run.parent_run_id,
            sizes: run.sizes.into(),
            status: run.status.into(),
        }
    }
}

impl From<&RecordedRunInfo> for RecordedRun {
    fn from(run: &RecordedRunInfo) -> Self {
        Self {
            run_id: run.run_id,
            store_format_version: run.store_format_version.major,
            store_format_minor_version: run.store_format_version.minor,
            nextest_version: run.nextest_version.clone(),
            started_at: run.started_at,
            last_written_at: run.last_written_at,
            duration_secs: run.duration_secs,
            cli_args: run.cli_args.clone(),
            build_scope_args: run.build_scope_args.clone(),
            env_vars: run.env_vars.clone(),
            parent_run_id: run.parent_run_id,
            sizes: run.sizes.into(),
            status: (&run.status).into(),
        }
    }
}

impl From<RecordedRunStatusFormat> for RecordedRunStatus {
    fn from(status: RecordedRunStatusFormat) -> Self {
        match status {
            RecordedRunStatusFormat::Incomplete => Self::Incomplete,
            RecordedRunStatusFormat::Unknown => Self::Unknown,
            RecordedRunStatusFormat::Completed {
                initial_run_count,
                passed,
                failed,
                exit_code,
            } => Self::Completed(CompletedRunStats {
                initial_run_count,
                passed,
                failed,
                exit_code,
            }),
            RecordedRunStatusFormat::Cancelled {
                initial_run_count,
                passed,
                failed,
                exit_code,
            } => Self::Cancelled(CompletedRunStats {
                initial_run_count,
                passed,
                failed,
                exit_code,
            }),
            RecordedRunStatusFormat::StressCompleted {
                initial_iteration_count,
                success_count,
                failed_count,
                exit_code,
            } => Self::StressCompleted(StressCompletedRunStats {
                initial_iteration_count,
                success_count,
                failed_count,
                exit_code,
            }),
            RecordedRunStatusFormat::StressCancelled {
                initial_iteration_count,
                success_count,
                failed_count,
                exit_code,
            } => Self::StressCancelled(StressCompletedRunStats {
                initial_iteration_count,
                success_count,
                failed_count,
                exit_code,
            }),
        }
    }
}

impl From<&RecordedRunStatus> for RecordedRunStatusFormat {
    fn from(status: &RecordedRunStatus) -> Self {
        match status {
            RecordedRunStatus::Incomplete => Self::Incomplete,
            RecordedRunStatus::Unknown => Self::Unknown,
            RecordedRunStatus::Completed(stats) => Self::Completed {
                initial_run_count: stats.initial_run_count,
                passed: stats.passed,
                failed: stats.failed,
                exit_code: stats.exit_code,
            },
            RecordedRunStatus::Cancelled(stats) => Self::Cancelled {
                initial_run_count: stats.initial_run_count,
                passed: stats.passed,
                failed: stats.failed,
                exit_code: stats.exit_code,
            },
            RecordedRunStatus::StressCompleted(stats) => Self::StressCompleted {
                initial_iteration_count: stats.initial_iteration_count,
                success_count: stats.success_count,
                failed_count: stats.failed_count,
                exit_code: stats.exit_code,
            },
            RecordedRunStatus::StressCancelled(stats) => Self::StressCancelled {
                initial_iteration_count: stats.initial_iteration_count,
                success_count: stats.success_count,
                failed_count: stats.failed_count,
                exit_code: stats.exit_code,
            },
        }
    }
}

// ---
// Rerun types
// ---

/// Rerun-specific metadata stored in `meta/rerun-info.json`.
///
/// This is only present for reruns (runs with a parent run).
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RerunInfo {
    /// The immediate parent run ID.
    pub parent_run_id: ReportUuid,

    /// Root information from the original run.
    pub root_info: RerunRootInfo,

    /// The set of outstanding and passing test cases.
    pub test_suites: IdOrdMap<RerunTestSuiteInfo>,
}

/// For a rerun, information obtained from the root of the rerun chain.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RerunRootInfo {
    /// The run ID.
    pub run_id: ReportUuid,

    /// Build scope args from the original run.
    pub build_scope_args: Vec<String>,
}

impl RerunRootInfo {
    /// Creates a new `RerunRootInfo` for a root of a rerun chain.
    ///
    /// `build_scope_args` should be the build scope arguments extracted from
    /// the original run's CLI args. Use `extract_build_scope_args` from
    /// `cargo-nextest` to extract these.
    pub fn new(run_id: ReportUuid, build_scope_args: Vec<String>) -> Self {
        Self {
            run_id,
            build_scope_args,
        }
    }
}

/// A test suite's outstanding and passing test cases.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct RerunTestSuiteInfo {
    /// The binary ID.
    pub binary_id: RustBinaryId,

    /// The set of passing test cases.
    pub passing: BTreeSet<TestCaseName>,

    /// The set of outstanding test cases.
    pub outstanding: BTreeSet<TestCaseName>,
}

impl RerunTestSuiteInfo {
    pub(super) fn new(binary_id: RustBinaryId) -> Self {
        Self {
            binary_id,
            passing: BTreeSet::new(),
            outstanding: BTreeSet::new(),
        }
    }
}

impl IdOrdItem for RerunTestSuiteInfo {
    type Key<'a> = &'a RustBinaryId;
    fn key(&self) -> Self::Key<'_> {
        &self.binary_id
    }
    id_upcast!();
}

// ---
// Recording format types
// ---

/// File name for the store archive.
pub static STORE_ZIP_FILE_NAME: &str = "store.zip";

/// File name for the run log.
pub static RUN_LOG_FILE_NAME: &str = "run.log.zst";

/// Returns true if the path has a `.zip` extension (case-insensitive).
pub fn has_zip_extension(path: &Utf8Path) -> bool {
    path.extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("zip"))
}

// Paths within the zip archive.
/// Path to cargo metadata within the store archive.
pub static CARGO_METADATA_JSON_PATH: &str = "meta/cargo-metadata.json";
/// Path to the test list within the store archive.
pub static TEST_LIST_JSON_PATH: &str = "meta/test-list.json";
/// Path to record options within the store archive.
pub static RECORD_OPTS_JSON_PATH: &str = "meta/record-opts.json";
/// Path to rerun info within the store archive (only present for reruns).
pub static RERUN_INFO_JSON_PATH: &str = "meta/rerun-info.json";
/// Path to the stdout dictionary within the store archive.
pub static STDOUT_DICT_PATH: &str = "meta/stdout.dict";
/// Path to the stderr dictionary within the store archive.
pub static STDERR_DICT_PATH: &str = "meta/stderr.dict";

// ---
// Portable recording format types
// ---

define_format_version! {
    /// Major version of the portable recording format for breaking changes.
    pub struct PortableRecordingFormatMajorVersion;
}

define_format_version! {
    @default
    /// Minor version of the portable recording format for additive changes.
    pub struct PortableRecordingFormatMinorVersion;
}

/// Combined major and minor version of the portable recording format.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct PortableRecordingFormatVersion {
    /// The major version (breaking changes).
    pub major: PortableRecordingFormatMajorVersion,
    /// The minor version (additive changes).
    pub minor: PortableRecordingFormatMinorVersion,
}

impl PortableRecordingFormatVersion {
    /// Creates a new `PortableRecordingFormatVersion`.
    pub const fn new(
        major: PortableRecordingFormatMajorVersion,
        minor: PortableRecordingFormatMinorVersion,
    ) -> Self {
        Self { major, minor }
    }

    /// Checks if an archive with version `self` can be read by a reader that
    /// supports `supported`.
    pub fn check_readable_by(
        self,
        supported: Self,
    ) -> Result<(), PortableRecordingVersionIncompatibility> {
        if self.major != supported.major {
            return Err(PortableRecordingVersionIncompatibility::MajorMismatch {
                recording_major: self.major,
                supported_major: supported.major,
            });
        }
        if self.minor > supported.minor {
            return Err(PortableRecordingVersionIncompatibility::MinorTooNew {
                recording_minor: self.minor,
                supported_minor: supported.minor,
            });
        }
        Ok(())
    }
}

impl fmt::Display for PortableRecordingFormatVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}", self.major, self.minor)
    }
}

/// An incompatibility between an archive's portable format version and what the
/// reader supports.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PortableRecordingVersionIncompatibility {
    /// The archive's major version differs from the supported major version.
    MajorMismatch {
        /// The major version in the archive.
        recording_major: PortableRecordingFormatMajorVersion,
        /// The major version this nextest supports.
        supported_major: PortableRecordingFormatMajorVersion,
    },
    /// The archive's minor version is newer than the supported minor version.
    MinorTooNew {
        /// The minor version in the archive.
        recording_minor: PortableRecordingFormatMinorVersion,
        /// The maximum minor version this nextest supports.
        supported_minor: PortableRecordingFormatMinorVersion,
    },
}

impl fmt::Display for PortableRecordingVersionIncompatibility {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MajorMismatch {
                recording_major,
                supported_major,
            } => {
                write!(
                    f,
                    "major version {} differs from supported version {}",
                    recording_major, supported_major
                )
            }
            Self::MinorTooNew {
                recording_minor,
                supported_minor,
            } => {
                write!(
                    f,
                    "minor version {} is newer than supported version {}",
                    recording_minor, supported_minor
                )
            }
        }
    }
}

/// The current format version for portable recordings.
pub const PORTABLE_RECORDING_FORMAT_VERSION: PortableRecordingFormatVersion =
    PortableRecordingFormatVersion::new(
        PortableRecordingFormatMajorVersion::new(1),
        PortableRecordingFormatMinorVersion::new(0),
    );

/// File name for the manifest within a portable recording.
pub static PORTABLE_MANIFEST_FILE_NAME: &str = "manifest.json";

/// The manifest for a portable recording.
///
/// A portable recording packages a single recorded run into a self-contained
/// zip file for sharing and import.
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) struct PortableManifest {
    /// The format version of this portable recording.
    pub(crate) format_version: PortableRecordingFormatVersion,
    /// The run metadata.
    pub(super) run: RecordedRun,
}

impl PortableManifest {
    /// Creates a new manifest for the given run.
    pub(crate) fn new(run: &RecordedRunInfo) -> Self {
        Self {
            format_version: PORTABLE_RECORDING_FORMAT_VERSION,
            run: RecordedRun::from(run),
        }
    }

    /// Returns the run info extracted from this manifest.
    pub(crate) fn run_info(&self) -> RecordedRunInfo {
        RecordedRunInfo::from(self.run.clone())
    }

    /// Returns the store format version from the run metadata.
    pub(crate) fn store_format_version(&self) -> StoreFormatVersion {
        StoreFormatVersion::new(
            self.run.store_format_version,
            self.run.store_format_minor_version,
        )
    }
}

/// Which dictionary to use for compressing/decompressing a file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutputDict {
    /// Use the stdout dictionary (for stdout and combined output).
    Stdout,
    /// Use the stderr dictionary.
    Stderr,
    /// Use standard zstd compression (for metadata files).
    None,
}

impl OutputDict {
    /// Determines which dictionary to use based on the file path.
    ///
    /// Output files in `out/` use dictionaries based on their suffix:
    /// - `-stdout` and `-combined` use the stdout dictionary.
    /// - `-stderr` uses the stderr dictionary.
    ///
    /// All other files (metadata in `meta/`) use standard zstd.
    pub fn for_path(path: &Utf8Path) -> Self {
        let mut iter = path.iter();
        let Some(first_component) = iter.next() else {
            return Self::None;
        };
        // Output files are always in the out/ directory.
        if first_component != "out" {
            return Self::None;
        }

        Self::for_output_file_name(iter.as_path().as_str())
    }

    /// Determines which dictionary to use based on the output file name.
    ///
    /// The file name should be the basename without the `out/` prefix,
    /// e.g., `test-abc123-1-stdout`.
    pub fn for_output_file_name(file_name: &str) -> Self {
        if file_name.ends_with("-stdout") || file_name.ends_with("-combined") {
            Self::Stdout
        } else if file_name.ends_with("-stderr") {
            Self::Stderr
        } else {
            // Unknown output type, use standard compression.
            Self::None
        }
    }

    /// Returns the dictionary bytes for this output type (for writing new archives).
    ///
    /// Returns `None` for `OutputDict::None`.
    pub fn dict_bytes(self) -> Option<&'static [u8]> {
        match self {
            Self::Stdout => Some(super::dicts::STDOUT),
            Self::Stderr => Some(super::dicts::STDERR),
            Self::None => None,
        }
    }
}

// ---
// Zip file options helpers
// ---

/// Returns file options for storing pre-compressed data (no additional
/// compression).
pub(super) fn stored_file_options() -> FileOptions {
    let mut options = FileOptions::default();
    options.compression_method = CompressionMethod::STORE;
    options
}

/// Returns file options for zstd-compressed data.
pub(super) fn zstd_file_options() -> FileOptions {
    let mut options = FileOptions::default();
    options.compression_method = CompressionMethod::ZSTD;
    options.level = Some(3);
    options
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_output_dict_for_path() {
        // Metadata files should not use dictionaries.
        assert_eq!(
            OutputDict::for_path("meta/cargo-metadata.json".as_ref()),
            OutputDict::None
        );
        assert_eq!(
            OutputDict::for_path("meta/test-list.json".as_ref()),
            OutputDict::None
        );

        // Content-addressed output files should use appropriate dictionaries.
        assert_eq!(
            OutputDict::for_path("out/0123456789abcdef-stdout".as_ref()),
            OutputDict::Stdout
        );
        assert_eq!(
            OutputDict::for_path("out/0123456789abcdef-stderr".as_ref()),
            OutputDict::Stderr
        );
        assert_eq!(
            OutputDict::for_path("out/0123456789abcdef-combined".as_ref()),
            OutputDict::Stdout
        );
    }

    #[test]
    fn test_output_dict_for_output_file_name() {
        // Content-addressed file names.
        assert_eq!(
            OutputDict::for_output_file_name("0123456789abcdef-stdout"),
            OutputDict::Stdout
        );
        assert_eq!(
            OutputDict::for_output_file_name("0123456789abcdef-stderr"),
            OutputDict::Stderr
        );
        assert_eq!(
            OutputDict::for_output_file_name("0123456789abcdef-combined"),
            OutputDict::Stdout
        );
        assert_eq!(
            OutputDict::for_output_file_name("0123456789abcdef-unknown"),
            OutputDict::None
        );
    }

    #[test]
    fn test_dict_bytes() {
        assert!(OutputDict::Stdout.dict_bytes().is_some());
        assert!(OutputDict::Stderr.dict_bytes().is_some());
        assert!(OutputDict::None.dict_bytes().is_none());
    }

    #[test]
    fn test_runs_json_missing_version() {
        // runs.json.zst without format-version should fail to deserialize.
        let json = r#"{"runs": []}"#;
        let result: Result<RecordedRunList, _> = serde_json::from_str(json);
        assert!(result.is_err(), "expected error for missing format-version");
    }

    #[test]
    fn test_runs_json_current_version() {
        // runs.json.zst with current version should deserialize and allow writes.
        let json = format!(
            r#"{{"format-version": {}, "runs": []}}"#,
            RUNS_JSON_FORMAT_VERSION
        );
        let list: RecordedRunList = serde_json::from_str(&json).expect("should deserialize");
        assert_eq!(list.write_permission(), RunsJsonWritePermission::Allowed);
    }

    #[test]
    fn test_runs_json_older_version() {
        // runs.json.zst with older version (if any existed) should allow writes.
        // Since we only have version 1, test version 0 if we supported it.
        // For now, this test just ensures version 1 allows writes.
        let json = r#"{"format-version": 1, "runs": []}"#;
        let list: RecordedRunList = serde_json::from_str(json).expect("should deserialize");
        assert_eq!(list.write_permission(), RunsJsonWritePermission::Allowed);
    }

    #[test]
    fn test_runs_json_newer_version() {
        // runs.json.zst with newer version should deserialize but deny writes.
        let json = r#"{"format-version": 99, "runs": []}"#;
        let list: RecordedRunList = serde_json::from_str(json).expect("should deserialize");
        assert_eq!(
            list.write_permission(),
            RunsJsonWritePermission::Denied {
                file_version: RunsJsonFormatVersion::new(99),
                max_supported_version: RUNS_JSON_FORMAT_VERSION,
            }
        );
    }

    #[test]
    fn test_runs_json_serialization_includes_version() {
        // Serialized runs.json.zst should always include format-version.
        let list = RecordedRunList::from_data(&[], None);
        let json = serde_json::to_string(&list).expect("should serialize");
        assert!(
            json.contains("format-version"),
            "serialized runs.json.zst should include format-version"
        );

        // Verify it's the current version.
        let parsed: serde_json::Value = serde_json::from_str(&json).expect("should parse");
        let version: RunsJsonFormatVersion =
            serde_json::from_value(parsed["format-version"].clone()).expect("valid version");
        assert_eq!(
            version, RUNS_JSON_FORMAT_VERSION,
            "format-version should be current version"
        );
    }

    #[test]
    fn test_runs_json_new() {
        // RecordedRunList::new() should create with current version.
        let list = RecordedRunList::new();
        assert_eq!(list.format_version, RUNS_JSON_FORMAT_VERSION);
        assert!(list.runs.is_empty());
        assert_eq!(list.write_permission(), RunsJsonWritePermission::Allowed);
    }

    // --- RecordedRun serialization snapshot tests ---

    fn make_test_run(status: RecordedRunStatusFormat) -> RecordedRun {
        RecordedRun {
            run_id: ReportUuid::from_u128(0x550e8400_e29b_41d4_a716_446655440000),
            store_format_version: STORE_FORMAT_VERSION.major,
            store_format_minor_version: STORE_FORMAT_VERSION.minor,
            nextest_version: Version::new(0, 9, 111),
            started_at: DateTime::parse_from_rfc3339("2024-12-19T14:22:33-08:00")
                .expect("valid timestamp"),
            last_written_at: DateTime::parse_from_rfc3339("2024-12-19T22:22:33Z")
                .expect("valid timestamp"),
            duration_secs: Some(12.345),
            cli_args: vec![
                "cargo".to_owned(),
                "nextest".to_owned(),
                "run".to_owned(),
                "--workspace".to_owned(),
            ],
            build_scope_args: vec!["--workspace".to_owned()],
            env_vars: BTreeMap::from([
                ("CARGO_TERM_COLOR".to_owned(), "always".to_owned()),
                ("NEXTEST_PROFILE".to_owned(), "ci".to_owned()),
            ]),
            parent_run_id: Some(ReportUuid::from_u128(
                0x550e7400_e29b_41d4_a716_446655440000,
            )),
            sizes: RecordedSizesFormat {
                log: ComponentSizesFormat {
                    compressed: 2345,
                    uncompressed: 5678,
                    entries: 42,
                },
                store: ComponentSizesFormat {
                    compressed: 10000,
                    uncompressed: 40000,
                    entries: 15,
                },
            },
            status,
        }
    }

    #[test]
    fn test_recorded_run_serialize_incomplete() {
        let run = make_test_run(RecordedRunStatusFormat::Incomplete);
        let json = serde_json::to_string_pretty(&run).expect("serialization should succeed");
        insta::assert_snapshot!(json);
    }

    #[test]
    fn test_recorded_run_serialize_completed() {
        let run = make_test_run(RecordedRunStatusFormat::Completed {
            initial_run_count: 100,
            passed: 95,
            failed: 5,
            exit_code: 0,
        });
        let json = serde_json::to_string_pretty(&run).expect("serialization should succeed");
        insta::assert_snapshot!(json);
    }

    #[test]
    fn test_recorded_run_serialize_cancelled() {
        let run = make_test_run(RecordedRunStatusFormat::Cancelled {
            initial_run_count: 100,
            passed: 45,
            failed: 5,
            exit_code: 100,
        });
        let json = serde_json::to_string_pretty(&run).expect("serialization should succeed");
        insta::assert_snapshot!(json);
    }

    #[test]
    fn test_recorded_run_serialize_stress_completed() {
        let run = make_test_run(RecordedRunStatusFormat::StressCompleted {
            initial_iteration_count: NonZero::new(100),
            success_count: 98,
            failed_count: 2,
            exit_code: 0,
        });
        let json = serde_json::to_string_pretty(&run).expect("serialization should succeed");
        insta::assert_snapshot!(json);
    }

    #[test]
    fn test_recorded_run_serialize_stress_cancelled() {
        let run = make_test_run(RecordedRunStatusFormat::StressCancelled {
            initial_iteration_count: NonZero::new(100),
            success_count: 45,
            failed_count: 5,
            exit_code: 100,
        });
        let json = serde_json::to_string_pretty(&run).expect("serialization should succeed");
        insta::assert_snapshot!(json);
    }

    #[test]
    fn test_recorded_run_deserialize_unknown_status() {
        // Simulate a run from a future nextest version with an unknown status.
        // The store-format-version is set to 999 to indicate a future version.
        let json = r#"{
            "run-id": "550e8400-e29b-41d4-a716-446655440000",
            "store-format-version": 999,
            "nextest-version": "0.9.999",
            "started-at": "2024-12-19T14:22:33-08:00",
            "last-written-at": "2024-12-19T22:22:33Z",
            "cli-args": ["cargo", "nextest", "run"],
            "env-vars": {},
            "sizes": {
                "log": { "compressed": 2345, "uncompressed": 5678 },
                "store": { "compressed": 10000, "uncompressed": 40000 }
            },
            "status": {
                "status": "super-new-status",
                "some-future-field": 42
            }
        }"#;
        let run: RecordedRun = serde_json::from_str(json).expect("should deserialize");
        assert!(
            matches!(run.status, RecordedRunStatusFormat::Unknown),
            "unknown status should deserialize to Unknown variant"
        );

        // Verify domain conversion preserves Unknown.
        let info: RecordedRunInfo = run.into();
        assert!(
            matches!(info.status, RecordedRunStatus::Unknown),
            "Unknown format should convert to Unknown domain type"
        );
    }

    #[test]
    fn test_recorded_run_roundtrip() {
        let original = make_test_run(RecordedRunStatusFormat::Completed {
            initial_run_count: 100,
            passed: 95,
            failed: 5,
            exit_code: 0,
        });
        let json = serde_json::to_string(&original).expect("serialization should succeed");
        let roundtripped: RecordedRun =
            serde_json::from_str(&json).expect("deserialization should succeed");

        assert_eq!(roundtripped.run_id, original.run_id);
        assert_eq!(roundtripped.nextest_version, original.nextest_version);
        assert_eq!(roundtripped.started_at, original.started_at);
        assert_eq!(roundtripped.sizes, original.sizes);

        // Verify status fields via domain conversion.
        let info: RecordedRunInfo = roundtripped.into();
        match info.status {
            RecordedRunStatus::Completed(stats) => {
                assert_eq!(stats.initial_run_count, 100);
                assert_eq!(stats.passed, 95);
                assert_eq!(stats.failed, 5);
            }
            _ => panic!("expected Completed variant"),
        }
    }

    // --- Store format version tests ---

    /// Helper to create a StoreFormatVersion.
    fn version(major: u32, minor: u32) -> StoreFormatVersion {
        StoreFormatVersion::new(
            StoreFormatMajorVersion::new(major),
            StoreFormatMinorVersion::new(minor),
        )
    }

    #[test]
    fn test_store_version_compatibility() {
        assert!(
            version(1, 0).check_readable_by(version(1, 0)).is_ok(),
            "same version should be compatible"
        );

        assert!(
            version(1, 0).check_readable_by(version(1, 2)).is_ok(),
            "older minor version should be compatible"
        );

        let error = version(1, 3).check_readable_by(version(1, 2)).unwrap_err();
        assert_eq!(
            error,
            StoreVersionIncompatibility::MinorTooNew {
                recording_minor: StoreFormatMinorVersion::new(3),
                supported_minor: StoreFormatMinorVersion::new(2),
            },
            "newer minor version should be incompatible"
        );
        insta::assert_snapshot!(error.to_string(), @"minor version 3 is newer than supported version 2");

        // Archive newer than supported → RecordingTooNew.
        let error = version(2, 0).check_readable_by(version(1, 5)).unwrap_err();
        assert_eq!(
            error,
            StoreVersionIncompatibility::RecordingTooNew {
                recording_major: StoreFormatMajorVersion::new(2),
                supported_major: StoreFormatMajorVersion::new(1),
            },
        );
        insta::assert_snapshot!(
            error.to_string(),
            @"recording has major version 2, but this nextest only supports version 1 (upgrade nextest to replay this recording)"
        );

        // Archive older than supported → ArchiveTooOld (with known version).
        let error = version(1, 0).check_readable_by(version(2, 0)).unwrap_err();
        assert_eq!(
            error,
            StoreVersionIncompatibility::RecordingTooOld {
                recording_major: StoreFormatMajorVersion::new(1),
                supported_major: StoreFormatMajorVersion::new(2),
                last_nextest_version: Some("0.9.130"),
            },
        );
        insta::assert_snapshot!(
            error.to_string(),
            @"recording has major version 1, but this nextest requires version 2 (use nextest <= 0.9.130 to replay this recording)"
        );

        // Archive older than supported → ArchiveTooOld (unknown version).
        let error = version(3, 0).check_readable_by(version(5, 0)).unwrap_err();
        assert_eq!(
            error,
            StoreVersionIncompatibility::RecordingTooOld {
                recording_major: StoreFormatMajorVersion::new(3),
                supported_major: StoreFormatMajorVersion::new(5),
                last_nextest_version: None,
            },
        );
        insta::assert_snapshot!(
            error.to_string(),
            @"recording has major version 3, but this nextest requires version 5"
        );

        insta::assert_snapshot!(version(1, 2).to_string(), @"1.2");
    }

    #[test]
    fn test_recorded_run_deserialize_without_minor_version() {
        // Old archives without store-format-minor-version should default to 0.
        let json = r#"{
            "run-id": "550e8400-e29b-41d4-a716-446655440000",
            "store-format-version": 1,
            "nextest-version": "0.9.111",
            "started-at": "2024-12-19T14:22:33-08:00",
            "last-written-at": "2024-12-19T22:22:33Z",
            "cli-args": [],
            "env-vars": {},
            "sizes": {
                "log": { "compressed": 0, "uncompressed": 0 },
                "store": { "compressed": 0, "uncompressed": 0 }
            },
            "status": { "status": "incomplete" }
        }"#;
        let run: RecordedRun = serde_json::from_str(json).expect("should deserialize");
        assert_eq!(run.store_format_version, StoreFormatMajorVersion::new(1));
        assert_eq!(
            run.store_format_minor_version,
            StoreFormatMinorVersion::new(0)
        );

        // Domain conversion should produce a StoreFormatVersion with minor 0.
        let info: RecordedRunInfo = run.into();
        assert_eq!(info.store_format_version, version(1, 0));
    }

    #[test]
    fn test_recorded_run_serialize_includes_minor_version() {
        // New archives should include store-format-minor-version in serialization.
        let run = make_test_run(RecordedRunStatusFormat::Incomplete);
        let json = serde_json::to_string_pretty(&run).expect("serialization should succeed");
        assert!(
            json.contains("store-format-minor-version"),
            "serialized run should include store-format-minor-version"
        );
    }

    // --- Portable archive format version tests ---

    /// Helper to create a PortableRecordingFormatVersion.
    fn portable_version(major: u32, minor: u32) -> PortableRecordingFormatVersion {
        PortableRecordingFormatVersion::new(
            PortableRecordingFormatMajorVersion::new(major),
            PortableRecordingFormatMinorVersion::new(minor),
        )
    }

    #[test]
    fn test_portable_version_compatibility() {
        assert!(
            portable_version(1, 0)
                .check_readable_by(portable_version(1, 0))
                .is_ok(),
            "same version should be compatible"
        );

        assert!(
            portable_version(1, 0)
                .check_readable_by(portable_version(1, 2))
                .is_ok(),
            "older minor version should be compatible"
        );

        let error = portable_version(1, 3)
            .check_readable_by(portable_version(1, 2))
            .unwrap_err();
        assert_eq!(
            error,
            PortableRecordingVersionIncompatibility::MinorTooNew {
                recording_minor: PortableRecordingFormatMinorVersion::new(3),
                supported_minor: PortableRecordingFormatMinorVersion::new(2),
            },
            "newer minor version should be incompatible"
        );
        insta::assert_snapshot!(error.to_string(), @"minor version 3 is newer than supported version 2");

        let error = portable_version(2, 0)
            .check_readable_by(portable_version(1, 5))
            .unwrap_err();
        assert_eq!(
            error,
            PortableRecordingVersionIncompatibility::MajorMismatch {
                recording_major: PortableRecordingFormatMajorVersion::new(2),
                supported_major: PortableRecordingFormatMajorVersion::new(1),
            },
            "different major version should be incompatible"
        );
        insta::assert_snapshot!(error.to_string(), @"major version 2 differs from supported version 1");

        insta::assert_snapshot!(portable_version(1, 2).to_string(), @"1.2");
    }

    #[test]
    fn test_portable_version_serialization() {
        // Test that PortableRecordingFormatVersion serializes to {major: ..., minor: ...}.
        let version = portable_version(1, 0);
        let json = serde_json::to_string(&version).expect("serialization should succeed");
        insta::assert_snapshot!(json, @r#"{"major":1,"minor":0}"#);

        // Test roundtrip.
        let roundtripped: PortableRecordingFormatVersion =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert_eq!(roundtripped, version);
    }

    #[test]
    fn test_portable_manifest_format_version() {
        // Verify the current PORTABLE_RECORDING_FORMAT_VERSION constant.
        assert_eq!(
            PORTABLE_RECORDING_FORMAT_VERSION,
            portable_version(1, 0),
            "current portable recording format version should be 1.0"
        );
    }
}