hermit-run 0.4.0

Hermit: a deterministic Linux execution engine for reproducible runs, record and replay, and concurrency-race search.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
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
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
//! Machine-readable verification reports shared by the Hermit producer and its consumers.

use serde::Deserialize;
use serde::Serialize;

/// The verification verdict, independent of the guest's exit status.
///
/// A guest that deterministically exits nonzero can still match, while a guest
/// that exits zero can still diverge. Consumers must read this value rather than
/// infer the verdict from either the process status or human-readable stderr.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
    /// The two runs matched on every compared dimension.
    Matched,
    /// The two runs diverged; verification failed.
    Diverged,
    /// Verification stopped before it could reach a verdict.
    NoResult,
    /// Verification completed enough work to name an understood machine or
    /// harness failure, so the receipt is neither a product verdict nor an
    /// unknown no-result.
    InfrastructureError,
}

impl std::fmt::Display for Verdict {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Matched => "matched",
            Self::Diverged => "diverged",
            Self::NoResult => "no_result",
            Self::InfrastructureError => "infrastructure_error",
        })
    }
}

/// Why verification did not reach a verdict.
///
/// This distinction is functional evidence. `FirstRunRejected` means the guest
/// ran and its disposition was rejected by `--verify-allow`; `NotRun` is the
/// pre-run stamp left when the invocation died before recording a more specific
/// result. Collapsing both into `no_result` made a completed guest refusal and a
/// container or launcher failure indistinguishable to the result reader.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum NoResultReason {
    /// The invocation did not replace the pre-run stamp with a more specific
    /// outcome.
    NotRun,
    /// Run 1 completed and its exit status was rejected by `--verify-allow`.
    FirstRunRejected {
        exit_code: Option<i32>,
        signal: Option<i32>,
        stdout_bytes: u64,
        stderr_bytes: u64,
    },
    /// The log comparator refused to claim either agreement or divergence.
    ComparisonRefused { detail: String },
    /// A sandbox exited before returning its guest Output. This is an
    /// attempted execution failure, with no guest disposition or comparison.
    ContainerFailed(ContainerFailure),
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum VerificationRun {
    Run1,
    Run2,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "kind", deny_unknown_fields)]
pub enum ContainerDisposition {
    /// Zero is possible when the child exits without returning its result.
    Exited {
        code: i32,
    },
    Signaled {
        signal: i32,
        core_dumped: bool,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ContainerFailure {
    pub run: VerificationRun,
    pub disposition: ContainerDisposition,
}

impl ContainerFailure {
    /// `main` returns 125 for ContainerChildExit. This is the enclosing Hermit
    /// process's status, distinct from the container disposition above.
    pub fn require_reporter_exit(
        &self,
        status: Option<i32>,
        signal: Option<i32>,
        timed_out: bool,
    ) -> Result<(), String> {
        if status == Some(125) && signal.is_none() && !timed_out {
            Ok(())
        } else {
            Err(format!(
                "container_failed contradicts Hermit process disposition: status={status:?} signal={signal:?} timed_out={timed_out} (expected exit 125 without timeout)"
            ))
        }
    }
}

/// The understood infrastructure failure recorded by verification.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum InfrastructureError {
    /// A ptrace PMU timer interrupt arrived after its target. Both runs and
    /// their comparison may still be retained, but the result is not admitted.
    SkidOvershoot { count: u64 },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RuntimeStats {
    pub scheduler_turns: u64,
    pub virtual_nanoseconds: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub syscalls: Option<u64>,
    /// The run's backend dispatch record, copied from its summary. Absent for
    /// a backend without one (KVM) and in reports written before the record.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dispatch: Option<detcore_model::summary::DispatchStats>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct VerificationRuntime {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub run1: Option<RuntimeStats>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub run2: Option<RuntimeStats>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DbtCountedBranchComparison {
    pub left: u64,
    pub right: u64,
}

impl DbtCountedBranchComparison {
    #[allow(dead_code)] // path-included consumers do not all construct DBT outcomes
    pub fn matched(self) -> bool {
        self.left == self.right
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LogCompareStrictness {
    Stripped,
    Canonical,
}

impl std::fmt::Display for LogCompareStrictness {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Stripped => "stripped",
            Self::Canonical => "canonical",
        })
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ComparedLogScope {
    Deterministic,
    Info,
    FullTrace,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RecordEnvelopeReport {
    AllRecordsV1,
    DbtEvidenceTransportV1,
    CrossBackendDetcoreV1,
    CallerDefined,
}

impl RecordEnvelopeReport {
    pub fn is_canonical(self) -> bool {
        matches!(self, Self::AllRecordsV1 | Self::DbtEvidenceTransportV1)
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::AllRecordsV1 => "all_records_v1",
            Self::DbtEvidenceTransportV1 => "dbt_evidence_transport_v1",
            Self::CrossBackendDetcoreV1 => "cross_backend_detcore_v1",
            Self::CallerDefined => "caller_defined",
        }
    }
}

/// The comparison fields serialized beside a verification verdict.
///
/// Fields added after the original report are optional here so retained reports
/// remain readable. A current producer writes every one of them, and
/// [`VerificationReport::from_current_json_value`] checks their presence.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ComparisonReport {
    pub strictness: LogCompareStrictness,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    pub compare_logs: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compare_io_buffers: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub log_scope: Option<ComparedLogScope>,
    pub record_envelope: RecordEnvelopeReport,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub virtualize_time: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strip_lines: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canonicalize_addresses: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub full_trace: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exact_remainder: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stripped_prefixes: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canonicalizations: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ignore_lines: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skip_commit: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skip_detlog: Option<bool>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ComparedLogMessages {
    pub left: u64,
    pub right: u64,
}

/// Content identity and disposition of one guest execution.
///
/// The bytes themselves remain in the invoking process or retained artifacts;
/// these fields make the exact stdout/stderr/status comparison independently
/// checkable without attempting to recover guest stderr from controller logs.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ComparedOutput {
    pub exit_code: Option<i32>,
    pub signal: Option<i32>,
    pub stdout_sha256: String,
    pub stdout_bytes: u64,
    pub stderr_sha256: String,
    pub stderr_bytes: u64,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ComparedOutputs {
    pub left: ComparedOutput,
    pub right: ComparedOutput,
}

impl ComparedOutputs {
    pub fn require_exact_match(&self) -> Result<(), String> {
        if self.left == self.right {
            Ok(())
        } else {
            Err("verification operands differ in status, stdout, or stderr".into())
        }
    }
}

/// The complete machine-readable report written by `--verify-json`.
///
/// This type is shared by the Hermit producer, the manifest runner, the
/// compatibility pressure test, and the scorecard. The serialized field order
/// is retained because existing report bytes are hashed as evidence.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct VerificationReport {
    pub verified: bool,
    pub bitwise_parity: bool,
    pub verdict: Verdict,
    #[serde(default)]
    pub no_result_reason: Option<NoResultReason>,
    #[serde(default)]
    pub infrastructure_error: Option<InfrastructureError>,
    /// `None` when the producer reached no verdict. This is a DOCUMENTED
    /// producer state, not a malformed report: `VerificationReport::no_result()`
    /// in hermit-cli sets it, and its doc says "`null` when no verdict was
    /// reached". Declaring it non-optional made a legitimate no-result
    /// deserialise as "unreadable report", which reported an infrastructure
    /// fault where the truth was that nothing had been recorded.
    #[serde(deserialize_with = "present_but_nullable_comparison")]
    pub comparison: Option<ComparisonReport>,
    pub compared_log_messages: Option<ComparedLogMessages>,
    /// Exact output/status evidence for both executions. Optional only so
    /// retained reports written before this field remain readable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compared_outputs: Option<ComparedOutputs>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dbt_counted_branches: Option<DbtCountedBranchComparison>,
    /// Runtime totals for the two compared executions when the producer could
    /// read both run summaries.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime: Option<VerificationRuntime>,
    /// The guest's exit code when an exited status was available to the
    /// producer. `None` means either that `guest_signal` records a signal
    /// disposition, or that execution did not return a guest status at all;
    /// current producers must not leave this null for `ExitStatus::Exited`.
    #[serde(default)]
    pub guest_exit_code: Option<i32>,
    /// The guest's signal when a signaled status was available to the producer.
    /// When both disposition fields are null, the writer had no guest status.
    #[serde(default)]
    pub guest_signal: Option<i32>,
    /// WHERE the divergence began, in scheduler-turn units. `None` when the
    /// logs matched, when no comparison ran, or when the report predates the
    /// field.
    ///
    /// `#[serde(default)]` is deliberate here and is the OPPOSITE choice from
    /// `ComparisonReport::record_envelope` above. That field is an admission
    /// gate, so a missing value must never be supplied on the producer's
    /// behalf. This one is a diagnostic position: absent means "not located",
    /// which is exactly what `None` says. Requiring it would turn every
    /// retained pre-field report into an unreadable-report ERROR and
    /// misclassify old evidence as an infrastructure fault -- the same trap
    /// documented on `comparison` just above.
    #[serde(default)]
    pub first_divergent_scheduler_turn: Option<u64>,
    /// WHERE the divergence began, in virtual-nanosecond units. Same
    /// tolerant-default rationale as the field above.
    ///
    /// NOTE both of these are the position of the PRECEDING scheduler COMMIT,
    /// so when no COMMIT precedes the differing record they collapse to the
    /// origin and BOUND the divergence rather than locating it. The field below
    /// is the one that locates it.
    #[serde(default)]
    pub first_divergent_virtual_nanoseconds: Option<u64>,
    /// 1-based index of the first differing compared record -- the LOCATION of
    /// the divergence rather than a bound on it, and the only one of the three
    /// that is a true log prefix. It shares a unit with
    /// `compared_log_messages`, so `record / compared` is the fraction of the
    /// log that was deterministic.
    ///
    /// `null` and `0` are not the same claim: null is "no divergence located",
    /// while 0 would mean the very first record differed. Nothing writes 0 --
    /// the index is 1-based. Same tolerant-default rationale as its siblings.
    #[serde(default)]
    pub first_divergent_record: Option<u64>,
    /// How many syscalls the guest had COMPLETED when the divergence appeared,
    /// from detcore's own `finish syscall #N` counter.
    ///
    /// NOT interchangeable with `first_divergent_record`: one counts guest work
    /// and the other counts compared log records, and they move at completely
    /// different rates. Measured on one real divergence: record 98, syscall 37.
    /// `null` also covers a genuine state -- a run that diverged before any
    /// syscall completed.
    #[serde(default)]
    pub first_divergent_syscall: Option<u64>,
    /// First differing compared message from the left execution, with the
    /// separately recorded syscall number, scheduler turn, and committed time
    /// removed. Older reports omit it and remain readable.
    #[serde(default)]
    pub first_divergent_left_message: Option<String>,
    /// Corresponding first differing compared message from the right execution.
    #[serde(default)]
    pub first_divergent_right_message: Option<String>,
}

/// Accept `null` but not a MISSING field. serde maps an absent `Option` field to
/// `None` by default, which would let a report that never mentioned a comparison
/// read as a legitimate no-result. Naming a `deserialize_with` makes the field
/// required again while still admitting an explicit null.
fn present_but_nullable_comparison<'de, D>(
    deserializer: D,
) -> Result<Option<ComparisonReport>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    Option::<ComparisonReport>::deserialize(deserializer)
}

impl VerificationReport {
    #[allow(dead_code)] // path-included retained-report readers do not produce reports
    pub fn no_result() -> Self {
        Self {
            verified: false,
            bitwise_parity: false,
            verdict: Verdict::NoResult,
            no_result_reason: Some(NoResultReason::NotRun),
            infrastructure_error: None,
            comparison: None,
            compared_log_messages: None,
            compared_outputs: None,
            dbt_counted_branches: None,
            runtime: None,
            guest_exit_code: None,
            guest_signal: None,
            first_divergent_scheduler_turn: None,
            first_divergent_virtual_nanoseconds: None,
            first_divergent_record: None,
            first_divergent_syscall: None,
            first_divergent_left_message: None,
            first_divergent_right_message: None,
        }
    }

    /// `null` is legal only when no comparison completed: either the producer
    /// reached no verdict, or it named an infrastructure error before it could
    /// compare. A null comparison beside a product verdict is contradictory
    /// and stays refused at parse.
    fn require_consistent_outcome_fields(self) -> Result<Self, String> {
        if let Some(NoResultReason::ContainerFailed(failure)) = &self.no_result_reason {
            let valid_status = match failure.disposition {
                // classify_container_result reserves these normal exit codes
                // for policy refusal, deadline, and mapped signal stops.
                ContainerDisposition::Exited { code } => {
                    // The deadline constant currently lives in hermit-cli,
                    // which this shared schema's manifest reader cannot import.
                    const DEADLINE_EXIT: i32 = 124;
                    (0..=255).contains(&code)
                        && code != detcore_model::HERMIT_POLICY_REFUSAL_EXIT
                        && code != DEADLINE_EXIT
                        && detcore_model::signal_from_exit_status(code).is_none()
                }
                ContainerDisposition::Signaled { signal, .. } => (1..=64).contains(&signal),
            };
            if !valid_status {
                return Err("invalid container_failed disposition".into());
            }
            // No Output returned from the failed run. In particular, run 1's
            // status must not be relabelled as the failed run 2's guest status.
            if self.verdict != Verdict::NoResult
                || self.verified
                || self.bitwise_parity
                || self.infrastructure_error.is_some()
                || self.comparison.is_some()
                || self.compared_log_messages.is_some()
                || self.compared_outputs.is_some()
                || self.dbt_counted_branches.is_some()
                || self.runtime.is_some()
                || self.guest_exit_code.is_some()
                || self.guest_signal.is_some()
                || self.first_divergent_scheduler_turn.is_some()
                || self.first_divergent_virtual_nanoseconds.is_some()
                || self.first_divergent_record.is_some()
                || self.first_divergent_syscall.is_some()
                || self.first_divergent_left_message.is_some()
                || self.first_divergent_right_message.is_some()
            {
                return Err(
                    "container_failed contradicts its no-comparison, unknown-guest outcome".into(),
                );
            }
        }
        if self.comparison.is_none()
            && !matches!(
                self.verdict,
                Verdict::NoResult | Verdict::InfrastructureError
            )
        {
            return Err(format!(
                "incomplete verification report: comparison is null but verdict is {}; null is legal only for no_result or infrastructure_error",
                self.verdict
            ));
        }
        match (&self.verdict, &self.infrastructure_error) {
            (Verdict::InfrastructureError, Some(InfrastructureError::SkidOvershoot { count }))
                if *count > 0 => {}
            (Verdict::InfrastructureError, Some(InfrastructureError::SkidOvershoot { .. })) => {
                return Err(
                    "incomplete verification report: skid_overshoot count must be positive".into(),
                );
            }
            (Verdict::InfrastructureError, None) => {
                return Err(
                    "incomplete verification report: infrastructure_error verdict omitted infrastructure_error"
                        .into(),
                );
            }
            (_, Some(_)) => {
                return Err(format!(
                    "inconsistent verification report: verdict={} carries infrastructure_error",
                    self.verdict
                ));
            }
            (_, None) => {}
        }
        Ok(self)
    }

    /// Parse the complete typed receipt. A top-level JSON object is not enough:
    /// every nested field used by admission must deserialize successfully.
    #[allow(dead_code)] // this file is path-included by consumers that use one parse form
    pub fn from_json_slice(bytes: &[u8]) -> Result<Self, String> {
        serde_json::from_slice::<Self>(bytes)
            .map_err(|error| format!("incomplete verification report: {error}"))?
            .require_consistent_outcome_fields()
    }

    #[allow(dead_code)] // this file is path-included by consumers that use one parse form
    pub fn from_json_value(value: serde_json::Value) -> Result<Self, String> {
        serde_json::from_value::<Self>(value)
            .map_err(|error| format!("incomplete verification report: {error}"))?
            .require_consistent_outcome_fields()
    }

    /// Parse a report written by the current producer and require every field
    /// it promises to emit, preserving duplicate-field refusal from the original
    /// bytes. Parsing only a Value would silently collapse duplicate object keys.
    #[allow(dead_code)] // path-included readers use different parse forms
    pub fn from_current_json_slice(bytes: &[u8]) -> Result<Self, String> {
        let report = Self::from_json_slice(bytes)?;
        let value = serde_json::from_slice(bytes)
            .map_err(|error| format!("incomplete verification report: {error}"))?;
        Self::from_current_json_value(value)?;
        Ok(report)
    }

    /// Parse a report written by the current producer and require every field
    /// that producer promises to emit. Retained-report readers use
    /// [`Self::from_json_value`] instead so fields added after an old run remain
    /// honest absence rather than making the whole report unreadable.
    #[allow(dead_code)] // path-included readers use different parse forms
    pub fn from_current_json_value(value: serde_json::Value) -> Result<Self, String> {
        Self::from_producer_json_value(value, true)
    }

    /// Parse a retained cell receipt from before exact output evidence was
    /// added. Preserve that absence while retaining the other producer-field
    /// and duplicate-key requirements. This is not current producer admission
    /// and must not be used for either operand of backend parity.
    #[allow(dead_code)] // only retained cell receipt readers use this form
    pub fn from_retained_cell_json_slice(bytes: &[u8]) -> Result<Self, String> {
        let report = Self::from_json_slice(bytes)?;
        let value = serde_json::from_slice(bytes)
            .map_err(|error| format!("incomplete verification report: {error}"))?;
        Self::from_producer_json_value(value, false)?;
        Ok(report)
    }

    fn from_producer_json_value(
        value: serde_json::Value,
        require_outputs: bool,
    ) -> Result<Self, String> {
        let object = value
            .as_object()
            .ok_or_else(|| "incomplete verification report: expected an object".to_string())?;
        for field in [
            "verified",
            "bitwise_parity",
            "verdict",
            "infrastructure_error",
            "comparison",
            "no_result_reason",
            "compared_log_messages",
            "guest_exit_code",
            "guest_signal",
            "first_divergent_scheduler_turn",
            "first_divergent_virtual_nanoseconds",
            "first_divergent_record",
            "first_divergent_syscall",
            "first_divergent_left_message",
            "first_divergent_right_message",
        ] {
            if !object.contains_key(field) {
                return Err(format!(
                    "incomplete verification report: missing current producer field `{field}`"
                ));
            }
        }
        let verdict = object.get("verdict").and_then(serde_json::Value::as_str);
        if require_outputs
            && matches!(verdict, Some("matched" | "diverged"))
            && object
                .get("compared_outputs")
                .is_none_or(serde_json::Value::is_null)
        {
            return Err(
                "incomplete verification report: missing current producer field `compared_outputs`"
                    .into(),
            );
        }
        if let Some(comparison) = object
            .get("comparison")
            .and_then(serde_json::Value::as_object)
        {
            for field in [
                "strictness",
                "display_name",
                "compare_logs",
                "compare_io_buffers",
                "log_scope",
                "record_envelope",
                "virtualize_time",
                "strip_lines",
                "canonicalize_addresses",
                "full_trace",
                "exact_remainder",
                "stripped_prefixes",
                "canonicalizations",
                "ignore_lines",
                "skip_commit",
                "skip_detlog",
            ] {
                if !comparison.contains_key(field) {
                    return Err(format!(
                        "incomplete verification report: missing current comparison field `{field}`"
                    ));
                }
            }
        }
        let report = Self::from_json_value(value)?;
        // Historical receipts may predate this field. When a matched report
        // explicitly carries outputs, they must support its claim even if the
        // receipt was read through the retained-input compatibility path.
        if report.verdict == Verdict::Matched && report.compared_outputs.is_some() {
            report.require_exact_output_match()?;
        }
        if report.verdict == Verdict::NoResult && report.compared_outputs.is_some() {
            return Err(
                "inconsistent verification report: no_result carries compared_outputs".into(),
            );
        }
        match (&report.verdict, &report.no_result_reason) {
            (Verdict::NoResult, Some(NoResultReason::ComparisonRefused { detail }))
                if detail.trim().is_empty() =>
            {
                Err("incomplete verification report: comparison_refused omitted its detail".into())
            }
            (Verdict::NoResult, Some(_)) => Ok(report),
            (Verdict::NoResult, None) => Ok(report),
            (_, Some(_)) => Err(format!(
                "inconsistent verification report: verdict={} carries no_result_reason",
                report.verdict
            )),
            (_, None) => Ok(report),
        }
    }

    /// Prove that the invocation actually compared the canonical INFO evidence.
    /// This is separate from whether that comparison matched: a canonical
    /// divergence is a product result, while a stripped/output-only/empty-log
    /// comparison is incomplete evidence and therefore an infrastructure result.
    pub fn require_canonical_comparison(&self) -> Result<(), String> {
        let counts = self.compared_log_messages.as_ref();
        // No comparison at all is a distinct outcome from a comparison that was
        // too weak, and it is still not admissible. Naming it separately is the
        // whole point: "no verdict was recorded" is actionable against the
        // producer, while the old "unreadable report" pointed at the reader.
        let Some(comparison) = self.comparison.as_ref() else {
            return Err(format!(
                "verification recorded no comparison at all (verdict={}), so there is no canonical INFO evidence to admit",
                self.verdict
            ));
        };
        if comparison.strictness == LogCompareStrictness::Canonical
            && comparison.compare_logs
            && comparison.record_envelope.is_canonical()
            && counts.is_some_and(|counts| counts.left > 0 && counts.right > 0)
        {
            Ok(())
        } else {
            Err(format!(
                "verification did not compare canonical non-vacuous INFO evidence: strictness={} compare_logs={} record_envelope={} messages={}/{}",
                comparison.strictness,
                comparison.compare_logs,
                comparison.record_envelope.as_str(),
                counts.map_or(0, |counts| counts.left),
                counts.map_or(0, |counts| counts.right),
            ))
        }
    }

    /// Require complete, identical guest outputs for a current strict operand.
    /// Historical log-only receipts retain their separate admission path.
    pub fn require_exact_output_match(&self) -> Result<(), String> {
        let outputs = self
            .compared_outputs
            .as_ref()
            .ok_or("same-backend verification omitted exact output evidence")?;
        outputs.require_exact_match()?;
        let output = &outputs.left;
        for (field, digest) in [
            ("stdout_sha256", output.stdout_sha256.as_str()),
            ("stderr_sha256", output.stderr_sha256.as_str()),
        ] {
            if digest.len() != 64
                || !digest
                    .bytes()
                    .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
            {
                return Err(format!("{field} is not a SHA-256 digest"));
            }
        }
        if output.exit_code.is_some() == output.signal.is_some() {
            return Err(
                "output must record exactly one guest disposition (exit code or signal)".into(),
            );
        }
        if self.guest_exit_code != output.exit_code || self.guest_signal != output.signal {
            return Err("output disposition contradicts its verification result".into());
        }
        Ok(())
    }

    /// Admit a green only when both the canonical comparison and the match
    /// claim agree. `verified=true` alone is intentionally insufficient: KVM's
    /// output-only fallback can report it with zero compared INFO messages.
    pub fn require_canonical_match(&self) -> Result<(), String> {
        self.require_canonical_comparison()?;
        if self.compared_outputs.is_some() {
            self.require_exact_output_match()?;
        }
        if self.verified && self.verdict == Verdict::Matched && self.bitwise_parity {
            Ok(())
        } else {
            Err(format!(
                "canonical verification did not match: verified={} verdict={} bitwise_parity={}",
                self.verified, self.verdict, self.bitwise_parity
            ))
        }
    }
}

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

    fn failed_container_report(
        run: VerificationRun,
        disposition: ContainerDisposition,
    ) -> VerificationReport {
        let mut report = VerificationReport::no_result();
        report.no_result_reason = Some(NoResultReason::ContainerFailed(ContainerFailure {
            run,
            disposition,
        }));
        report
    }

    #[test]
    fn container_failure_requires_exact_actor_and_absent_comparison_fields() {
        for run in [VerificationRun::Run1, VerificationRun::Run2] {
            for disposition in [
                ContainerDisposition::Exited { code: 0 },
                ContainerDisposition::Exited { code: 101 },
                ContainerDisposition::Signaled {
                    signal: 14,
                    core_dumped: false,
                },
                ContainerDisposition::Signaled {
                    signal: 11,
                    core_dumped: true,
                },
            ] {
                let report = failed_container_report(run, disposition);
                let bytes = serde_json::to_vec(&report).unwrap();
                assert_eq!(
                    VerificationReport::from_current_json_slice(&bytes).unwrap(),
                    report
                );
                assert!(report.require_canonical_comparison().is_err());
                assert!(report.require_canonical_match().is_err());
                let NoResultReason::ContainerFailed(failure) =
                    report.no_result_reason.as_ref().unwrap()
                else {
                    unreachable!()
                };
                failure
                    .require_reporter_exit(Some(125), None, false)
                    .unwrap();
                for (status, signal, timeout) in [
                    (Some(0), None, false),
                    (Some(122), None, false),
                    (None, Some(14), false),
                    (Some(125), None, true),
                ] {
                    assert!(
                        failure
                            .require_reporter_exit(status, signal, timeout)
                            .is_err()
                    );
                }
                let value = serde_json::to_value(&report).unwrap();
                for (field, invented) in [
                    ("verified", serde_json::json!(true)),
                    ("bitwise_parity", serde_json::json!(true)),
                    ("verdict", serde_json::json!("matched")),
                    ("guest_exit_code", serde_json::json!(0)),
                    ("guest_signal", serde_json::json!(14)),
                    (
                        "runtime",
                        serde_json::json!({"run1":{"scheduler_turns":1,"virtual_nanoseconds":2}}),
                    ),
                    (
                        "compared_log_messages",
                        serde_json::json!({"left":1,"right":1}),
                    ),
                    ("first_divergent_record", serde_json::json!(1)),
                    ("first_divergent_syscall", serde_json::json!(1)),
                    ("first_divergent_scheduler_turn", serde_json::json!(1)),
                    ("first_divergent_virtual_nanoseconds", serde_json::json!(1)),
                    (
                        "first_divergent_left_message",
                        serde_json::json!("invented"),
                    ),
                    (
                        "first_divergent_right_message",
                        serde_json::json!("invented"),
                    ),
                    (
                        "dbt_counted_branches",
                        serde_json::json!({"left":1,"right":1}),
                    ),
                    (
                        "infrastructure_error",
                        serde_json::json!({"kind":"skid_overshoot","count":1}),
                    ),
                ] {
                    let mut bad = value.clone();
                    bad[field] = invented;
                    let bytes = serde_json::to_vec(&bad).unwrap();
                    assert!(
                        VerificationReport::from_current_json_slice(&bytes).is_err(),
                        "{field}"
                    );
                    assert!(
                        VerificationReport::from_retained_cell_json_slice(&bytes).is_err(),
                        "{field}"
                    );
                }
            }
        }
    }

    #[test]
    fn container_failure_rejects_malformed_duplicate_and_reserved_dispositions() {
        let report = failed_container_report(
            VerificationRun::Run1,
            ContainerDisposition::Exited { code: 0 },
        );
        let value = serde_json::to_value(report).unwrap();
        for code in [-1, 122, 124, 129, 142, 192, 256] {
            let mut bad = value.clone();
            bad["no_result_reason"]["disposition"]["code"] = code.into();
            assert!(
                VerificationReport::from_current_json_value(bad).is_err(),
                "{code}"
            );
        }
        for replacement in [
            serde_json::json!({"kind":"container_failed","disposition":{"kind":"exited","code":1}}),
            serde_json::json!({"kind":"container_failed","run":"run3","disposition":{"kind":"exited","code":1}}),
            serde_json::json!({"kind":"container_failed","run":"run1","disposition":{"kind":"exited","code":1,"signal":14}}),
            serde_json::json!({"kind":"container_failed","run":"run1","disposition":{"kind":"signaled","signal":14}}),
            serde_json::json!({"kind":"container_failed","run":"run1","disposition":{"kind":"signaled","signal":0,"core_dumped":false}}),
            serde_json::json!({"kind":"container_failed","run":"run1","disposition":{"kind":"signaled","signal":65,"core_dumped":false}}),
            serde_json::json!({"kind":"container_failed","run":"run1","extra":true,"disposition":{"kind":"exited","code":1}}),
        ] {
            let mut bad = value.clone();
            bad["no_result_reason"] = replacement;
            assert!(VerificationReport::from_current_json_value(bad).is_err());
        }
        let raw = serde_json::to_string(&value).unwrap();
        for (needle, replacement) in [
            (r#""run":"run1""#, r#""run":"run1","run":"run2""#),
            (r#""code":0"#, r#""code":0,"code":0"#),
        ] {
            assert!(raw.contains(needle));
            let bad = raw.replacen(needle, replacement, 1);
            assert!(
                VerificationReport::from_current_json_slice(bad.as_bytes())
                    .unwrap_err()
                    .contains("duplicate field")
            );
        }
    }

    /// The divergence position must survive the parse. It was already being
    /// emitted by hermit and already present in the retained report string, but
    /// this struct dropped it, so no cell could ever report where its
    /// divergence began.
    #[test]
    fn divergence_position_survives_the_parse() {
        let json = br#"{"verified":false,"bitwise_parity":false,"verdict":"diverged",
            "comparison":{"strictness":"canonical","compare_logs":true,"record_envelope":"all_records_v1"},"compared_log_messages":{"left":180,"right":180},
            "first_divergent_scheduler_turn":4,
            "first_divergent_virtual_nanoseconds":1767225600002825515,
            "first_divergent_record":108,
            "first_divergent_syscall":37,
            "first_divergent_left_message":"INFO detcore: left event",
            "first_divergent_right_message":"INFO detcore: right event"}"#;
        let report = VerificationReport::from_json_slice(json).expect("diverged report parses");
        assert_eq!(report.first_divergent_scheduler_turn, Some(4));
        assert_eq!(
            report.first_divergent_virtual_nanoseconds,
            Some(1_767_225_600_002_825_515)
        );
        assert_eq!(report.first_divergent_record, Some(108));
        // THE FOURTH COORDINATE, asserted because it was the one that could
        // stop arriving unnoticed. Demonstrated 2026-08-25: with this line
        // absent, renaming the field so no real report could populate it left
        // all 11 tests in this module GREEN. A struct field nothing asserts is
        // indistinguishable from one nothing populates.
        assert_eq!(report.first_divergent_syscall, Some(37));
        assert_eq!(
            report.first_divergent_left_message.as_deref(),
            Some("INFO detcore: left event")
        );
        assert_eq!(
            report.first_divergent_right_message.as_deref(),
            Some("INFO detcore: right event")
        );
    }

    /// The record index is the only coordinate that LOCATES the divergence;
    /// the other two are the preceding COMMIT and merely bound it. So a report
    /// can carry a record with both bounds collapsed to the origin, and that
    /// is a MORE informative report rather than a malformed one.
    #[test]
    fn a_located_record_does_not_require_its_bounding_siblings() {
        let json = br#"{"verified":false,"bitwise_parity":false,"verdict":"diverged",
            "comparison":{"strictness":"canonical","compare_logs":true,"record_envelope":"all_records_v1"},
            "compared_log_messages":{"left":180,"right":180},
            "first_divergent_record":3}"#;
        let report = VerificationReport::from_json_slice(json).expect("report parses");
        assert_eq!(report.first_divergent_record, Some(3));
        assert_eq!(report.first_divergent_scheduler_turn, None);
        assert_eq!(report.first_divergent_virtual_nanoseconds, None);
        assert_eq!(report.first_divergent_left_message, None);
        assert_eq!(report.first_divergent_right_message, None);
        assert_eq!(report.first_divergent_syscall, None);
    }

    /// An EARLIER divergence must report a SMALLER value in both units. This is
    /// the ordering the whole metric rests on: a fix that moves the divergence
    /// later has to be visible as a larger number, and a regression as a
    /// smaller one. Both figures below were measured with `hermit log-diff
    /// --json` against one real 131-line INFO log, diverged at two different
    /// depths -- after COMMIT turn 4 and after COMMIT turn 1.
    #[test]
    fn an_earlier_divergence_reports_a_smaller_position() {
        let parse = |turn: u64, nanos: u64| {
            let json = format!(
                r#"{{"verified":false,"bitwise_parity":false,"verdict":"diverged",
                    "comparison":{{"strictness":"canonical","compare_logs":true,"record_envelope":"all_records_v1"}},"compared_log_messages":{{"left":180,"right":180}},
                    "first_divergent_scheduler_turn":{turn},
                    "first_divergent_virtual_nanoseconds":{nanos}}}"#
            );
            VerificationReport::from_json_slice(json.as_bytes()).expect("report parses")
        };
        let late = parse(4, 1_767_225_600_002_825_515);
        let early = parse(1, 1_767_225_600_000_500_000);
        assert!(
            early.first_divergent_scheduler_turn < late.first_divergent_scheduler_turn,
            "an earlier divergence must order before a later one in scheduler turns"
        );
        assert!(
            early.first_divergent_virtual_nanoseconds < late.first_divergent_virtual_nanoseconds,
            "and in virtual nanoseconds"
        );
    }

    /// A report written before the field existed must still parse. Requiring it
    /// would reclassify every retained pre-field report as an unreadable-report
    /// infrastructure fault.
    #[test]
    fn a_report_without_the_divergence_position_still_parses() {
        let json = br#"{"verified":true,"bitwise_parity":true,"verdict":"matched",
            "comparison":{"strictness":"canonical","compare_logs":true,"record_envelope":"all_records_v1"},"compared_log_messages":{"left":180,"right":180}}"#;
        let report = VerificationReport::from_json_slice(json);
        let report = report.expect("a pre-field report is not malformed");
        assert_eq!(report.first_divergent_scheduler_turn, None);
        assert_eq!(report.first_divergent_virtual_nanoseconds, None);
    }

    #[test]
    fn runtime_totals_survive_the_typed_report_parse() {
        let json = br#"{"verified":true,"bitwise_parity":true,"verdict":"matched",
            "comparison":{"strictness":"canonical","compare_logs":true,"record_envelope":"all_records_v1"},"compared_log_messages":{"left":180,"right":180},
            "runtime":{"run1":{"scheduler_turns":12,"virtual_nanoseconds":34,"syscalls":5},
                       "run2":{"scheduler_turns":13,"virtual_nanoseconds":35,"syscalls":6}}}"#;
        let report = VerificationReport::from_json_slice(json).expect("runtime report parses");
        let runtime = report.runtime.expect("runtime retained");
        assert_eq!(runtime.run1.expect("run1").syscalls, Some(5));
        assert_eq!(runtime.run2.expect("run2").scheduler_turns, 13);
    }

    fn report(
        strictness: LogCompareStrictness,
        compare_logs: bool,
        left: u64,
        right: u64,
    ) -> VerificationReport {
        VerificationReport {
            verified: true,
            bitwise_parity: true,
            verdict: Verdict::Matched,
            no_result_reason: None,
            infrastructure_error: None,
            comparison: Some(ComparisonReport {
                strictness,
                display_name: None,
                compare_logs,
                compare_io_buffers: None,
                log_scope: None,
                record_envelope: RecordEnvelopeReport::AllRecordsV1,
                virtualize_time: None,
                strip_lines: None,
                canonicalize_addresses: None,
                full_trace: None,
                exact_remainder: None,
                stripped_prefixes: None,
                canonicalizations: None,
                ignore_lines: None,
                skip_commit: None,
                skip_detlog: None,
            }),
            compared_log_messages: Some(ComparedLogMessages { left, right }),
            compared_outputs: None,
            dbt_counted_branches: None,
            runtime: None,
            guest_exit_code: None,
            guest_signal: None,
            first_divergent_scheduler_turn: None,
            first_divergent_virtual_nanoseconds: None,
            first_divergent_record: None,
            first_divergent_syscall: None,
            first_divergent_left_message: None,
            first_divergent_right_message: None,
        }
    }

    #[test]
    fn brackets_every_canonical_match_requirement() {
        assert!(
            report(LogCompareStrictness::Canonical, true, 1, 1)
                .require_canonical_match()
                .is_ok()
        );
        let mut weak = report(LogCompareStrictness::Canonical, true, 1, 1);
        weak.verified = false;
        assert!(weak.require_canonical_match().is_err());
        let mut weak = report(LogCompareStrictness::Canonical, true, 1, 1);
        weak.verdict = Verdict::Diverged;
        assert!(weak.require_canonical_match().is_err());
        let mut weak = report(LogCompareStrictness::Canonical, true, 1, 1);
        weak.bitwise_parity = false;
        assert!(weak.require_canonical_match().is_err());
        assert!(
            report(LogCompareStrictness::Stripped, true, 1, 1)
                .require_canonical_match()
                .is_err()
        );
        assert!(
            report(LogCompareStrictness::Canonical, false, 1, 1)
                .require_canonical_match()
                .is_err()
        );
        assert!(
            report(LogCompareStrictness::Canonical, true, 0, 1)
                .require_canonical_match()
                .is_err()
        );
        let mut weak = report(LogCompareStrictness::Canonical, true, 1, 1);
        weak.comparison.as_mut().unwrap().record_envelope = RecordEnvelopeReport::CallerDefined;
        assert!(weak.require_canonical_match().is_err());
    }

    /// The exact bytes hermit writes for a run that reached no verdict, copied
    /// from a real capture rather than reconstructed. Before this was `Option`,
    /// parsing these failed with "invalid type: null, expected struct
    /// ComparisonReport at line 1 column 80" and the cell was scored ERROR
    /// "verification report is unreadable" -- an infrastructure fault where the
    /// truth was that the producer had recorded nothing.
    const REAL_NO_RESULT_REPORT: &str = concat!(
        r#"{"verified":false,"bitwise_parity":false,"verdict":"no_result","#,
        r#""comparison":null,"compared_log_messages":null,"guest_exit_code":null,"#,
        r#""guest_signal":null,"first_divergent_scheduler_turn":null,"#,
        r#""first_divergent_virtual_nanoseconds":null,"first_divergent_record":null,"#,
        r#""first_divergent_syscall":null}"#,
    );

    #[test]
    fn a_real_no_result_report_parses_instead_of_reading_as_unreadable() {
        let parsed = VerificationReport::from_json_slice(REAL_NO_RESULT_REPORT.as_bytes())
            .expect("a documented no-result report must parse");
        assert_eq!(parsed.verdict, Verdict::NoResult);
        assert!(parsed.comparison.is_none());
    }

    #[test]
    fn a_no_result_report_is_still_inadmissible_and_names_the_real_reason() {
        // Parsing it is NOT admitting it. The point of the change is that the
        // refusal now points at the producer that recorded nothing, instead of
        // claiming the report could not be read.
        let parsed = VerificationReport::from_json_slice(REAL_NO_RESULT_REPORT.as_bytes())
            .expect("a documented no-result report must parse");
        let refusal = parsed
            .require_canonical_comparison()
            .expect_err("a report with no comparison must never be admitted");
        assert!(
            refusal.contains("recorded no comparison at all"),
            "refusal must name the missing comparison, got: {refusal}"
        );
        assert!(
            refusal.contains("no_result"),
            "refusal must carry the verdict, got: {refusal}"
        );
        assert!(parsed.require_canonical_match().is_err());
    }

    #[test]
    fn a_missing_comparison_field_is_refused_rather_than_defaulting_to_none() {
        // serde would otherwise map an absent Option field to None, letting a
        // report that never mentioned a comparison read as a legitimate
        // no-result. Optional must not mean absent.
        let absent = r#"{"verified":false,"bitwise_parity":false,"verdict":"no_result","compared_log_messages":null}"#;
        assert!(VerificationReport::from_json_slice(absent.as_bytes()).is_err());
    }

    #[test]
    fn a_malformed_comparison_object_is_still_refused_at_parse() {
        // Optional must not mean lenient: a comparison that is present but the
        // wrong shape is still an unreadable report, not a silent None.
        let malformed = REAL_NO_RESULT_REPORT.replace(r#""comparison":null"#, r#""comparison":7"#);
        assert!(VerificationReport::from_json_slice(malformed.as_bytes()).is_err());
        let missing_field = REAL_NO_RESULT_REPORT.replace(
            r#""comparison":null"#,
            r#""comparison":{"compare_logs":true,"record_envelope":"all_records_v1"}"#,
        );
        assert!(VerificationReport::from_json_slice(missing_field.as_bytes()).is_err());
    }

    #[test]
    fn comparison_record_envelope_is_required_and_unknown_values_are_refused() {
        let missing = serde_json::json!({
            "verified": true,
            "bitwise_parity": true,
            "verdict": "matched",
            "infrastructure_error": null,
            "comparison": {"strictness": "canonical", "compare_logs": true},
            "compared_log_messages": {"left": 1, "right": 1}
        });
        let error = VerificationReport::from_json_value(missing)
            .expect_err("a comparison that never states its record envelope is not admissible")
            .to_string();
        // The runner surfaces this verbatim as "verification report is
        // unreadable: {error}". Refusing is only useful if the operator can
        // tell WHICH producer contract was unmet -- an old binary that predates
        // the field looks identical to a corrupt file unless the message names
        // it. Assert the naming rather than trusting serde to keep doing it.
        assert!(
            error.contains("record_envelope"),
            "the refusal must name the missing field so an operator can tell a producer that \
             predates the envelope from a corrupt report; got: {error}"
        );

        let unknown = serde_json::json!({
            "verified": true,
            "bitwise_parity": true,
            "verdict": "matched",
            "infrastructure_error": null,
            "comparison": {
                "strictness": "canonical",
                "compare_logs": true,
                "record_envelope": "unknown_v9"
            },
            "compared_log_messages": {"left": 1, "right": 1}
        });
        assert!(VerificationReport::from_json_value(unknown).is_err());
    }

    #[test]
    fn readable_object_with_unreadable_nested_predicate_is_refused() {
        let malformed = serde_json::json!({
            "verified": true,
            "bitwise_parity": true,
            "verdict": "matched",
            "comparison": null,
            "compared_log_messages": {"left": 1, "right": 1}
        });
        assert!(VerificationReport::from_json_value(malformed).is_err());
    }

    #[test]
    fn typed_no_result_reason_round_trips_and_unknown_values_are_refused() {
        let current = serde_json::to_value(VerificationReport::no_result()).unwrap();
        let parsed = VerificationReport::from_current_json_value(current.clone())
            .expect("the typed not-run reason must round-trip");
        assert_eq!(parsed.no_result_reason, Some(NoResultReason::NotRun));

        let mut rejected = VerificationReport::no_result();
        rejected.no_result_reason = Some(NoResultReason::FirstRunRejected {
            exit_code: Some(9),
            signal: None,
            stdout_bytes: 0,
            stderr_bytes: 0,
        });
        rejected.guest_exit_code = Some(9);
        let mut rejected_value = serde_json::to_value(&rejected).unwrap();
        for include_null in [false, true] {
            if include_null {
                rejected_value["compared_outputs"] = serde_json::Value::Null;
            } else {
                rejected_value
                    .as_object_mut()
                    .unwrap()
                    .remove("compared_outputs");
            }
            let parsed = VerificationReport::from_current_json_slice(
                &serde_json::to_vec(&rejected_value).unwrap(),
            )
            .expect("a first-run rejection has no comparison output evidence");
            assert_eq!(parsed, rejected);
        }
        let output = ComparedOutput {
            exit_code: Some(9),
            signal: None,
            stdout_sha256: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
                .into(),
            stdout_bytes: 0,
            stderr_sha256: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
                .into(),
            stderr_bytes: 0,
        };
        rejected.compared_outputs = Some(ComparedOutputs {
            left: output.clone(),
            right: output,
        });
        let error =
            VerificationReport::from_current_json_slice(&serde_json::to_vec(&rejected).unwrap())
                .expect_err("a first-run rejection cannot carry comparison output evidence");
        assert!(
            error.contains("no_result") && error.contains("compared_outputs"),
            "{error}"
        );

        let mut missing = current.clone();
        missing.as_object_mut().unwrap().remove("no_result_reason");
        let error = VerificationReport::from_current_json_value(missing)
            .expect_err("a current no-result must state the nullable reason field");
        assert!(error.contains("no_result_reason"), "{error}");

        let mut absent = current.clone();
        absent["no_result_reason"] = serde_json::Value::Null;
        let parsed = VerificationReport::from_current_json_value(absent)
            .expect("explicit null records that the producer has no exact cause");
        assert_eq!(parsed.no_result_reason, None);

        let mut comparator_refusal = current.clone();
        comparator_refusal["no_result_reason"] = serde_json::json!({
            "kind": "comparison_refused",
            "detail": "the first log was truncated"
        });
        let parsed = VerificationReport::from_current_json_value(comparator_refusal)
            .expect("a comparator refusal carries the producer's exact cause");
        assert_eq!(
            parsed.no_result_reason,
            Some(NoResultReason::ComparisonRefused {
                detail: "the first log was truncated".into()
            })
        );

        let mut unknown = current;
        unknown["no_result_reason"] = serde_json::json!({"kind": "never_ran"});
        let error = VerificationReport::from_current_json_value(unknown)
            .expect_err("an unknown no-result reason must be refused");
        assert!(
            error.contains("unknown variant"),
            "refusal must identify the unknown typed reason: {error}"
        );
    }

    #[test]
    fn current_comparison_requires_every_producer_field_by_name() {
        let mut current = serde_json::json!({
            "verified": true,
            "bitwise_parity": true,
            "verdict": "matched",
            "no_result_reason": null,
            "infrastructure_error": null,
            "comparison": {
                "strictness": "canonical",
                "display_name": "BitwiseInfoV1",
                "compare_logs": true,
                "compare_io_buffers": true,
                "log_scope": "info",
                "record_envelope": "all_records_v1",
                "virtualize_time": true,
                "strip_lines": false,
                "canonicalize_addresses": true,
                "full_trace": true,
                "exact_remainder": true,
                "stripped_prefixes": ["real-wall-clock-prefix/v1"],
                "canonicalizations": ["host-address-to-first-appearance-ordinal/v1"],
                "ignore_lines": false,
                "skip_commit": false,
                "skip_detlog": false
            },
            "compared_log_messages": {"left": 1, "right": 1},
            "compared_outputs": {
                "left": {
                    "exit_code": 0,
                    "signal": null,
                    "stdout_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                    "stdout_bytes": 4,
                    "stderr_sha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",
                    "stderr_bytes": 0
                },
                "right": {
                    "exit_code": 0,
                    "signal": null,
                    "stdout_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                    "stdout_bytes": 4,
                    "stderr_sha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",
                    "stderr_bytes": 0
                }
            },
            "guest_exit_code": 0,
            "guest_signal": null,
            "first_divergent_scheduler_turn": null,
            "first_divergent_virtual_nanoseconds": null,
            "first_divergent_record": null,
            "first_divergent_syscall": null,
            "first_divergent_left_message": null,
            "first_divergent_right_message": null
        });
        let parsed = VerificationReport::from_current_json_value(current.clone())
            .expect("the complete current producer shape must parse");
        let comparison = parsed.comparison.expect("matched report has comparison");
        assert_eq!(comparison.compare_io_buffers, Some(true));
        assert_eq!(comparison.log_scope, Some(ComparedLogScope::Info));
        assert_eq!(parsed.guest_exit_code, Some(0));
        let mut missing_outputs = current.clone();
        missing_outputs
            .as_object_mut()
            .unwrap()
            .remove("compared_outputs");
        let error = VerificationReport::from_current_json_value(missing_outputs)
            .expect_err("a completed current report must carry exact output evidence");
        assert!(error.contains("compared_outputs"), "{error}");
        let mut null_outputs = current.clone();
        null_outputs["compared_outputs"] = serde_json::Value::Null;
        let error = VerificationReport::from_current_json_value(null_outputs)
            .expect_err("null is not output evidence for a completed current report");
        assert!(error.contains("compared_outputs"), "{error}");
        current["comparison"]
            .as_object_mut()
            .unwrap()
            .remove("compare_io_buffers");
        let error = VerificationReport::from_current_json_value(current)
            .expect_err("current comparison missing a producer field must be refused");
        assert!(
            error.contains("compare_io_buffers"),
            "refusal must name the missing comparison field: {error}"
        );
    }

    #[test]
    fn current_raw_reports_reject_duplicates_and_preserve_required_fields() {
        let mut current = serde_json::json!({
            "verified": true,
            "bitwise_parity": true,
            "verdict": "matched",
            "no_result_reason": null,
            "infrastructure_error": null,
            "comparison": {
                "strictness": "canonical",
                "display_name": "BitwiseInfoV1",
                "compare_logs": true,
                "compare_io_buffers": true,
                "log_scope": "info",
                "record_envelope": "all_records_v1",
                "virtualize_time": true,
                "strip_lines": false,
                "canonicalize_addresses": true,
                "full_trace": true,
                "exact_remainder": true,
                "stripped_prefixes": ["real-wall-clock-prefix/v1"],
                "canonicalizations": ["host-address-to-first-appearance-ordinal/v1"],
                "ignore_lines": false,
                "skip_commit": false,
                "skip_detlog": false
            },
            "compared_log_messages": {"left": 1, "right": 1},
            "guest_exit_code": 0,
            "guest_signal": null,
            "first_divergent_scheduler_turn": null,
            "first_divergent_virtual_nanoseconds": null,
            "first_divergent_record": null,
            "first_divergent_syscall": null,
            "first_divergent_left_message": null,
            "first_divergent_right_message": null
        });
        let output = serde_json::json!({
            "exit_code": 0, "signal": null,
            "stdout_sha256": "a".repeat(64), "stdout_bytes": 0,
            "stderr_sha256": "b".repeat(64), "stderr_bytes": 0
        });
        current["compared_outputs"] = serde_json::json!({"left": output, "right": output});
        for mutation in [
            "unequal",
            "bad-digest",
            "two-dispositions",
            "wrong-disposition",
        ] {
            let mut bad = current.clone();
            match mutation {
                "unequal" => {
                    bad["compared_outputs"]["right"]["stdout_sha256"] = "c".repeat(64).into()
                }
                "bad-digest" => {
                    for side in ["left", "right"] {
                        bad["compared_outputs"][side]["stdout_sha256"] = "invalid".into();
                    }
                }
                "two-dispositions" => {
                    for side in ["left", "right"] {
                        bad["compared_outputs"][side]["signal"] = 9.into();
                    }
                }
                "wrong-disposition" => bad["guest_exit_code"] = 7.into(),
                _ => unreachable!(),
            }
            let bytes = serde_json::to_vec(&bad).unwrap();
            assert!(
                VerificationReport::from_current_json_slice(&bytes).is_err(),
                "{mutation}"
            );
            assert!(
                VerificationReport::from_retained_cell_json_slice(&bytes).is_err(),
                "{mutation}"
            );
            assert!(
                VerificationReport::from_json_slice(&bytes)
                    .unwrap()
                    .require_canonical_match()
                    .is_err(),
                "{mutation}"
            );
        }
        let mut historical = current.clone();
        historical
            .as_object_mut()
            .unwrap()
            .remove("compared_outputs");
        let bytes = serde_json::to_vec(&historical).unwrap();
        VerificationReport::from_retained_cell_json_slice(&bytes)
            .unwrap()
            .require_canonical_match()
            .unwrap();
        assert!(VerificationReport::from_current_json_slice(&bytes).is_err());
        let mut diverged = current.clone();
        diverged["verdict"] = "diverged".into();
        diverged["verified"] = false.into();
        diverged["bitwise_parity"] = false.into();
        diverged["compared_outputs"]["right"]["stdout_sha256"] = "c".repeat(64).into();
        VerificationReport::from_current_json_value(diverged).unwrap();
        let mut relaxed = current.clone();
        relaxed["comparison"]["strictness"] = "stripped".into();
        relaxed["bitwise_parity"] = false.into();
        VerificationReport::from_current_json_value(relaxed).unwrap();
        let raw = serde_json::to_string(&current).unwrap();
        VerificationReport::from_current_json_slice(raw.as_bytes())
            .unwrap()
            .require_canonical_match()
            .unwrap();
        for (needle, replacement) in [
            (r#""verified":true"#, r#""verified":false,"verified":true"#),
            (r#""verified":true"#, r#""verified":true,"verified":true"#),
            (
                r#""no_result_reason":null"#,
                r#""no_result_reason":{"kind":"not_run"},"no_result_reason":null"#,
            ),
            (
                r#""no_result_reason":null"#,
                r#""no_result_reason":null,"no_result_reason":null"#,
            ),
            (r#""left":1"#, r#""left":0,"left":1"#),
            (r#""left":1"#, r#""left":1,"left":1"#),
        ] {
            assert_eq!(raw.matches(needle).count(), 1);
            let duplicated = raw.replacen(needle, replacement, 1);
            let collapsed: serde_json::Value = serde_json::from_str(&duplicated).unwrap();
            assert_eq!(
                collapsed, current,
                "the last-value map loses this contradiction"
            );
            let error =
                VerificationReport::from_current_json_slice(duplicated.as_bytes()).unwrap_err();
            assert!(error.contains("duplicate field"), "{replacement}: {error}");
        }
        for field in ["no_result_reason", "guest_signal"] {
            let mut missing = current.clone();
            missing.as_object_mut().unwrap().remove(field);
            let error =
                VerificationReport::from_current_json_slice(&serde_json::to_vec(&missing).unwrap())
                    .unwrap_err();
            assert!(error.contains(field), "{error}");
        }
        let mut missing = current;
        missing["comparison"]
            .as_object_mut()
            .unwrap()
            .remove("compare_io_buffers");
        assert!(
            VerificationReport::from_current_json_slice(&serde_json::to_vec(&missing).unwrap())
                .unwrap_err()
                .contains("compare_io_buffers")
        );
        let mut refused = serde_json::to_value(VerificationReport::no_result()).unwrap();
        refused["no_result_reason"] = serde_json::json!({"kind":"comparison_refused","detail":"the second log was truncated"});
        VerificationReport::from_current_json_slice(&serde_json::to_vec(&refused).unwrap())
            .unwrap();
        refused["no_result_reason"]["detail"] = serde_json::json!("");
        assert!(
            VerificationReport::from_current_json_slice(&serde_json::to_vec(&refused).unwrap())
                .unwrap_err()
                .contains("detail")
        );
    }

    #[test]
    fn unknown_verdict_is_refused_by_the_shared_type() {
        let unknown = serde_json::json!({
            "verified": false,
            "bitwise_parity": false,
            "verdict": "partly_matched",
            "comparison": null,
            "compared_log_messages": null
        });
        let error = VerificationReport::from_json_value(unknown)
            .expect_err("an unknown verdict must not become a product failure");
        assert!(
            error.contains("unknown variant"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn infrastructure_error_is_distinct_from_no_result_and_requires_a_positive_count() {
        let mut report =
            serde_json::to_value(report(LogCompareStrictness::Canonical, true, 1, 1)).unwrap();
        report["verified"] = serde_json::json!(false);
        report["bitwise_parity"] = serde_json::json!(false);
        report["verdict"] = serde_json::json!("infrastructure_error");
        report["infrastructure_error"] = serde_json::json!({"kind": "skid_overshoot", "count": 2});

        let parsed = VerificationReport::from_json_value(report.clone()).unwrap();
        assert_eq!(parsed.verdict, Verdict::InfrastructureError);
        assert_eq!(
            parsed.infrastructure_error,
            Some(InfrastructureError::SkidOvershoot { count: 2 })
        );
        assert!(parsed.comparison.is_some());

        report["infrastructure_error"]["count"] = serde_json::json!(0);
        let error = VerificationReport::from_json_value(report)
            .expect_err("zero cannot describe an observed skid overshoot");
        assert!(error.contains("count must be positive"), "{error}");
    }
}