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
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
//! Independent JSON contracts for mutation testing.
//!
//! A mutation report never contains source text, so a report can leave the
//! machine without the code of the project. A mutant is identified by its id, file, position and operator.
//! The `change` of a mutant uses a fixed vocabulary of operator tokens,
//! literals and placeholders, never project text.
//! The `inspect` command shows the code of one mutant.
use fallow_types::envelope::{ElapsedMs, ToolVersion};
use serde::{Deserialize, Serialize};
use crate::audit_test_reach::TestReachClass;
use crate::gate_outcomes::GateOutcomes;
pub use crate::mutation_plan_runner::MutationPlanRunner;
use crate::mutation_replay::{
MutantWitness, MutationRecordingOutput, MutationReplayOutput, MutationTaskWitness,
};
use crate::root_envelopes::serialize_named_json_output;
/// Current mutation report schema version.
pub const MUTATION_SCHEMA_VERSION: u32 = 2;
/// Current mutation plan schema version.
pub const MUTATION_PLAN_SCHEMA_VERSION: u32 = 1;
/// Current mutation inspect schema version.
pub const MUTATION_INSPECT_SCHEMA_VERSION: u32 = 2;
/// Current mutation tasks schema version.
pub const MUTATION_TASKS_SCHEMA_VERSION: u32 = 1;
/// The code of the run issue for tests that share a test id in the dry run.
pub const DUPLICATE_TEST_IDS_CODE: &str = "duplicate-test-ids";
/// The code of the run issue for tests that the dry run skipped or marked as
/// todo, in a test file of the plan. Such a test checks nothing.
pub const SKIPPED_TESTS_CODE: &str = "skipped-tests";
/// Version singleton for a mutation report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum MutationSchemaVersion {
/// Adds complete kill matrix evidence.
#[serde(rename = "2")]
V2,
}
/// Version singleton for a mutation plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum MutationPlanSchemaVersion {
/// Initial independent contract.
#[serde(rename = "1")]
V1,
}
/// The result of one mutant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MutantStatus {
/// A covering test failed.
Killed,
/// The run passed its timeout. A retry in a new companion with twice the
/// time also timed out, when the time budget allowed the retry. The
/// mutant counts as detected.
Timeout,
/// Each covering test passed, also in a retry in a new companion when
/// the time budget allowed the retry.
Survived,
/// No test reaches the mutant.
NoCoverage,
/// The runner failed for a reason outside the tests.
RuntimeError,
/// The second run in a new companion changed whether the tests detect
/// the mutant.
Flaky,
/// A static rule removed the mutant.
Pruned,
/// The mutant did not run: the mutant limit or the time budget ended first.
Pending,
/// A verdict marks the mutant as equivalent to the original code: no
/// test can detect it.
Equivalent,
/// Each covering test passed, but the mutated file does not type-check.
/// Only a run with the type check of survivors gives this status. The
/// mutant does not count in the score.
CompileError,
/// Each covering `--kill-matrix-for` target test passed, and the
/// target-first mode ran no other test. It is a final status of that
/// mode, but it says nothing about the other tests: they can kill the
/// mutant or let it survive. The mode has no score.
NotKilledByTarget,
}
/// The `pending_reason` of a mutant that the `--mutants-per-line` limit left
/// out of the plan.
pub const SAMPLED_OUT_REASON: &str = "sampled-out";
/// The number of mutants for each status, and the mutation score.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationStatusCounts {
/// Each mutant.
pub total: usize,
/// Killed mutants.
pub killed: usize,
/// Mutants that passed their timeout.
pub timeout: usize,
/// Mutants that each covering test let pass.
pub survived: usize,
/// Mutants that no test reaches.
pub no_coverage: usize,
/// Mutants with a runner fault.
pub runtime_error: usize,
/// Mutants where the second run in a new companion changed whether the
/// tests detect the mutant.
pub flaky: usize,
/// Mutants that a static rule removed.
pub pruned: usize,
/// Mutants that did not run.
pub pending: usize,
/// Mutants that a verdict marks as equivalent.
pub equivalent: usize,
/// Survived mutants that do not type-check. A report from a version
/// before `--typecheck` has no such field, so it reads as 0.
#[serde(default)]
pub compile_error: usize,
/// Mutants that no target test kills in the target-first mode of
/// `--kill-matrix-for`. A report from a version before this mode has no
/// such field, so it reads as 0.
#[serde(default)]
pub not_killed_by_target: usize,
}
impl MutationStatusCounts {
/// The mutants that ran against the tests: `killed`, `timeout`,
/// `survived`, `runtime_error`, `flaky`, `compile_error` and
/// `not_killed_by_target`.
#[must_use]
pub const fn executed(&self) -> usize {
self.killed
.saturating_add(self.timeout)
.saturating_add(self.survived)
.saturating_add(self.runtime_error)
.saturating_add(self.flaky)
.saturating_add(self.compile_error)
.saturating_add(self.not_killed_by_target)
}
/// Adds one mutant with `status`.
pub const fn add(&mut self, status: MutantStatus) {
self.total += 1;
match status {
MutantStatus::Killed => self.killed += 1,
MutantStatus::Timeout => self.timeout += 1,
MutantStatus::Survived => self.survived += 1,
MutantStatus::NoCoverage => self.no_coverage += 1,
MutantStatus::RuntimeError => self.runtime_error += 1,
MutantStatus::Flaky => self.flaky += 1,
MutantStatus::Pruned => self.pruned += 1,
MutantStatus::Pending => self.pending += 1,
MutantStatus::Equivalent => self.equivalent += 1,
MutantStatus::CompileError => self.compile_error += 1,
MutantStatus::NotKilledByTarget => self.not_killed_by_target += 1,
}
}
/// Removes one mutant with `status`. The count never goes below zero.
pub const fn remove(&mut self, status: MutantStatus) {
let count = match status {
MutantStatus::Killed => &mut self.killed,
MutantStatus::Timeout => &mut self.timeout,
MutantStatus::Survived => &mut self.survived,
MutantStatus::NoCoverage => &mut self.no_coverage,
MutantStatus::RuntimeError => &mut self.runtime_error,
MutantStatus::Flaky => &mut self.flaky,
MutantStatus::Pruned => &mut self.pruned,
MutantStatus::Pending => &mut self.pending,
MutantStatus::Equivalent => &mut self.equivalent,
MutantStatus::CompileError => &mut self.compile_error,
MutantStatus::NotKilledByTarget => &mut self.not_killed_by_target,
};
if *count > 0 {
*count -= 1;
self.total -= 1;
}
}
/// The mutation score over the executed mutants: `(killed + timeout) /
/// (killed + timeout + survived)`, from 0 to 1. `None` when no mutant
/// ran to a tested result.
///
/// `no_coverage` mutants stay out of the score;
/// [`MutationSummary::coverage`] reports them. Runtime errors, flaky, pruned,
/// pending, equivalent, compile-error and not-killed-by-target mutants
/// never count.
#[must_use]
#[expect(
clippy::cast_precision_loss,
reason = "mutant counts are far below 2^52"
)]
pub fn score(&self) -> Option<f64> {
let detected = self.killed.saturating_add(self.timeout);
let executed = detected.saturating_add(self.survived);
(executed > 0).then(|| detected as f64 / executed as f64)
}
}
/// Whether the result is conclusive.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MutationCompletionStatus {
/// Each planned mutant has a final status. `not_killed_by_target` is a
/// final status of the target-first mode. An empty survivor list is
/// conclusive.
Complete,
/// At least one planned mutant has no final status.
Partial,
}
/// Why a run is partial.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum MutationIncompleteReason {
/// At least one mutant has the status `runtime_error`.
RuntimeError,
/// The mutant limit left covered mutants `pending`.
MutantLimit,
/// The `--mutants-per-line` limit left mutants out of the plan. They are
/// `pending` with the reason `sampled-out`.
SampledOut,
/// The time budget ended before each mutant ran.
TimeBudget,
/// The plan did not instrument at least one selected file.
SkippedFiles,
/// The runner never loaded at least one instrumented file that has a
/// planned mutant and a static test file.
UnloadedFiles,
/// The runner does not list at least one static test file, so its tests
/// never ran. A mutant that only such a file reaches is `no_coverage` or
/// `survived` without proof. The `errors` entry
/// `test-files-not-discovered` names the files.
TestFilesNotDiscovered,
/// A test or a test file failed before any mutant was active.
BaselineFailure,
/// The run changed the git worktree.
WorktreeChanged,
/// The type check of the survivors failed, so a survivor can be a
/// mutant that does not type-check.
TypecheckFailed,
/// The end-of-run worktree check failed, so stray writes are unknown.
WorktreeUnchecked,
}
/// The completion status of a run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationCompletion {
/// `complete` or `partial`.
pub status: MutationCompletionStatus,
/// Why the run is partial, sorted. Empty for a complete run.
pub reasons: Vec<MutationIncompleteReason>,
}
impl MutationCompletion {
/// A completion with `reasons`. The status is `complete` only when the
/// list is empty.
#[must_use]
pub fn from_reasons(mut reasons: Vec<MutationIncompleteReason>) -> Self {
reasons.sort_unstable();
reasons.dedup();
let status = if reasons.is_empty() {
MutationCompletionStatus::Complete
} else {
MutationCompletionStatus::Partial
};
Self { status, reasons }
}
}
/// Which code a run mutates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MutationScopeKind {
/// The added lines against a base ref.
Changed,
/// Each source file of the project.
All,
/// The files at the given paths.
Paths,
}
/// The scope of a plan or a run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationScopeOutput {
/// The kind of scope.
pub kind: MutationScopeKind,
/// The base ref of a `changed` scope.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base_ref: Option<String>,
}
/// The JavaScript runtime that ran the companion.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationRuntimeOutput {
/// `node` or `bun`.
pub name: String,
/// The version that the runtime reports.
pub version: String,
}
/// The test runner of a run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationRunnerOutput {
/// The runner name, for example `vitest`.
pub name: String,
/// The runner version from the project.
pub version: String,
/// The wire protocol version of the companion.
pub protocol_version: u32,
/// The runtime of the mutation runner.
pub runtime: MutationRuntimeOutput,
/// The number of mutation runner processes that ran mutants.
pub concurrency: usize,
/// Facts of the runner setup that limit the result, kebab-case.
/// `typecheck-not-run`: the project config enables the Vitest type-check
/// pass, and the run did not execute it, so a type-level kill is not
/// counted. Absent when the runner states no fact.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
}
/// The source position of a mutant. No source text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutantLocation {
/// The stable mutant id.
pub mutant_id: String,
/// The root-relative path, with forward slashes.
pub file: String,
/// The 1-based line.
pub line: u32,
/// The 1-based column.
pub column: u32,
/// The byte span in the original file.
pub span: (u32, u32),
/// The operator name, kebab-case.
pub operator: String,
/// The name of the enclosing function.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub function: Option<String>,
/// The 1-based first line of the enclosing function.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub function_line: Option<u32>,
/// The 1-based execution rank of a planned mutant.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rank: Option<u32>,
/// The edit of the mutant, without project text. Absent in a report
/// that an older version wrote.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub change: Option<MutantChange>,
}
/// The edit of a mutant, without project text.
///
/// Each side is an operator token (for example `??` or `<=`), a fixed literal
/// (`true`, `undefined`, `""`, `"fallow"`, `void 0`), a regular expression
/// token (`^`, `$`, `[`, `[^`, `+`, `{n,m}`, `\d`), or a placeholder for a
/// side that is project code: `<condition>`, `<call>`, `<expression>`,
/// `<string>`, `<template>`, `<statement>`, `<statements>`, `<array>` or
/// `<object>`. An
/// empty side means that the edit removes the token.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutantChange {
/// The token or placeholder before the edit.
pub from: String,
/// The token or placeholder after the edit.
pub to: String,
}
/// One mutant of a run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutantResult {
/// The mutant and its position.
#[serde(flatten)]
pub location: MutantLocation,
/// The final status.
pub status: MutantStatus,
/// The static rule of a `pruned` mutant, kebab-case.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prune_reason: Option<String>,
/// Why a `pending` mutant did not run, kebab-case. Only `sampled-out` has
/// a reason: the `--mutants-per-line` limit left the mutant out of the
/// plan. A mutant that the mutant limit or the time budget left out has
/// no reason.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pending_reason: Option<String>,
/// The test that killed the mutant in this run. Absent for a kill by an
/// error outside a test.
///
/// This is evidence of one run, not a stable fact. A normal run stops at
/// the first failing test. A kill matrix run retains each failing test
/// in `killing_tests`. Tests run in measured fastest-first order, so a
/// second run on the same code can name another first killer. No
/// fingerprint or baseline comparison uses this field.
///
/// The retry of a survivor also runs the other tests of its test files,
/// so this test can be absent from `covering_tests`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub killed_by: Option<String>,
/// All observed failing tests, sorted. Timeouts do not count. Empty
/// outside `--kill-matrix`; `killed_by` keeps the first killer.
pub killing_tests: Vec<String>,
/// True only for exact requested membership with terminal pass or fail results.
pub kill_matrix_complete: bool,
/// The tests that reached the mutant in the dry run, sorted by test id.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub covering_tests: Vec<String>,
/// True when the mutant runs while a module loads, outside each test.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub static_mutant: bool,
/// The duration of one run in milliseconds. A `killed` mutant after a
/// retry reports the retry. Each other status reports the first run.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub duration_ms: Option<u64>,
/// How tests reach the code of the mutant in the module graph. Only a
/// `no_coverage` mutant has this field.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub test_reach: Option<MutantTestReach>,
/// True when the status comes from a first run and a retry in a new
/// companion. A `survived` or `timeout` mutant without this field got no
/// retry, because the time budget ended first.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub retried: bool,
/// The runs that gave the status of a `retried` mutant: the first run,
/// then the retry. Absent when the mutant got no retry, and absent for a
/// `cached` mutant. Each duration is evidence of one run, so no
/// fingerprint or baseline comparison uses this field.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attempts: Vec<MutantAttempt>,
/// True when the status comes from the result cache of an earlier run.
/// The mutant did not run in this run. `--no-cache` runs each mutant.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub cached: bool,
/// True when the status comes from the journal of an interrupted run
/// (`--resume`). The mutant did not run in this run.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub resumed: bool,
/// True when the status and its evidence come from the earlier report
/// of a `--recheck` run: the recheck did not select the mutant, its file
/// has the digest of that report, and each test file of its killing
/// tests exists. The mutant did not run in this run, and the kill matrix
/// of this run has no evidence of it.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub carried: bool,
/// The TypeScript diagnostic codes of the new errors of a
/// `compile_error` mutant, sorted, at most 8.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub type_error_codes: Vec<u32>,
/// An advisory hint that the mutant may be equivalent to the original
/// code. The hint never changes the status: the mutant stays `survived`
/// and counts in the score. A person decides, and records the decision in
/// a verdict file. The hint can be wrong.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub equivalence_hint: Option<MutantEquivalenceHint>,
/// The replay of a recorded input. Present only after a `--record-args
/// values` run, for a survived or uncovered mutant with a recorded input
/// of its export.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub witness: Option<MutantWitness>,
}
/// Why a survivor may be equivalent: a fact of the type check or of the
/// call evidence. The hint is advisory and never changes the status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum MutantEquivalenceHint {
/// The mutant removes an optional-chaining link (`?.`) or a nullish
/// fallback (`a ?? b` to `a`), and the declared type of the receiver
/// excludes `null` and `undefined`. If no run-time
/// value can be nullish, the mutant is equivalent. A run-time value can
/// still be nullish, for example in a method that loses its `this`, or
/// in a call whose declared return type hides a nullish value.
TypeNonNullish,
/// The mutant sets a branch or loop test to a constant. The test reads a
/// parameter, each visible call of the function passes the same literal
/// for it, and the literal gives the test the same constant. The
/// call evidence and the closed-world gate of the `constant-parameter`
/// rule prove the calls. A caller outside the project can still pass
/// another value.
ConstantParameter,
}
/// One run of a retried mutant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutantAttempt {
/// The status of this run alone.
pub status: MutantStatus,
/// The duration of this run in milliseconds. A watchdog timeout reports
/// the wait of the watchdog.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub duration_ms: Option<u64>,
/// The test that killed the mutant in this run.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub killed_by: Option<String>,
/// All observed failing tests, sorted. Timeouts do not count. Empty
/// outside `--kill-matrix`; `killed_by` keeps the first killer.
pub killing_tests: Vec<String>,
/// True only for exact requested membership with terminal pass or fail results.
pub kill_matrix_complete: bool,
/// How the run detected the mutant. Absent for a run that did not detect
/// it, and absent when the runner did not state the kind.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failure_kind: Option<MutantFailureKind>,
/// The first line of the reason of a `runtime_error` run.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
}
/// How a run detected a mutant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MutantFailureKind {
/// A test assertion failed.
Assertion,
/// A test or the module load threw an error that is not an assertion.
Error,
/// A test or the run passed its time limit.
Timeout,
}
impl MutantFailureKind {
/// The kind of a `failure_kind` value of the companion protocol. An
/// unknown value gives `None`.
#[must_use]
pub fn from_wire(value: &str) -> Option<Self> {
match value {
"assertion" => Some(Self::Assertion),
"error" => Some(Self::Error),
"timeout" => Some(Self::Timeout),
_ => None,
}
}
}
/// How tests reach the code of one mutant in the module graph. The class
/// gives a static reason why no test covers the mutant.
///
/// A mutant in the top-level statement that declares a value export gets the
/// class of that export. A mutant outside each such statement gets the class
/// of its file: `none-file` when no test loads the file, `mocked-only` when no
/// test loads the file and a mock explains an export of the file, and `none`
/// when a test loads the file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutantTestReach {
/// The reach class. The same open set as the test reach of `audit`.
pub reach: TestReachClass,
/// The export whose declaration holds the mutant. Absent for a mutant
/// outside each value export declaration.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub export_name: Option<String>,
/// For `mocked-only`: the test files whose references a mock removed,
/// sorted.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tests: Vec<String>,
/// For `mocked-only`: the mocked modules on the reference paths, sorted.
/// A mocked module can be a barrel in front of the file of the mutant.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mocked_targets: Vec<String>,
}
/// The result cache facts of a run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationCacheOutput {
/// The mutants whose status came from the cache. They did not run.
pub hits: usize,
/// The results that this run added to the cache.
pub stored: usize,
/// The test inputs that the cache key does not cover: modules that a
/// test loads through a dynamic import that the module graph does not
/// resolve (`dynamic-imports`), and files that a test reads
/// (`file-reads`). A change to them does not invalidate a cached result.
pub not_keyed: Vec<String>,
}
/// The resume facts of a `--resume` run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationResumeOutput {
/// The path of the outcome journal, relative to the project root. When
/// the cache directory is outside the root, the path is absolute: the
/// report has no other cache path, so no other rule applies. The file
/// stays only when the run did not complete. A run with
/// `completion.status: complete` removes it.
pub journal: String,
/// The mutants whose status came from the journal. They did not run.
pub reused: usize,
/// The journal results whose key does not match this run, because an
/// input of the mutant changed. These results were not reused from the
/// journal. The mutant ran again, or its status came from the result
/// cache.
pub rejected: usize,
/// Why the run did not read a journal and started from the beginning,
/// for example because no journal exists. Absent when the run read the
/// journal.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
/// The results of the mutants of one function.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationFunctionResult {
/// The root-relative path, with forward slashes.
pub file: String,
/// The function name. `null` for code outside each function, and for an
/// anonymous function.
pub name: Option<String>,
/// The 1-based first line. `null` for code outside each function.
pub line: Option<u32>,
/// The 1-based last line. `null` for code outside each function.
pub end_line: Option<u32>,
/// True when an added line of the diff is in the function.
pub in_diff: bool,
/// The cyclomatic complexity, when the analysis measured the function.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cyclomatic: Option<u16>,
/// The number of mutants for each status.
pub counts: MutationStatusCounts,
/// The mutation score of the function. `null` in the target-first mode
/// of `--kill-matrix-for`.
pub score: Option<f64>,
/// The ids of the survived mutants, in rank order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub survived: Vec<String>,
}
/// The totals of a run.
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationSummary {
/// The number of mutants for each status.
pub counts: MutationStatusCounts,
/// The mutation score over the executed mutants, a fraction from 0 to 1:
/// `(killed + timeout) / (killed + timeout + survived)`. `null` when no
/// mutant ran to a tested result, and in the target-first mode of
/// `--kill-matrix-for`, which has no survivors. `--min-score` and
/// `mutation.minScore` compare this value in percent.
pub score: Option<f64>,
/// The share of mutants that a test reaches, a fraction from 0 to 1:
/// `covered / (covered + no_coverage)` over the whole plan. `covered`
/// counts each executed mutant with a covering test and each `pending`
/// mutant that a passing dry-run test covers. A `pending` mutant that no
/// dry-run test covers is `no_coverage`, so a run that `--max-mutants`
/// caps reports the coverage of the full run. `equivalent` and `pruned`
/// mutants never count. `null` when no mutant is covered or unreached.
pub coverage: Option<f64>,
/// The `pending` mutants that the `--mutants-per-line` limit left out of
/// the plan. They are part of `counts.pending`.
pub sampled_out: usize,
}
impl MutationSummary {
/// The totals, the score and the coverage of `results`.
#[must_use]
pub fn from_results(results: &[MutantResult]) -> Self {
let mut counts = MutationStatusCounts::default();
let (mut covered, mut uncovered) = (0usize, 0usize);
let mut sampled_out = 0usize;
for result in results {
counts.add(result.status);
if result.status == MutantStatus::Pending
&& result.pending_reason.as_deref() == Some(SAMPLED_OUT_REASON)
{
sampled_out += 1;
}
match result.status {
MutantStatus::NoCoverage => uncovered += 1,
MutantStatus::Pending => covered += 1,
MutantStatus::Killed
| MutantStatus::Timeout
| MutantStatus::Survived
| MutantStatus::RuntimeError
| MutantStatus::Flaky
| MutantStatus::CompileError
| MutantStatus::NotKilledByTarget
if !result.covering_tests.is_empty() || result.static_mutant =>
{
covered += 1;
}
_ => {}
}
}
Self {
counts,
score: counts.score(),
coverage: ratio(covered, covered + uncovered),
sampled_out,
}
}
}
#[expect(
clippy::cast_precision_loss,
reason = "mutant counts are far below 2^52"
)]
fn ratio(part: usize, whole: usize) -> Option<f64> {
(whole > 0).then(|| part as f64 / whole as f64)
}
/// A test or a test file that failed with no active mutant. Its tests do not
/// decide a mutant status.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationBaselineFailure {
/// The test file, root-relative. `null` for an error outside each test
/// file.
pub file: Option<String>,
/// The test id, for a failed test.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub test_id: Option<String>,
/// The error message. For an error outside a test, the error. For a test
/// that failed in the first dry run, the first error of the test. For a
/// test that failed in a control run or in the dry run of a restarted
/// companion, the reason, then `: ` and the first error of the test. A
/// test error has its name and message on the first line and the stack
/// frames of the project after it. Absent for a test of the first dry
/// run when the companion sent no error.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
/// The mutants that ran without this test, because the test did not pass
/// in the dry run of a restarted companion. Each of them ran with its
/// other covering tests. Absent for a failure of the first dry run.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mutant_ids: Vec<String>,
}
/// A selected file that the plan did not instrument.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationSkippedFile {
/// The root-relative path, with forward slashes.
pub path: String,
/// Why the plan skipped the file, kebab-case.
pub reason: String,
}
/// A path of a `paths` scope that selects no file, with the reason.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationUnmatchedPath {
/// The path relative to the project root, with forward slashes. The
/// entry at the same index of `unmatched_paths` holds the path as given,
/// so match the two fields by index, not by value.
pub path: String,
/// Why the path selects no file, kebab-case: `not-found` (the path does
/// not exist), `ignored` (the ignore globs of the config exclude the
/// path or a file under it) or `no-source-file` (the path holds only
/// test code, declaration files or files outside the module graph).
pub reason: String,
}
/// The git worktree check of a run: a run refuses a dirty worktree unless
/// `--allow-dirty` is set, and it compares the worktree after the run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationWorktreeCheck {
/// False when the root is not in a git worktree, so no check ran.
pub checked: bool,
/// True when the caller allowed a dirty worktree.
pub allow_dirty: bool,
/// The paths that were dirty before the run, sorted.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dirty_at_start: Vec<String>,
/// The paths that the run changed, sorted. A non-empty list is an error.
pub changed_paths: Vec<String>,
}
/// An error of a run that did not stop the run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationRunIssue {
/// A stable kebab-case code: `cache-write-failed`,
/// `duplicate-test-ids`, `journal-write-failed`, `runtime-error`,
/// `skipped-tests`, `static-map-miss`, `test-files-not-discovered`,
/// `typecheck-failed`, `worktree-changed` or `worktree-check-failed`.
pub code: String,
/// A description.
pub message: String,
/// The mutant of the issue.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mutant_id: Option<String>,
/// The last part of the companion stderr.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stderr_tail: Option<String>,
}
/// The wall time of each phase, in milliseconds.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationTimings {
/// The analysis and the plan.
pub plan_ms: u64,
/// The companion install, the run directory, and the first `init`.
pub setup_ms: u64,
/// The dry run.
pub dry_run_ms: u64,
/// The mutant runs.
pub mutants_ms: u64,
/// The second runs of survived and timed-out mutants.
pub retry_ms: u64,
/// The type check of the survivors. Zero when the run did not check
/// them.
pub typecheck_ms: u64,
}
/// Why the type check did not check a survivor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum MutationTypecheckSkipReason {
/// No TypeScript project includes the file.
NoProject,
/// The checker does not check the file: a `// @ts-nocheck` comment, or a
/// JavaScript file without `checkJs`.
NotTypeChecked,
/// The file changed after the plan.
SourceChanged,
/// The file does not exist.
FileMissing,
/// The checker cannot read the file type: a Vue, Svelte or Astro
/// component file.
UnsupportedFile,
}
/// The number of survivors with one skip reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationTypecheckSkip {
/// Why the type check did not check these survivors.
pub reason: MutationTypecheckSkipReason,
/// The number of survivors.
pub count: usize,
}
/// The type check of the survivors (`--typecheck`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationTypecheckOutput {
/// True when the type check gave a result for each survivor that it
/// received. False when the companion failed; the survivors then keep
/// the status `survived`.
pub completed: bool,
/// The survivors that the type check received.
pub survivors: usize,
/// The survivors that the checker checked.
pub checked: usize,
/// The checked survivors that do not type-check. They have the status
/// `compile_error`.
pub compile_errors: usize,
/// The mutants of the final report that have the `type-non-nullish`
/// hint. They keep the status `survived`. A verdict that makes a mutant
/// `equivalent` removes its hint and lowers this count.
#[serde(default, skip_serializing_if = "is_zero")]
pub hinted: usize,
/// The survivors that the checker did not check, by reason.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub skipped: Vec<MutationTypecheckSkip>,
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde skip predicate signature"
)]
const fn is_zero(value: &usize) -> bool {
*value == 0
}
/// The quality of observed test-to-mutant evidence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MutationKillMatrixStatus {
/// Each eligible test has a terminal result for each covered mutant.
Complete,
/// At least one result is missing or inconclusive.
Incomplete,
/// The run did not request a kill matrix.
Unavailable,
}
/// The quality of the evidence of one `--kill-matrix-for` target.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MutationKillMatrixTargetStatus {
/// Each test of the target has complete evidence for each covered mutant.
Complete,
/// The run or at least one covered mutant has incomplete evidence.
Incomplete,
}
/// The observed mutant kills of one eligible test.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationTestKillRow {
/// The runner test id.
pub test_id: String,
/// The root-relative test file.
pub file: String,
/// The observed killed mutant ids, sorted.
pub kills: Vec<String>,
/// The mutant ids that no other eligible test kills, sorted.
pub unique_kills: Vec<String>,
/// The tests whose kill sets contain this full kill set, sorted. The
/// full matrix leaves out the duplicate test ids of the dry run, whose
/// kills can belong to a twin test.
pub subsuming_tests: Vec<String>,
/// Conservative evidence notes, sorted.
pub notes: Vec<String>,
/// The kills that other target tests also detect and no non-target test
/// detects, sorted by mutant id. Only `--kill-matrix-for` sets this
/// field. The test stays redundant only while one of `targets` for each
/// entry stays in the suite.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target_only_kills: Option<Vec<MutationTargetOnlyKill>>,
}
/// A kill of a target test that only other target tests share.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationTargetOnlyKill {
/// The killed mutant.
pub mutant_id: String,
/// The other target tests that also kill the mutant, sorted.
pub targets: Vec<String>,
}
/// One `--kill-matrix-for` target and the dry-run tests that it selects.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationKillMatrixTarget {
/// The target as the caller gave it, after path normalization: a test
/// file or a runner test id.
pub target: String,
/// The dry-run test ids that the target selects, sorted.
pub test_ids: Vec<String>,
/// Whether the evidence of this target supports candidate analysis:
/// `complete` or `incomplete`. Only the tests of a complete target can
/// be candidates.
pub status: MutationKillMatrixTargetStatus,
/// Why the evidence of this target is incomplete, sorted.
/// `baseline-failure` means that a test failed with no active mutant, and
/// that the failure can affect this target: the failing test is a test
/// of the target or is in a test file of the target, or it covers, kills,
/// or ran without a mutant that a test of the target covers or kills.
/// `partial-mutation-run` means that the run is partial. When baseline
/// failures are the only cause of a partial run, only the targets with
/// `baseline-failure` get it. Each other cause applies to each target,
/// and so does `missing-test-file-metadata`.
/// `incomplete-mutant-results` means that a test of this target covers a
/// mutant with incomplete evidence. `unmatched-target` means that the
/// target selects no test. With it, `not-a-test-file` means that the
/// runner does not list the file of the target as a test file, and
/// `no-planned-code` means that the file reaches no planned code, so
/// the dry run does not run it. A run stops only when no target selects
/// a test.
pub reasons: Vec<String>,
/// The baseline failures that give this target `baseline-failure`,
/// sorted: the test id, or the test file for an error outside a test.
/// Never serialized: the human output names them, and the JSON consumer
/// reads `baseline_failures` of the report.
#[serde(skip)]
#[cfg_attr(feature = "schema", schemars(skip))]
pub baseline_failures: Vec<String>,
}
/// Redundancy signals over the observed mutants. Candidates need review.
/// Removing candidates together can remove all tests for a mutant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationKillMatrix {
/// Whether the matrix supports candidate analysis.
pub status: MutationKillMatrixStatus,
/// Why evidence is unavailable or incomplete, sorted.
pub reasons: Vec<String>,
/// Each eligible test with observed coverage, sorted by test id.
pub tests: Vec<MutationTestKillRow>,
/// Tests with nonempty kills and no unique kills, sorted by test id.
/// In target mode, only the tests of complete targets. The full matrix
/// leaves out the duplicate test ids of the dry run.
pub candidates: Vec<String>,
/// Tests with coverage and no observed kills, sorted by test id. The full
/// matrix leaves out the duplicate test ids of the dry run.
pub coverage_without_kills: Vec<String>,
/// The `--kill-matrix-for` targets, in the given order. Absent outside
/// target mode. In target mode, `tests` has only target tests, and
/// `subsuming_tests` is empty, because bail hides the other killers.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub targets: Option<Vec<MutationKillMatrixTarget>>,
/// How the `--kill-matrix-for` run selected the tests of each mutant.
/// Absent outside target mode.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target_mode: Option<MutationKillMatrixTargetMode>,
}
/// How a `--kill-matrix-for` run selects the tests of each mutant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum MutationKillMatrixTargetMode {
/// The target tests run first. A mutant that no target kills is
/// `not_killed_by_target` and runs no other test. After a target kill,
/// the other covering tests run until the first kill.
TargetFirst,
/// Each mutant runs its target tests and then its other covering tests,
/// and each survivor gets a retry (`--kill-matrix-full`).
Full,
}
impl MutationReport {
/// Removes the scores of a target-first `--kill-matrix-for` run. That
/// mode runs no other test after the target tests pass, so no mutant is
/// `survived`, and a score would always be 100%.
pub fn withhold_target_first_scores(&mut self) {
if self.kill_matrix.target_mode != Some(MutationKillMatrixTargetMode::TargetFirst) {
return;
}
self.summary.score = None;
for function in &mut self.functions {
function.score = None;
}
}
}
impl Default for MutationKillMatrix {
fn default() -> Self {
Self {
status: MutationKillMatrixStatus::Unavailable,
reasons: vec!["kill-matrix-disabled".to_owned()],
tests: Vec::new(),
candidates: Vec::new(),
coverage_without_kills: Vec::new(),
targets: None,
target_mode: None,
}
}
}
/// The envelope of `fallow mutation`.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationReport {
/// Independent schema version.
pub schema_version: MutationSchemaVersion,
/// The Fallow version.
pub version: ToolVersion,
/// The total wall time.
pub elapsed_ms: ElapsedMs,
/// Whether the result is conclusive.
pub completion: MutationCompletion,
/// The observed kill matrix and candidate review signals.
pub kill_matrix: MutationKillMatrix,
/// The mutated code.
pub scope: MutationScopeOutput,
/// The runner. Absent when no companion started, for example when no
/// test file reaches a mutant.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runner: Option<MutationRunnerOutput>,
/// The result cache. Absent with `--no-cache`, and when no companion
/// started.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache: Option<MutationCacheOutput>,
/// The resume facts. Absent without `--resume`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resume: Option<MutationResumeOutput>,
/// The totals.
pub summary: MutationSummary,
/// Each mutant, ranked mutants first.
pub mutants: Vec<MutantResult>,
/// The results per enclosing function, by file and line.
pub functions: Vec<MutationFunctionResult>,
/// True when the project has no test files.
pub no_test_files: bool,
/// The tests and test files that failed with no active mutant.
pub baseline_failures: Vec<MutationBaselineFailure>,
/// The selected files that the plan did not instrument.
pub skipped_files: Vec<MutationSkippedFile>,
/// The paths of a `paths` scope that select no file.
pub unmatched_paths: Vec<String>,
/// The reason for each entry of `unmatched_paths`, at the same index.
/// Each path is relative to the project root. Absent when
/// `unmatched_paths` is empty.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub unmatched_path_reasons: Vec<MutationUnmatchedPath>,
/// The instrumented files that the runner never loaded.
pub unloaded_paths: Vec<String>,
/// The git worktree check.
pub worktree: MutationWorktreeCheck,
/// The errors that did not stop the run.
pub errors: Vec<MutationRunIssue>,
/// The wall time of each phase.
pub timings: MutationTimings,
/// The mutated files with their SHA-256 digest at plan time, sorted by
/// path. `fallow mutation inspect` compares the digest with the current
/// file.
pub files: Vec<MutationPlanFile>,
/// The join with a verdict document. Absent when the run read no verdict
/// document (`--verdicts` not set).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub verdicts: Option<MutationVerdictJoin>,
/// The type check of the survivors. Absent when the run did not check
/// them (`--typecheck` not set).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub typecheck: Option<MutationTypecheckOutput>,
/// The result of each rechecked mutant against its status in the earlier
/// report. Absent outside `--recheck`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recheck: Option<MutationRecheck>,
/// The mutants whose result differs from a saved report. Absent outside
/// `--compare`, and absent when this run is not complete.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compare: Option<MutationCompare>,
/// The verdict of the `mutation-min-score` gate. Present only when a
/// minimum applies: from `--min-score`, or from `mutation.minScore` when
/// the run is not a recheck. The exit code of the run reads this entry.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gate_outcomes: Option<GateOutcomes>,
/// The argument recording of the dry run. Present only with
/// `--record-args`. It holds counts and reasons, never argument values.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recording: Option<MutationRecordingOutput>,
/// The id of the outcome journal that this run wrote. A caller passes the
/// report to the journal removal, which removes only this journal. It is
/// not part of the JSON report.
#[serde(skip)]
#[cfg_attr(feature = "schema", schemars(skip))]
pub journal_run_id: Option<String>,
}
/// How one mutant of a compare differs from the saved report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MutationCompareChange {
/// The saved report detects the mutant (`killed` or `timeout`), and this
/// run does not (`survived` or `no_coverage`). The tests lost the
/// detection of the mutant.
Regressed,
/// The mutant is `flaky` in one of the two runs, so the comparison of
/// this mutant proves nothing.
Inconclusive,
/// Only this run has the mutant id.
Added,
/// Only the saved report has the mutant id.
Removed,
}
/// One mutant of a compare.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationCompareMutant {
/// The id of the mutant.
pub mutant_id: String,
/// The project-root-relative path of the mutated file.
pub file: String,
/// The 1-based line of the mutant.
pub line: u32,
/// How the mutant differs from the saved report.
pub change: MutationCompareChange,
/// The status in the saved report. Absent for an `added` mutant.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub previous_status: Option<MutantStatus>,
/// The status in this run. Absent for a `removed` mutant.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<MutantStatus>,
/// The tests that killed the mutant in the saved report, sorted: its
/// `killing_tests`, else its `killed_by`. Empty when the saved report
/// names no killing test.
pub previous_killing_tests: Vec<String>,
}
/// The compare facts of a `--compare` run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationCompare {
/// The SHA-256 digest of the saved report.
pub report_sha256: String,
/// The number of mutant ids in both runs.
pub compared: usize,
/// The number of mutants for each change.
pub regressed: usize,
/// See `regressed`.
pub inconclusive: usize,
/// See `regressed`.
pub added: usize,
/// See `regressed`.
pub removed: usize,
/// Each mutant with a change, sorted by file, line and mutant id. A
/// mutant in both runs without a change is not in the list.
pub mutants: Vec<MutationCompareMutant>,
}
/// What a recheck shows for one mutant of the earlier report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MutationRecheckOutcome {
/// A test now fails on the mutant (`killed` or `timeout`).
Killed,
/// Each covering test still passes on the mutant.
Survived,
/// No test reaches the mutant.
NoCoverage,
/// A test of the run fails on the original code, so the run proves no
/// survivor. Fix that test first.
TestsFailOnOriginal,
/// The mutant has no final result, for example `runtime_error`, `flaky`
/// or `pending`. `status` gives the reason.
Unsettled,
}
/// One rechecked mutant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationRecheckMutant {
/// The id of the mutant.
pub mutant_id: String,
/// The project-root-relative path of the mutated file.
pub file: String,
/// The 1-based line of the mutant.
pub line: u32,
/// The status in the earlier report.
pub previous_status: MutantStatus,
/// The status in this run.
pub status: MutantStatus,
/// What the recheck shows.
pub outcome: MutationRecheckOutcome,
}
/// The recheck facts of a `--recheck` run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationRecheck {
/// The SHA-256 digest of the earlier report.
pub report_sha256: String,
/// The number of mutants for each outcome.
pub killed: usize,
/// See `killed`.
pub survived: usize,
/// See `killed`.
pub no_coverage: usize,
/// See `killed`.
pub tests_fail_on_original: usize,
/// See `killed`.
pub unsettled: usize,
/// The rechecked mutants, sorted by file, line and mutant id.
pub mutants: Vec<MutationRecheckMutant>,
/// The mutants of the report that keep their result from the earlier
/// report (`carried`), because the recheck did not select them. The
/// summary counts them. The recheck does not run them again, so a test
/// that became weaker does not change their result.
#[serde(default)]
pub carried: usize,
/// The files of the earlier report outside this run whose earlier
/// results do not apply, sorted: the source changed after the report,
/// the test file of a killing test is gone, or the report has no digest
/// or no readable entry for the file. The report leaves out their
/// mutants. Run `fallow mutation` on them for new
/// results.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stale_files: Vec<String>,
}
/// Version singleton for a mutation verdict document.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum MutationVerdictSchemaVersion {
/// Initial independent contract.
#[serde(rename = "1")]
V1,
}
/// The judgment of a mutation verdict.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum MutationVerdictKind {
/// The mutant behaves the same as the original code, so no test can kill
/// it. It gets the status `equivalent` and leaves the score.
Equivalent,
}
/// One reviewed mutant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct MutationVerdict {
/// The review key of the mutant. It is the `mutant_id`: the id hashes the
/// path, the text of the enclosing function, the relative span, the
/// operator and the replacement, so it stays the same until the function
/// changes.
pub review_key: String,
/// The judgment.
pub verdict: MutationVerdictKind,
/// A short reason, for human review.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
/// A versioned verdict document, authored by a person or an agent, for
/// `fallow mutation --verdicts <file>`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct MutationVerdictInput {
/// Independent verdict document schema version.
pub schema_version: MutationVerdictSchemaVersion,
/// The verdicts. Each `review_key` occurs one time.
pub verdicts: Vec<MutationVerdict>,
}
/// The result of the join of a run with a verdict document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationVerdictJoin {
/// The SHA-256 digest of the verdict document, lowercase hex.
pub verdicts_sha256: String,
/// The mutants that got the status `equivalent`, sorted.
pub applied: Vec<String>,
/// The verdicts that a test contradicts, sorted: the mutant was killed or
/// timed out, so it is not equivalent. The status stays.
pub contradicted: Vec<String>,
/// The verdicts for mutants with no tested result (`pending`,
/// `runtime_error` or `pruned`), sorted. The status stays.
pub deferred: Vec<String>,
/// The verdicts that match no mutant of this run, sorted. A verdict
/// document can hold keys for code outside the scope of the run, and an
/// edit of a function gives its mutants new keys.
pub unmatched: Vec<String>,
}
/// The status of a mutant in a plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MutationPlanDisposition {
/// A run executes the mutant.
Planned,
/// The mutant is after the mutant limit. The plan limit comes before
/// the coverage is known: a run executes a pending mutant in the place
/// of a planned mutant that no test covers.
Pending,
/// No test file reaches the file of the mutant.
NoCoverage,
/// A static rule removes the mutant.
Pruned,
}
/// One mutant of a plan.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationPlanMutant {
/// The mutant and its position.
#[serde(flatten)]
pub location: MutantLocation,
/// The status in the plan.
pub disposition: MutationPlanDisposition,
/// The static rule of a `pruned` mutant, kebab-case.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prune_reason: Option<String>,
/// Why a `pending` mutant did not run, kebab-case. Only `sampled-out` has
/// a reason: the `--mutants-per-line` limit left the mutant out of the
/// plan. A mutant that the mutant limit or the time budget left out has
/// no reason.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pending_reason: Option<String>,
/// How tests reach the code of the mutant in the module graph. Only a
/// `no_coverage` mutant has this field.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub test_reach: Option<MutantTestReach>,
}
/// One instrumented file of a plan.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationPlanFile {
/// The root-relative path, with forward slashes.
pub path: String,
/// The SHA-256 digest of the file, lowercase hex.
pub source_sha256: String,
/// The test files that reach the file in the module graph, sorted.
pub static_test_files: Vec<String>,
}
/// The totals of a plan.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationPlanCountsOutput {
/// Each mutant.
pub total: usize,
/// Planned mutants.
pub planned: usize,
/// Mutants after the mutant limit, and the sampled-out mutants.
pub pending: usize,
/// The `pending` mutants that the `--mutants-per-line` limit left out.
pub sampled_out: usize,
/// Mutants that no test file reaches.
pub no_coverage: usize,
/// Mutants in unused files.
pub pruned_dead_code: usize,
/// Mutants in generated files.
pub pruned_generated: usize,
/// Mutants near a file system, process, network or database sink.
pub pruned_side_effect_sink: usize,
/// Mutants in framework config exports.
pub pruned_framework_config: usize,
/// Mutants in files that only tool config files reach. Absent when 0.
#[serde(default, skip_serializing_if = "is_zero")]
pub pruned_build_tool_only: usize,
}
/// The envelope of `fallow mutation --plan`. It runs no user code.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationPlanOutput {
/// Independent schema version.
pub schema_version: MutationPlanSchemaVersion,
/// The Fallow version.
pub version: ToolVersion,
/// The total wall time.
pub elapsed_ms: ElapsedMs,
/// The mutated code.
pub scope: MutationScopeOutput,
/// The totals.
pub counts: MutationPlanCountsOutput,
/// Each mutant, ranked mutants first.
pub mutants: Vec<MutationPlanMutant>,
/// The instrumented files.
pub files: Vec<MutationPlanFile>,
/// The union of the static test files, sorted.
pub test_files: Vec<String>,
/// True when the project has no test files.
pub no_test_files: bool,
/// True when the plan applied the `framework-config` and
/// `build-tool-only` prune rules.
pub framework_config_checked: bool,
/// The selected files that the plan did not instrument.
pub skipped_files: Vec<MutationSkippedFile>,
/// The paths of a `paths` scope that select no file.
pub unmatched_paths: Vec<String>,
/// The reason for each entry of `unmatched_paths`, at the same index.
/// Each path is relative to the project root. Absent when
/// `unmatched_paths` is empty.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub unmatched_path_reasons: Vec<MutationUnmatchedPath>,
/// The selected test runner and the verdict on its installed version.
pub runner: MutationPlanRunner,
}
/// Version singleton for a mutation inspect packet.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum MutationInspectSchemaVersion {
/// Adds complete kill matrix evidence.
#[serde(rename = "2")]
V2,
}
/// Whether the saved report still describes the current file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MutationInspectStatus {
/// The file has the digest of the report, and the mutant is reproduced.
Fresh,
/// The file changed, is missing, or no longer gives the mutant. The
/// packet then has no code.
Stale,
}
/// Why an inspect packet is stale.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum MutationStaleReason {
/// The file does not exist or cannot be read.
FileMissing,
/// The report has no digest for the file.
NoDigest,
/// The SHA-256 digest of the file differs from the report.
SourceChanged,
/// The file has the digest of the report, but the instrumentation does
/// not give the mutant.
MutantNotReproduced,
}
/// The code of one mutant, from the current file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationInspectCode {
/// The original text of the span.
pub original: String,
/// The text that replaces the span.
pub replacement: String,
/// The source lines that contain the span, before the mutation.
pub original_lines: String,
/// The same lines with the replacement applied.
pub mutated_lines: String,
}
/// The envelope of `fallow mutation inspect`. It runs no user code, except
/// with `--replay`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationInspectOutput {
/// Independent schema version.
pub schema_version: MutationInspectSchemaVersion,
/// The Fallow version.
pub version: ToolVersion,
/// Whether the report still describes the current file.
pub status: MutationInspectStatus,
/// Why the packet is stale. Absent for a fresh packet.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stale_reason: Option<MutationStaleReason>,
/// The mutant and its position, from the report.
#[serde(flatten)]
pub location: MutantLocation,
/// The status of the mutant in the report. Absent for a plan.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub report_status: Option<MutantStatus>,
/// The SHA-256 digest of the file in the report.
pub report_sha256: Option<String>,
/// The SHA-256 digest of the current file. `null` when the file is
/// missing.
pub current_sha256: Option<String>,
/// The original and mutated code. `null` for a stale packet.
pub code: Option<MutationInspectCode>,
/// The tests that reached the mutant in the dry run, sorted.
pub covering_tests: Vec<String>,
/// The test files that reach the file in the module graph, sorted.
pub static_test_files: Vec<String>,
/// The test that killed the mutant in the run of the report.
pub killed_by: Option<String>,
/// All observed failing tests, sorted. Timeouts do not count. Empty
/// outside `--kill-matrix`; `killed_by` keeps the first killer.
pub killing_tests: Vec<String>,
/// True only for exact requested membership with terminal pass or fail results.
pub kill_matrix_complete: bool,
/// The replay of the mutant. Present only with `--replay`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub replay: Option<MutationReplayOutput>,
}
/// Version singleton for the open tasks of a mutation report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum MutationTasksSchemaVersion {
/// The first version.
#[serde(rename = "1")]
V1,
}
/// One open task: a `survived` or `no_coverage` mutant of a saved report.
/// A task holds no source text other than the source lines of the mutant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationTask {
/// The id of the mutant. `fallow mutation inspect` takes this id.
pub mutant_id: String,
/// The project-root-relative path of the mutated file.
pub file: String,
/// The 1-based line of the mutant.
pub line: u32,
/// The 1-based column of the mutant.
pub column: u32,
/// The operator, kebab-case.
pub operator: String,
/// The name of the enclosing function. Absent at the top level of a
/// module and for an anonymous function.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub function: Option<String>,
/// `survived` or `no_coverage`.
pub status: MutantStatus,
/// The source lines that contain the mutant, from the current file.
/// `null` when the task is stale.
pub original_lines: Option<String>,
/// The same lines with the mutation applied. `null` when the task is
/// stale.
pub mutated_lines: Option<String>,
/// An advisory hint that the mutant may be equivalent. The task stays
/// open: a person decides, and records an equivalent mutant in a verdict
/// file.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub equivalence_hint: Option<MutantEquivalenceHint>,
/// Why the current file no longer gives the mutant. Absent for a fresh
/// task.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stale_reason: Option<MutationStaleReason>,
/// The test files of the tests that reached the mutant in the dry run,
/// sorted. Empty for `no_coverage`. `fallow mutation inspect` gives the
/// test ids and the static test files of one mutant.
pub covering_test_files: Vec<String>,
/// The witness of the task: a recorded input that shows a difference, with
/// the results of both sides. Present only after a `--record-args
/// values` run.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub witness: Option<MutationTaskWitness>,
}
/// The number of tasks for each status.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationTasksSummary {
/// The number of tasks.
pub tasks: usize,
/// The tasks with the status `survived`.
pub survived: usize,
/// The tasks with the status `no_coverage`.
pub no_coverage: usize,
/// The tasks whose file changed after the report. They have no code.
pub stale: usize,
}
/// The envelope of `fallow mutation tasks`: the open tasks of one saved
/// report, as one batch. It runs no user code.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MutationTasksOutput {
/// Independent schema version.
pub schema_version: MutationTasksSchemaVersion,
/// The Fallow version.
pub version: ToolVersion,
/// The completion status of the report. A `partial` report can miss
/// tasks: a `pending` mutant is not a task.
pub report_completion: Option<MutationCompletionStatus>,
/// The counts of the tasks.
pub summary: MutationTasksSummary,
/// The tasks, sorted by file, line, column and mutant id.
pub tasks: Vec<MutationTask>,
}
/// Serialize a mutation report with its root discriminator.
///
/// # Errors
///
/// Returns a serde error when the envelope cannot be converted to JSON.
pub fn serialize_mutation_json_output(
output: MutationReport,
) -> Result<serde_json::Value, serde_json::Error> {
serialize_named_json_output(output, "mutation")
}
/// Serialize a mutation plan with its root discriminator.
///
/// # Errors
///
/// Returns a serde error when the envelope cannot be converted to JSON.
pub fn serialize_mutation_plan_json_output(
output: MutationPlanOutput,
) -> Result<serde_json::Value, serde_json::Error> {
serialize_named_json_output(output, "mutation-plan")
}
/// Serialize the open tasks of a mutation report with their root
/// discriminator.
///
/// # Errors
///
/// Returns a serde error when the envelope cannot be converted to JSON.
pub fn serialize_mutation_tasks_json_output(
output: MutationTasksOutput,
) -> Result<serde_json::Value, serde_json::Error> {
serialize_named_json_output(output, "mutation-tasks")
}
/// Serialize a mutation inspect packet with its root discriminator.
///
/// # Errors
///
/// Returns a serde error when the envelope cannot be converted to JSON.
pub fn serialize_mutation_inspect_json_output(
output: MutationInspectOutput,
) -> Result<serde_json::Value, serde_json::Error> {
serialize_named_json_output(output, "mutation-inspect")
}
#[cfg(test)]
mod tests {
use super::*;
fn counts(statuses: &[MutantStatus]) -> MutationStatusCounts {
let mut counts = MutationStatusCounts::default();
for status in statuses {
counts.add(*status);
}
counts
}
#[test]
fn the_score_counts_executed_mutants_and_coverage_counts_reached_mutants() {
let counts = counts(&[
MutantStatus::Killed,
MutantStatus::Killed,
MutantStatus::Timeout,
MutantStatus::Survived,
MutantStatus::NoCoverage,
MutantStatus::NoCoverage,
MutantStatus::RuntimeError,
MutantStatus::Flaky,
MutantStatus::Pruned,
MutantStatus::Pending,
]);
assert_eq!(counts.total, 10);
assert_eq!(counts.killed, 2);
assert_eq!(counts.timeout, 1);
assert_eq!(counts.survived, 1);
assert_eq!(counts.no_coverage, 2);
assert_eq!(counts.runtime_error, 1);
assert_eq!(counts.flaky, 1);
assert_eq!(counts.pruned, 1);
assert_eq!(counts.pending, 1);
assert_eq!(counts.score(), Some(0.75));
}
fn result(status: MutantStatus, covering_tests: &[&str]) -> MutantResult {
MutantResult {
location: MutantLocation {
mutant_id: "m".to_owned(),
file: "src/a.ts".to_owned(),
line: 1,
column: 1,
span: (0, 1),
operator: "arithmetic-operator".to_owned(),
function: None,
function_line: None,
rank: None,
change: None,
},
status,
prune_reason: None,
pending_reason: None,
killing_tests: Vec::new(),
kill_matrix_complete: false,
killed_by: None,
covering_tests: covering_tests
.iter()
.map(|test| (*test).to_owned())
.collect(),
static_mutant: false,
duration_ms: None,
test_reach: None,
retried: false,
attempts: Vec::new(),
cached: false,
resumed: false,
carried: false,
type_error_codes: Vec::new(),
equivalence_hint: None,
witness: None,
}
}
#[test]
fn coverage_counts_executed_mutants_with_a_test_and_pending_mutants_as_covered() {
let summary = MutationSummary::from_results(&[
result(MutantStatus::Killed, &["t1"]),
result(MutantStatus::Survived, &["t1"]),
result(MutantStatus::RuntimeError, &["t2"]),
result(MutantStatus::Pending, &[]),
result(MutantStatus::NoCoverage, &[]),
result(MutantStatus::Equivalent, &["t1"]),
result(MutantStatus::Pruned, &[]),
]);
assert_eq!(summary.score, Some(0.5));
assert_eq!(summary.coverage, Some(0.8));
assert_eq!(
MutationSummary::from_results(&[result(MutantStatus::Pruned, &[])]).coverage,
None
);
}
#[test]
fn a_capped_run_reports_the_coverage_of_the_full_run() {
let full = MutationSummary::from_results(&[
result(MutantStatus::Killed, &["t1"]),
result(MutantStatus::Survived, &["t1"]),
result(MutantStatus::NoCoverage, &[]),
result(MutantStatus::NoCoverage, &[]),
]);
let capped = MutationSummary::from_results(&[
result(MutantStatus::Killed, &["t1"]),
result(MutantStatus::Pending, &[]),
result(MutantStatus::NoCoverage, &[]),
result(MutantStatus::NoCoverage, &[]),
]);
assert_eq!(full.coverage, Some(0.5));
assert_eq!(capped.coverage, Some(0.5));
assert_eq!(full.score, Some(0.5));
assert_eq!(capped.score, Some(1.0));
}
#[test]
fn equivalent_mutants_leave_the_score() {
let mut counts = counts(&[
MutantStatus::Killed,
MutantStatus::Survived,
MutantStatus::Survived,
]);
assert_eq!(counts.score(), Some(1.0 / 3.0));
counts.remove(MutantStatus::Survived);
counts.add(MutantStatus::Equivalent);
assert_eq!(counts.total, 3);
assert_eq!(counts.survived, 1);
assert_eq!(counts.equivalent, 1);
assert_eq!(counts.score(), Some(0.5));
counts.remove(MutantStatus::Timeout);
assert_eq!(counts.total, 3, "removing an absent status changes nothing");
}
#[test]
fn verdict_documents_reject_unknown_fields_and_verdicts() {
let valid: MutationVerdictInput = serde_json::from_value(serde_json::json!({
"schema_version": "1",
"verdicts": [{ "review_key": "abc", "verdict": "equivalent", "note": "same result" }]
}))
.expect("valid document");
assert_eq!(valid.verdicts[0].verdict, MutationVerdictKind::Equivalent);
for invalid in [
serde_json::json!({ "schema_version": "1", "verdicts": [{ "review_key": "a", "verdict": "killed" }] }),
serde_json::json!({ "schema_version": "1", "verdicts": [{ "review_key": "a", "verdict": "equivalent", "extra": 1 }] }),
serde_json::json!({ "schema_version": "2", "verdicts": [] }),
serde_json::json!({ "verdicts": [] }),
] {
assert!(
serde_json::from_value::<MutationVerdictInput>(invalid.clone()).is_err(),
"{invalid}"
);
}
}
#[test]
fn the_score_is_null_when_no_mutant_counts() {
let excluded = counts(&[
MutantStatus::RuntimeError,
MutantStatus::Pruned,
MutantStatus::Flaky,
]);
assert_eq!(excluded.score(), None);
assert_eq!(counts(&[MutantStatus::Survived]).score(), Some(0.0));
assert_eq!(counts(&[MutantStatus::Timeout]).score(), Some(1.0));
}
#[test]
fn completion_is_partial_only_with_a_reason() {
let complete = MutationCompletion::from_reasons(Vec::new());
assert_eq!(complete.status, MutationCompletionStatus::Complete);
let partial = MutationCompletion::from_reasons(vec![
MutationIncompleteReason::TimeBudget,
MutationIncompleteReason::RuntimeError,
MutationIncompleteReason::TimeBudget,
]);
assert_eq!(partial.status, MutationCompletionStatus::Partial);
assert_eq!(
partial.reasons,
vec![
MutationIncompleteReason::RuntimeError,
MutationIncompleteReason::TimeBudget
]
);
}
#[test]
fn a_mutant_result_serializes_flat_with_snake_case_status_and_no_source_text() {
let result = MutantResult {
location: MutantLocation {
mutant_id: "m1".to_owned(),
file: "src/math.ts".to_owned(),
line: 2,
column: 10,
span: (40, 45),
operator: "arithmetic".to_owned(),
function: Some("add".to_owned()),
function_line: Some(1),
rank: Some(1),
change: None,
},
status: MutantStatus::NoCoverage,
prune_reason: None,
pending_reason: None,
killing_tests: Vec::new(),
kill_matrix_complete: false,
killed_by: None,
covering_tests: Vec::new(),
static_mutant: false,
duration_ms: None,
test_reach: None,
retried: false,
attempts: Vec::new(),
cached: false,
resumed: false,
carried: false,
type_error_codes: Vec::new(),
equivalence_hint: None,
witness: None,
};
let value = serde_json::to_value(&result).expect("serializes");
assert_eq!(
value,
serde_json::json!({
"mutant_id": "m1",
"file": "src/math.ts",
"line": 2,
"column": 10,
"span": [40, 45],
"operator": "arithmetic",
"function": "add",
"function_line": 1,
"rank": 1,
"status": "no_coverage",
"killing_tests": [],
"kill_matrix_complete": false
})
);
}
#[test]
fn a_retried_mutant_serializes_each_attempt_in_run_order() {
let attempt = |status, duration_ms, failure_kind| MutantAttempt {
status,
duration_ms: Some(duration_ms),
killing_tests: Vec::new(),
kill_matrix_complete: false,
killed_by: None,
failure_kind,
detail: None,
};
let result = MutantResult {
location: MutantLocation {
mutant_id: "m1".to_owned(),
file: "src/math.ts".to_owned(),
line: 2,
column: 10,
span: (40, 45),
operator: "arithmetic".to_owned(),
function: None,
function_line: None,
rank: None,
change: None,
},
status: MutantStatus::Flaky,
prune_reason: None,
pending_reason: None,
killing_tests: Vec::new(),
kill_matrix_complete: false,
killed_by: None,
covering_tests: Vec::new(),
static_mutant: false,
duration_ms: Some(5000),
test_reach: None,
retried: true,
attempts: vec![
attempt(
MutantStatus::Timeout,
5000,
Some(MutantFailureKind::Timeout),
),
attempt(MutantStatus::Survived, 12, None),
],
cached: false,
resumed: false,
carried: false,
type_error_codes: Vec::new(),
equivalence_hint: None,
witness: None,
};
let value = serde_json::to_value(&result).expect("serializes");
assert_eq!(
value["attempts"],
serde_json::json!([
{"status": "timeout", "duration_ms": 5000, "failure_kind": "timeout", "killing_tests": [], "kill_matrix_complete": false},
{"status": "survived", "duration_ms": 12, "killing_tests": [], "kill_matrix_complete": false}
])
);
assert_eq!(value["retried"], serde_json::json!(true));
}
}