targeted-mutation 0.20.2

Targeted mutation testing for Rust: find the wrong implementations your tests let through
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
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
//! Test binary execution, timeouts, process group cleanup, baseline timing, and worker pool.

use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};

use crate::propagation::{self};
use crate::trace::Trace;
use crate::work_lock::WorkLock;
use crate::{leftovers, progress, witness};

use super::*;

/// How a group of tests is started.
#[derive(Clone)]
pub(super) enum Runner {
    /// A libtest executable.
    Exe(PathBuf),
    Isolated {
        exe: PathBuf,
        test: String,
        ignored: bool,
        wrapper: Option<PathBuf>,
    },
    Nextest {
        copy: PathBuf,
        target_dir: PathBuf,
        profile: Option<String>,
        opt_level: Option<u8>,
        flags: Vec<String>,
    },
    /// The package's doc tests, through `cargo test --doc` in the working copy. rustdoc
    /// compiles them on every run, and they cannot be selected by name.
    Doc {
        copy: PathBuf,
        target_dir: PathBuf,
        package: String,
        opt_level: Option<u8>,
        flags: Vec<String>,
    },
}

impl Runner {
    pub(super) fn executable(&self) -> Option<&Path> {
        match self {
            Self::Exe(exe) | Self::Isolated { exe, .. } => Some(exe),
            Self::Doc { .. } | Self::Nextest { .. } => None,
        }
    }
}

#[derive(Clone, Copy)]
pub(super) enum BaselineTiming {
    Completed(Duration),
    StillRunning(Duration),
}

pub(super) fn explicit_timeout_conflict(
    timeout: Option<Duration>,
    baseline: Duration,
    selected_count: Option<usize>,
    test_count: usize,
) -> Option<Duration> {
    let entire_runner = selected_count.is_none_or(|count| count == test_count);
    timeout.filter(|&limit| entire_runner && baseline >= limit)
}

pub(super) type FilteredTimings =
    std::sync::Mutex<BTreeMap<(usize, Vec<String>), std::sync::Arc<std::sync::OnceLock<Duration>>>>;

#[derive(Debug, Default)]
pub(super) struct WrapperGraceCounter {
    exited: std::sync::atomic::AtomicUsize,
    expired: std::sync::atomic::AtomicUsize,
}

impl WrapperGraceCounter {
    pub(super) fn record_exited(&self) {
        self.exited
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    pub(super) fn record_expired(&self) {
        self.expired
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    pub(super) fn snapshot(&self) -> crate::report::WrapperGraceOutcomes {
        crate::report::WrapperGraceOutcomes {
            exited: self.exited.load(std::sync::atomic::Ordering::Relaxed),
            expired: self.expired.load(std::sync::atomic::Ordering::Relaxed),
        }
    }
}

pub(super) const PROPTEST_DISABLE_ENV: &str = "PROPTEST_DISABLE_FAILURE_PERSISTENCE";
pub(super) const TMT_KEEP_PROPTEST_PERSISTENCE_ENV: &str = "TMT_KEEP_PROPTEST_PERSISTENCE";

pub(super) fn keep_proptest_persistence_requested(setting: Option<std::ffi::OsString>) -> bool {
    setting.is_some_and(|value| !value.is_empty())
}

/// Returns true if a workspace-copy-relative path is a `proptest` regression file:
/// either under a `proptest-regressions` directory (`FileFailurePersistence::SourceParallel`)
/// or with the `.proptest-regressions` extension (`FileFailurePersistence::WithSource`).
pub(super) fn is_proptest_regression_rel(rel: &Path) -> bool {
    rel.components()
        .any(|part| part.as_os_str() == "proptest-regressions")
        || rel
            .extension()
            .is_some_and(|ext| ext == "proptest-regressions")
}

/// Returns true if any regular file under `copy_root` (without following symlinks)
/// is a `proptest` regression file.
pub(super) fn copy_has_proptest_regressions(copy_root: &Path) -> bool {
    let mut stack = vec![copy_root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let Ok(meta) = fs::symlink_metadata(&path) else {
                continue;
            };
            if meta.is_dir() {
                stack.push(path);
            } else if meta.is_file()
                && path
                    .strip_prefix(copy_root)
                    .is_ok_and(is_proptest_regression_rel)
            {
                return true;
            }
        }
    }
    false
}

/// Returns true if any kept file under `copy_root` is a `proptest` regression file.
#[cfg(test)]
pub(super) fn scope_has_proptest_regressions(
    copy_root: &Path,
    kept_files: &HashSet<PathBuf>,
) -> bool {
    kept_files.iter().any(|path| {
        path.strip_prefix(copy_root)
            .is_ok_and(is_proptest_regression_rel)
    })
}

/// Whether `run_binary` should set `PROPTEST_DISABLE_FAILURE_PERSISTENCE=1` to avoid
/// accumulating mutant failure seeds in the isolated working copy.
///
/// Checks the entire workspace copy after build (not only the package directory) because
/// `FileFailurePersistence::SourceParallel` resolves above the package directory for
/// root-level `[lib] path = "lib.rs"` members and `build.rs` may generate regression files.
/// Disabled automatically when any existing regression file is present, when the parent
/// environment already sets `PROPTEST_DISABLE_FAILURE_PERSISTENCE`, or when
/// `TMT_KEEP_PROPTEST_PERSISTENCE` is set to a non-empty value (e.g. for custom
/// `FileFailurePersistence` paths).
pub(super) fn should_disable_proptest_persistence(
    has_existing_regressions: bool,
    parent_env_set: bool,
    keep_opt_out: bool,
) -> bool {
    !has_existing_regressions && !parent_env_set && !keep_opt_out
}

pub(super) struct TestBinary {
    pub(super) name: String,
    /// Directory the tests run in: their package's, as under `cargo test`.
    pub(super) cwd: PathBuf,
    /// Where the marks of its runs are made: a directory of this analysis alone.
    pub(super) marks: PathBuf,
    pub(super) git_ceiling: PathBuf,
    pub(super) work_lock: Option<Arc<WorkLock>>,
    /// The tests the binary contains, by the name libtest selects them with.
    pub(super) tests: BTreeSet<String>,
    pub(super) runner: Runner,
    /// How long the tests take when nothing is recorded: what a mutant is measured against.
    pub(super) baseline: Duration,
    /// A comparable measurement, with trace recording disabled.
    pub(super) untraced_baseline: Option<BaselineTiming>,
    pub(super) timeout_diagnostic: std::sync::Once,
    /// How long they took while recording.
    pub(super) traced: Duration,
    pub(super) timeout: Option<Duration>,
    pub(super) wrapper_grace: Duration,
    pub(super) wrapper_grace_counter: Option<Arc<WrapperGraceCounter>>,
    pub(super) report_slow: bool,
    pub(super) disable_proptest_persistence: bool,
    pub(super) filtered_timings: FilteredTimings,
    pub(super) trace: Trace,
    pub(super) effects_baseline: std::sync::OnceLock<propagation::BaselineIndex>,
}

impl TestBinary {
    pub(super) fn mutant_limit(&self, baseline: Duration) -> Duration {
        self.timeout.unwrap_or_else(|| mutant_timeout(baseline))
    }

    pub(super) fn warn_timeout_conflict(&self, filter: Option<&[String]>) {
        // The initial timing can include tracing or tests outside this filter.
        let Some(limit) = explicit_timeout_conflict(
            self.timeout,
            self.baseline,
            filter.map(<[String]>::len),
            self.tests.len(),
        ) else {
            return;
        };
        self.timeout_diagnostic.call_once(|| {
            let timing = self.untraced_baseline.or_else(|| {
                let started = Instant::now();
                // Bound the check by the original traced run. If it times
                // out, exclude time spent stopping it from the lower bound.
                match run_binary(self, None, &[], self.traced, RunOutput::Quiet, 1) {
                    Ok(Outcome::Pass) => Some(BaselineTiming::Completed(started.elapsed())),
                    Ok(Outcome::Timeout) => Some(BaselineTiming::StillRunning(self.traced)),
                    _ => None,
                }
            });
            let (elapsed, message) = match timing {
                Some(BaselineTiming::Completed(elapsed)) => (elapsed, "took"),
                Some(BaselineTiming::StillRunning(elapsed)) => (elapsed, "was still running after"),
                None => return,
            };
            if elapsed >= limit {
                eprintln!(
                    "tmt: warning: unmutated baseline for `{}` {message} {:.3}s, meeting or exceeding --timeout {}",
                    crate::report::sanitize_inline(&self.name),
                    elapsed.as_secs_f64(),
                    limit.as_secs()
                );
            }
        });
    }

    pub(super) fn filtered_limit(
        &self,
        filter: Option<&[String]>,
        traced: bool,
        sharing: usize,
    ) -> Duration {
        let baseline = if traced { self.traced } else { self.baseline };
        let Some(filter) =
            filter.filter(|names| !names.is_empty() && names.len() < self.tests.len())
        else {
            return self.mutant_limit(baseline);
        };
        if self.timeout.is_some() || baseline < SLOW_TRACE || !matches!(self.runner, Runner::Exe(_))
        {
            return self.mutant_limit(baseline);
        }
        let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
        let threads = test_threads(cores, sharing);
        let timed = {
            let mut groups = self
                .filtered_timings
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            groups
                .entry((threads, filter.to_vec()))
                .or_default()
                .clone()
        };
        let timing = *timed.get_or_init(|| {
            let untraced = self.baseline;
            let started = Instant::now();
            // One measured group is shared by all jobs with this exact filter.
            // A failing or inconclusive timing run keeps the conservative limit.
            match run_binary(
                self,
                Some(filter),
                &[],
                untraced,
                RunOutput::Quiet,
                sharing.max(1),
            ) {
                Ok(Outcome::Pass) => started.elapsed(),
                _ => untraced,
            }
        });
        self.mutant_limit(if traced {
            timing.max(
                timing.mul_f64(self.traced.as_secs_f64() / self.baseline.as_secs_f64().max(0.001)),
            )
        } else {
            timing
        })
    }
}

#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum Outcome {
    Pass,
    Fail,
    Timeout,
    /// The run gave up: it could not go on as the mutant it was started with.
    Unable,
}

impl From<Outcome> for progress::Outcome {
    fn from(outcome: Outcome) -> Self {
        match outcome {
            Outcome::Pass => Self::Survived,
            Outcome::Fail => Self::Failed,
            Outcome::Timeout => Self::TimedOut,
            Outcome::Unable => Self::Unable,
        }
    }
}

/// Tests to pass to the binary, or `None` for "run everything".
///
/// A name that is not one of the binary's tests comes from a thread the test named
/// itself; passing it to libtest would select nothing and "pass". Such observations
/// belong to some unknown test, like those of unnamed threads.
pub(super) fn test_filter(
    tests: &BTreeSet<String>,
    known: &BTreeSet<String>,
) -> Option<Vec<String>> {
    if tests.len() > MAX_TEST_FILTERS || !tests.iter().all(|t| known.contains(t)) {
        None
    } else {
        Some(tests.iter().cloned().collect())
    }
}

/// Names of the tests in libtest's `--list --format terse` output.
pub(super) fn parse_test_list(stdout: &str) -> BTreeSet<String> {
    stdout
        .lines()
        .filter_map(|line| line.strip_suffix(": test"))
        .map(str::to_string)
        .collect()
}

/// Runs `command` in its own process group (on Unix), collecting stdout and stderr while
/// remaining responsive to `SIGINT` / `SIGTERM`. If interrupted, stops and reaps the child
/// process group before returning [`crate::interrupt::Interrupted`].
pub(super) fn output_interruptible(command: &mut Command) -> Result<std::process::Output> {
    use std::io::Read as _;

    crate::interrupt::check()?;
    command
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    #[cfg(unix)]
    std::os::unix::process::CommandExt::process_group(command, 0);

    let mut child = command.spawn()?;
    let group = child.id();
    let mut exit_waiter = ExitWaiter::new(group);
    let stdout_pipe = child.stdout.take();
    let stderr_pipe = child.stderr.take();
    let stdout_handle = std::thread::spawn(move || {
        let mut buf = Vec::new();
        if let Some(mut pipe) = stdout_pipe {
            let _ = pipe.read_to_end(&mut buf);
        }
        buf
    });
    let stderr_handle = std::thread::spawn(move || {
        let mut buf = Vec::new();
        if let Some(mut pipe) = stderr_pipe {
            let _ = pipe.read_to_end(&mut buf);
        }
        buf
    });

    let status = loop {
        if crate::interrupt::is_interrupted() {
            stop_for_interrupt(&mut child, group, false, crate::interrupt::INTERRUPT_GRACE);
            let _ = stdout_handle.join();
            let _ = stderr_handle.join();
            return Err(crate::interrupt::Interrupted.into());
        }
        if let Some(status) = child.try_wait()? {
            break status;
        }
        exit_waiter.wait(Duration::from_millis(50));
    };
    let stdout = stdout_handle.join().unwrap_or_default();
    let stderr = stderr_handle.join().unwrap_or_default();
    Ok(std::process::Output {
        status,
        stdout,
        stderr,
    })
}

/// What makes cargo build the tests (and what they depend on) at an optimisation level.
pub(super) fn list_tests(
    exe: &Path,
    cwd: &Path,
    work: &Path,
    ignored: bool,
    strict: bool,
    lock: Option<&WorkLock>,
) -> Result<BTreeSet<String>> {
    let mut command = Command::new(exe);
    isolate_copy_command(&mut command, work);
    if let Some(lock) = lock {
        lock.retain_for(&mut command);
    }
    command.args(["--list", "--format", "terse"]);
    if ignored {
        command.arg("--ignored");
    }
    command.current_dir(cwd);
    let listing = output_interruptible(&mut command)
        .with_context(|| format!("listing tests of {}", exe.display()))?;
    if !listing.status.success() {
        if !strict {
            return Ok(BTreeSet::new());
        }
        bail!(
            "listing tests of {} failed: {}",
            exe.display(),
            String::from_utf8_lossy(&listing.stderr)
        );
    }
    Ok(parse_test_list(&String::from_utf8_lossy(&listing.stdout)))
}

/// Overflow checks and debug assertions stay as the profile has them.
pub(super) fn profile_env(opt_level: Option<u8>) -> Vec<(&'static str, String)> {
    opt_level.map_or(vec![], |level| {
        vec![
            ("CARGO_PROFILE_DEV_OPT_LEVEL", level.to_string()),
            ("CARGO_PROFILE_TEST_OPT_LEVEL", level.to_string()),
        ]
    })
}

/// A trace run longer than this is followed by a run without recording, for the timing.
pub(super) const SLOW_TRACE: Duration = Duration::from_secs(2);

pub(super) fn mutant_timeout(baseline: Duration) -> Duration {
    Duration::from_secs(5) + baseline * 5
}

pub(super) const TEST_POLL_INITIAL: Duration = Duration::from_micros(250);
pub(super) const TEST_POLL_CAP: Duration = Duration::from_millis(5);

/// Short-running tests often finish before the old polling interval. Back off for
/// longer runs so they do not pay for frequent exit and failure-output checks.
pub(super) fn next_test_poll(delay: &mut Duration, remaining: Duration) -> Duration {
    let wait = (*delay).min(remaining);
    *delay = (*delay * 2).min(TEST_POLL_CAP);
    wait
}

/// The test threads of one test binary when `sharing` of them run at the same time: its
/// share of the cores. Never fewer than two, because the harness runs the tests of a
/// single thread on the main thread, where they have no name to be told apart by.
pub(super) fn test_threads(cores: usize, sharing: usize) -> usize {
    (cores / sharing.max(1)).max(2)
}

pub(super) enum RunOutput<'a> {
    Quiet,
    FirstFailure,
    Capture(&'a fs::File),
}

pub(super) fn nextest_outcome(code: Option<i32>) -> Result<Outcome> {
    match code {
        Some(0) => Ok(Outcome::Pass),
        // Other exit codes indicate infrastructure errors or no selected tests.
        Some(100) => Ok(Outcome::Fail),
        _ => bail!("cargo nextest failed outside a test (exit code {code:?})"),
    }
}

pub(super) fn run_binary(
    bin: &TestBinary,
    tests: Option<&[String]>,
    env: &[(&str, &str)],
    timeout: Duration,
    output: RunOutput<'_>,
    sharing: usize,
) -> Result<Outcome> {
    crate::interrupt::check()?;
    let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
    let threads = test_threads(cores, sharing);
    static RUNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let unable_mark = reserve_file(&bin.marks, "unable", &RUNS)?;

    let mut cmd = match &bin.runner {
        Runner::Exe(exe) => {
            let mut cmd = Command::new(exe);
            // With one test thread libtest runs tests on the main thread, and the runtime
            // could no longer tell which test it is in.
            cmd.arg(format!("--test-threads={threads}"));
            if let Some(tests) = tests {
                cmd.arg("--exact").args(tests);
            }
            cmd.current_dir(&bin.cwd)
                .env("CARGO_MANIFEST_DIR", &bin.cwd);
            cmd
        }
        Runner::Isolated {
            exe,
            test,
            ignored,
            wrapper,
        } => {
            let mut cmd = if let Some(wrapper) = wrapper {
                let mut cmd = Command::new(wrapper);
                cmd.arg(exe);
                cmd
            } else {
                Command::new(exe)
            };
            cmd.args(["--exact", "--test-threads=1", test]);
            if *ignored {
                cmd.arg("--ignored");
            }
            cmd.current_dir(&bin.cwd)
                .env("CARGO_MANIFEST_DIR", &bin.cwd);
            cmd
        }
        Runner::Nextest {
            copy,
            target_dir,
            profile,
            opt_level,
            flags,
        } => {
            let mut cmd = Command::new("cargo");
            cmd.args(["nextest", "run", "--no-tests=fail"]);
            if let Some(profile) = profile {
                cmd.args(["--profile", profile]);
            }
            cmd.args(flags)
                .current_dir(copy)
                .env("CARGO_TARGET_DIR", target_dir)
                .env("CARGO_BUILD_BUILD_DIR", target_dir)
                .envs(profile_env(*opt_level));
            cmd
        }
        Runner::Doc {
            copy,
            target_dir,
            package,
            opt_level,
            flags,
        } => {
            let mut cmd = Command::new("cargo");
            cmd.args(["test", "--doc", "-p", package])
                .args(flags)
                .current_dir(copy)
                .env("CARGO_TARGET_DIR", target_dir)
                .env("CARGO_BUILD_BUILD_DIR", target_dir)
                .envs(profile_env(*opt_level));
            cmd
        }
    };
    isolate_copy_command(&mut cmd, &bin.git_ceiling);
    if let Some(lock) = &bin.work_lock {
        lock.retain_for(&mut cmd);
    }
    cmd.env_remove("TMT_TRACE")
        .env_remove("TMT_MUTANT")
        .env_remove("TMT_TEST")
        .env_remove(witness::OUTPUT_ENV)
        .env("TMT_UNABLE", &unable_mark);
    if bin.disable_proptest_persistence
        && std::env::var_os(PROPTEST_DISABLE_ENV).is_none()
        && !keep_proptest_persistence_requested(std::env::var_os(TMT_KEEP_PROPTEST_PERSISTENCE_ENV))
    {
        cmd.env(PROPTEST_DISABLE_ENV, "1");
    }
    cmd.envs(env.iter().copied()).stdin(Stdio::null());
    if let Runner::Isolated { test, .. } = &bin.runner {
        cmd.env("TMT_TEST", test);
    }
    let nextest = matches!(bin.runner, Runner::Nextest { .. });
    let mut output_to_watch = None;
    match output {
        RunOutput::Capture(file) => {
            cmd.stdout(file.try_clone()?).stderr(file.try_clone()?);
        }
        RunOutput::FirstFailure if !nextest && !matches!(bin.runner, Runner::Isolated { .. }) => {
            // A regular file has a readable end even if a descendant keeps stdout.
            // Reuse the per-run marker, whose contents are never interpreted by probes.
            let writer = fs::OpenOptions::new().append(true).open(&unable_mark)?;
            output_to_watch = Some(FailureOutput::new(fs::File::open(&unable_mark)?));
            cmd.stdout(writer).stderr(Stdio::null());
        }
        RunOutput::Quiet | RunOutput::FirstFailure => {
            cmd.stdout(Stdio::null()).stderr(Stdio::null());
        }
    }
    // Its own process group, so that a timeout can stop whatever the tests started too.
    #[cfg(unix)]
    std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
    // What the tests leave running outside their group is found by a file they pass on.
    let mut watch = leftovers::Watch::new(reserve_file(&bin.marks, "held", &RUNS)?);
    let mut child = match watch.spawn(&mut cmd) {
        Ok(child) => child,
        Err(error) => {
            watch.finish(true);
            let _ = release_mark(&unable_mark);
            return Err(error).with_context(|| format!("starting the tests of `{}`", bin.name));
        }
    };
    let group = child.id();
    let mut exit_waiter = ExitWaiter::new(group);
    let kill = |child: &mut std::process::Child| {
        if nextest {
            // Nextest creates a process group per test. Let its signal handler
            // forward SIGTERM and reap those groups before we return.
            stop_nextest(child, Duration::from_secs(12));
            return;
        }
        kill_test_group(group);
        let _ = child.kill();
        let _ = child.wait();
    };
    let mut reaped_for_interrupt = false;
    let started = Instant::now();
    let mut delay = TEST_POLL_INITIAL;
    let mut waiting_reported = false;
    let running_mutant = env.iter().any(|(key, _)| *key == "TMT_MUTANT")
        || matches!(output, RunOutput::FirstFailure);
    let result: Result<Outcome> = (|| loop {
        if crate::interrupt::is_interrupted() {
            stop_for_interrupt(
                &mut child,
                group,
                nextest,
                crate::interrupt::INTERRUPT_GRACE,
            );
            reaped_for_interrupt = true;
            return Err(crate::interrupt::Interrupted.into());
        }
        if let Some(status) = child.try_wait()? {
            if matches!(bin.runner, Runner::Isolated { .. }) || output_to_watch.is_some() {
                kill_test_group(group);
            }
            if nextest {
                return nextest_outcome(status.code());
            }
            return Ok(if status.success() {
                Outcome::Pass
            } else {
                Outcome::Fail
            });
        }
        if output_to_watch
            .as_mut()
            .map(FailureOutput::failed)
            .transpose()?
            .unwrap_or(false)
        {
            kill(&mut child);
            return Ok(Outcome::Fail);
        }
        let elapsed = started.elapsed();
        if bin.report_slow
            && running_mutant
            && !waiting_reported
            && elapsed >= Duration::from_secs(5).min(timeout / 2)
        {
            let selected = tests
                .filter(|names| !names.is_empty())
                .map(|names| {
                    names
                        .iter()
                        .map(|name| crate::report::sanitize_inline(name))
                        .collect::<Vec<_>>()
                        .join(", ")
                })
                .unwrap_or_else(|| crate::report::sanitize_inline(&bin.name));
            eprintln!(
                "tmt: waiting for mutant tests `{selected}` (limit {:.2}s)",
                timeout.as_secs_f64()
            );
            waiting_reported = true;
        }
        // tmt:ignore at exactly the limit either is right, and no test can stop the clock there
        if elapsed >= timeout {
            if cfg!(unix)
                && !bin.wrapper_grace.is_zero()
                && matches!(
                    &bin.runner,
                    Runner::Isolated {
                        wrapper: Some(_),
                        ..
                    }
                )
            {
                signal_test_group(group, 15);
                let began = Instant::now();
                let mut exited_in_grace = false;
                while began.elapsed() < bin.wrapper_grace {
                    if matches!(child.try_wait(), Ok(Some(_))) {
                        exited_in_grace = true;
                        break;
                    }
                    if crate::interrupt::force_kill_requested() {
                        break;
                    }
                    std::thread::sleep(
                        Duration::from_millis(10)
                            .min(bin.wrapper_grace.saturating_sub(began.elapsed())),
                    );
                }
                if !exited_in_grace && matches!(child.try_wait(), Ok(Some(_))) {
                    exited_in_grace = true;
                }
                if let Some(counter) = &bin.wrapper_grace_counter {
                    if exited_in_grace {
                        counter.record_exited();
                    } else {
                        counter.record_expired();
                    }
                }
            }
            kill(&mut child);
            return Ok(Outcome::Timeout);
        }
        // tmt:ignore without the pause the loop only looks more often: the verdict is the same
        let remaining = timeout - elapsed;
        let wait = if output_to_watch.is_none() && exit_waiter.is_event_driven() {
            if bin.report_slow && running_mutant && !waiting_reported {
                let slow_at = Duration::from_secs(5).min(timeout / 2);
                remaining.min(
                    slow_at
                        .saturating_sub(elapsed)
                        .max(Duration::from_millis(1)),
                )
            } else {
                remaining
            }
        } else {
            next_test_poll(&mut delay, remaining)
        };
        exit_waiter.wait(wait);
    })();
    // tmt:ignore only Windows needs the file closed before the mark is removed, and these tests are for Unix
    drop(output_to_watch);
    // Stop the runner before sweeping leftovers so a live child is never still holding
    // the watch lock when the sweep begins.
    if result.is_err() {
        if !reaped_for_interrupt {
            kill(&mut child);
        }
        let _ = release_mark(&unable_mark);
    }
    // The run is over, whichever way: what it started and did not stop is stopped now.
    let leave_leftovers = if reaped_for_interrupt {
        false
    } else {
        leftovers::leave()
    };
    leftovers::count(&watch.finish(leave_leftovers));
    let outcome = result?;

    // Whatever the tests made of it, a run that left the mark was not the mutant's. The
    // mark alone says so: a status is the tests' to choose, and one of them may well end
    // with the runtime's when it finds a mutant out.
    if release_mark(&unable_mark)? {
        return Ok(Outcome::Unable);
    }
    Ok(outcome)
}

pub(super) struct FailureOutput {
    pub(super) file: fs::File,
    pub(super) line: Vec<u8>,
    pub(super) discarded: bool,
}

/// Event-driven child exit waiter (`kqueue` on macOS, `pidfd_open` + `poll` on Linux,
/// falling back to `std::thread::sleep` on other platforms or unsupported kernels).
struct ExitWaiter {
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    fd: Option<std::os::fd::OwnedFd>,
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    exited: bool,
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    wake_registered: bool,
}

impl ExitWaiter {
    #[cfg(target_os = "macos")]
    fn new(pid: u32) -> Self {
        use std::os::fd::{FromRawFd, OwnedFd};
        const EVFILT_PROC: i16 = -5;
        const EV_ADD: u16 = 0x0001;
        const EV_ONESHOT: u16 = 0x0010;
        const NOTE_EXIT: u32 = 0x8000_0000;
        const F_SETFD: std::ffi::c_int = 2;
        const FD_CLOEXEC: std::ffi::c_int = 1;
        const ESRCH: i32 = 3;

        #[repr(C)]
        struct Kevent {
            ident: usize,
            filter: i16,
            flags: u16,
            fflags: u32,
            data: isize,
            udata: *mut std::ffi::c_void,
        }
        #[repr(C)]
        struct Timespec {
            tv_sec: isize,
            tv_nsec: isize,
        }
        unsafe extern "C" {
            fn kqueue() -> std::ffi::c_int;
            fn fcntl(fd: std::ffi::c_int, cmd: std::ffi::c_int, ...) -> std::ffi::c_int;
            fn kevent(
                kq: std::ffi::c_int,
                changelist: *const Kevent,
                nchanges: std::ffi::c_int,
                eventlist: *mut Kevent,
                nevents: std::ffi::c_int,
                timeout: *const Timespec,
            ) -> std::ffi::c_int;
        }
        // SAFETY: `kqueue()` takes no arguments and returns a new fd or -1.
        let raw = unsafe { kqueue() };
        if raw < 0 {
            return Self {
                fd: None,
                exited: false,
                wake_registered: false,
            };
        }
        // SAFETY: `raw` is a valid newly opened kqueue descriptor owned by `fd`.
        let fd = unsafe { OwnedFd::from_raw_fd(raw) };
        // Prevent concurrent child spawns from inheriting the kqueue descriptor.
        unsafe { fcntl(raw, F_SETFD, FD_CLOEXEC) };
        let change = Kevent {
            ident: pid as usize,
            filter: EVFILT_PROC,
            flags: EV_ADD | EV_ONESHOT,
            fflags: NOTE_EXIT,
            data: 0,
            udata: std::ptr::null_mut(),
        };
        let zero = Timespec {
            tv_sec: 0,
            tv_nsec: 0,
        };
        // SAFETY: `change` and `zero` are valid pointers for a 1-element registration.
        let rc = unsafe { kevent(raw, &change, 1, std::ptr::null_mut(), 0, &zero) };
        if rc == 0 {
            let mut wake_registered = false;
            if let Some(wake_fd) = crate::interrupt::wake_read_fd() {
                const EVFILT_READ: i16 = -1;
                let wake_change = Kevent {
                    ident: wake_fd as usize,
                    filter: EVFILT_READ,
                    flags: EV_ADD,
                    fflags: 0,
                    data: 0,
                    udata: std::ptr::null_mut(),
                };
                // SAFETY: `wake_change` and `zero` are valid stack structs.
                wake_registered =
                    unsafe { kevent(raw, &wake_change, 1, std::ptr::null_mut(), 0, &zero) } == 0;
            }
            Self {
                fd: Some(fd),
                exited: false,
                wake_registered,
            }
        } else if std::io::Error::last_os_error().raw_os_error() == Some(ESRCH) {
            Self {
                fd: None,
                exited: true,
                wake_registered: false,
            }
        } else {
            Self {
                fd: None,
                exited: false,
                wake_registered: false,
            }
        }
    }

    #[cfg(all(
        target_os = "linux",
        any(
            all(target_arch = "x86_64", target_pointer_width = "64"),
            target_arch = "aarch64",
            target_arch = "x86",
            target_arch = "riscv64"
        )
    ))]
    fn new(pid: u32) -> Self {
        use std::os::fd::{FromRawFd, OwnedFd};
        const SYS_PIDFD_OPEN: std::ffi::c_long = 434;
        const ESRCH: i32 = 3;
        unsafe extern "C" {
            fn syscall(num: std::ffi::c_long, ...) -> std::ffi::c_long;
        }
        let Ok(raw_pid) = std::ffi::c_int::try_from(pid) else {
            return Self {
                fd: None,
                exited: false,
                wake_registered: false,
            };
        };
        // SAFETY: `pidfd_open(pid, 0)` returns a new O_CLOEXEC fd or -1.
        let raw = unsafe { syscall(SYS_PIDFD_OPEN, raw_pid, 0 as std::ffi::c_uint) };
        if raw >= 0 {
            // SAFETY: `raw` is a newly created valid pidfd owned by this struct.
            let fd = unsafe { OwnedFd::from_raw_fd(raw as std::os::fd::RawFd) };
            Self {
                fd: Some(fd),
                exited: false,
                wake_registered: crate::interrupt::wake_read_fd().is_some(),
            }
        } else if std::io::Error::last_os_error().raw_os_error() == Some(ESRCH) {
            Self {
                fd: None,
                exited: true,
                wake_registered: false,
            }
        } else {
            Self {
                fd: None,
                exited: false,
                wake_registered: false,
            }
        }
    }

    #[cfg(not(any(
        target_os = "macos",
        all(
            target_os = "linux",
            any(
                all(target_arch = "x86_64", target_pointer_width = "64"),
                target_arch = "aarch64",
                target_arch = "x86",
                target_arch = "riscv64"
            )
        )
    )))]
    fn new(_pid: u32) -> Self {
        #[cfg(target_os = "linux")]
        {
            Self {
                fd: None,
                exited: false,
                wake_registered: false,
            }
        }
        #[cfg(not(target_os = "linux"))]
        {
            Self {}
        }
    }

    fn is_event_driven(&self) -> bool {
        #[cfg(any(target_os = "macos", target_os = "linux"))]
        {
            self.fd.is_some() || self.exited
        }
        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
        {
            false
        }
    }

    #[cfg(target_os = "macos")]
    fn wait(&mut self, duration: Duration) {
        use std::os::fd::AsRawFd;
        if self.exited {
            // `NOTE_EXIT` can fire slightly before `waitpid(WNOHANG)` sees the zombie;
            // yield briefly rather than busy-spinning.
            std::thread::sleep(duration.min(TEST_POLL_INITIAL));
            return;
        }
        let Some(fd) = &self.fd else {
            sleep_interruptible(duration);
            return;
        };
        #[repr(C)]
        struct Kevent {
            ident: usize,
            filter: i16,
            flags: u16,
            fflags: u32,
            data: isize,
            udata: *mut std::ffi::c_void,
        }
        #[repr(C)]
        struct Timespec {
            tv_sec: isize,
            tv_nsec: isize,
        }
        unsafe extern "C" {
            fn kevent(
                kq: std::ffi::c_int,
                changelist: *const Kevent,
                nchanges: std::ffi::c_int,
                eventlist: *mut Kevent,
                nevents: std::ffi::c_int,
                timeout: *const Timespec,
            ) -> std::ffi::c_int;
        }
        let mut ev = Kevent {
            ident: 0,
            filter: 0,
            flags: 0,
            fflags: 0,
            data: 0,
            udata: std::ptr::null_mut(),
        };
        let bounded = if self.wake_registered {
            duration
        } else {
            duration.min(Duration::from_millis(50))
        };
        let ts = Timespec {
            tv_sec: bounded.as_secs().min(isize::MAX as u64) as isize,
            tv_nsec: bounded.subsec_nanos() as isize,
        };
        const EVFILT_PROC: i16 = -5;
        // SAFETY: `ev` and `ts` are valid stack structs for a 1-event wait.
        let rc = unsafe { kevent(fd.as_raw_fd(), std::ptr::null(), 0, &mut ev, 1, &ts) };
        if rc > 0 && ev.filter == EVFILT_PROC {
            self.exited = true;
        }
    }

    #[cfg(target_os = "linux")]
    fn wait(&mut self, duration: Duration) {
        use std::os::fd::AsRawFd;
        if self.exited {
            return;
        }
        let Some(fd) = &self.fd else {
            sleep_interruptible(duration);
            return;
        };
        const POLLIN: std::ffi::c_short = 0x0001;
        #[repr(C)]
        struct PollFd {
            fd: std::ffi::c_int,
            events: std::ffi::c_short,
            revents: std::ffi::c_short,
        }
        unsafe extern "C" {
            fn poll(
                fds: *mut PollFd,
                nfds: std::ffi::c_ulong,
                timeout: std::ffi::c_int,
            ) -> std::ffi::c_int;
        }
        let mut pfds = [
            PollFd {
                fd: fd.as_raw_fd(),
                events: POLLIN,
                revents: 0,
            },
            PollFd {
                fd: crate::interrupt::wake_read_fd().unwrap_or(-1),
                events: POLLIN,
                revents: 0,
            },
        ];
        let nfds = if pfds[1].fd >= 0 { 2 } else { 1 };
        let bounded = if self.wake_registered && nfds == 2 {
            duration
        } else {
            duration.min(Duration::from_millis(50))
        };
        let ms = bounded.as_millis().clamp(1, std::ffi::c_int::MAX as u128) as std::ffi::c_int;
        // SAFETY: `pfds` is a valid `pollfd` array of length `nfds`.
        let rc = unsafe { poll(pfds.as_mut_ptr(), nfds, ms) };
        if rc > 0 && pfds[0].revents != 0 {
            self.exited = true;
        }
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    fn wait(&mut self, duration: Duration) {
        sleep_interruptible(duration);
    }
}

fn sleep_interruptible(duration: Duration) {
    const SLICE: Duration = Duration::from_millis(50);
    let started = Instant::now();
    while started.elapsed() < duration && !crate::interrupt::is_interrupted() {
        let left = duration.saturating_sub(started.elapsed());
        std::thread::sleep(left.min(SLICE));
    }
}

/// Stops an owned child process group on SIGINT: sends SIGTERM, waits up to `grace`
/// (aborting early on a second SIGINT), escalates to SIGKILL if still alive, and reaps
/// the child before returning.
pub(super) fn stop_for_interrupt(
    child: &mut std::process::Child,
    group: u32,
    nextest: bool,
    grace: Duration,
) {
    let effective_grace = if crate::interrupt::force_kill_requested() {
        Duration::ZERO
    } else {
        grace
    };
    if nextest {
        stop_nextest(child, effective_grace);
        return;
    }
    // Snapshot owned process groups while the leader is still un-reaped (so `group`
    // cannot be recycled by the OS). Include any process still in `group` even if the
    // leader already exited and reparented it to PID 1.
    #[cfg(unix)]
    let mut owned = owned_test_processes(group);
    #[cfg(unix)]
    for process in test_processes() {
        if process.group == group && !owned.iter().any(|existing| existing.pid == process.pid) {
            owned.push(process);
        }
    }
    if child.try_wait().ok().flatten().is_some() {
        #[cfg(unix)]
        for surviving in surviving_groups(&owned, &test_processes()) {
            kill_test_group(surviving);
        }
        return;
    }
    if !effective_grace.is_zero() {
        signal_test_group(group, 15);
        let began = Instant::now();
        while began.elapsed() < effective_grace {
            match child.try_wait() {
                Ok(Some(_)) => {
                    #[cfg(unix)]
                    for surviving in surviving_groups(&owned, &test_processes()) {
                        kill_test_group(surviving);
                    }
                    return;
                }
                Ok(None) => {
                    if crate::interrupt::force_kill_requested() {
                        break;
                    }
                    let left = effective_grace.saturating_sub(began.elapsed());
                    std::thread::sleep(Duration::from_millis(10).min(left));
                }
                Err(_) => break,
            }
        }
    }
    kill_test_group(group);
    #[cfg(unix)]
    for surviving in surviving_groups(&owned, &test_processes()) {
        kill_test_group(surviving);
    }
    let _ = child.kill();
    let _ = child.wait();
}

impl FailureOutput {
    pub(super) fn new(file: fs::File) -> Self {
        Self {
            file,
            line: Vec::new(),
            discarded: false,
        }
    }

    pub(super) fn failed(&mut self) -> std::io::Result<bool> {
        use std::io::Read as _;
        const MAX_LINE: usize = 8 * 1024;
        let mut chunk = [0; MAX_LINE];
        let read = self.file.read(&mut chunk)?;
        for part in chunk[..read].split_inclusive(|byte| *byte == b'\n') {
            self.discarded |= self.line.len() + part.len() > MAX_LINE;
            if !self.discarded {
                self.line.extend_from_slice(part);
            }
            if part.ends_with(b"\n") {
                if !self.discarded
                    && is_failure_line(String::from_utf8_lossy(&self.line).trim_end())
                {
                    return Ok(true);
                }
                self.discarded = false;
                self.line.clear();
            }
        }
        Ok(false)
    }
}

pub(super) fn stop_nextest(child: &mut std::process::Child, grace: Duration) {
    let wait = |child: &mut std::process::Child, limit: Duration| {
        let started = Instant::now();
        loop {
            match child.try_wait() {
                // tmt:ignore a runner taken for running is signalled again and collected at the end all the same: what this spares is signals to a group that is gone
                Ok(Some(_)) => return true,
                // tmt:ignore how long a runner that does not end is waited for can only be told by the clock
                Ok(None)
                    if started.elapsed() < limit && !crate::interrupt::force_kill_requested() =>
                {
                    // tmt:ignore without the pause the loop only looks more often
                    std::thread::sleep(Duration::from_millis(10));
                }
                _ => return false,
            }
        }
    };
    let group = child.id();
    // Snapshot the owned groups before checking whether the parent has already exited.
    // A wrapper can exit before its independently grouped children are reparented and stopped.
    #[cfg(unix)]
    let mut owned = owned_test_processes(group);
    if wait(child, Duration::ZERO) {
        #[cfg(unix)]
        for surviving in surviving_groups(&owned, &test_processes()) {
            kill_test_group(surviving);
        }
        return;
    }
    signal_test_group(group, 15);
    let mut reaped = wait(child, grace);
    if !reaped && !crate::interrupt::force_kill_requested() {
        // The second signal asks nextest to force its units to stop.
        signal_test_group(group, 15);
        reaped = wait(child, grace.min(Duration::from_secs(1)));
    }
    #[cfg(unix)]
    {
        // tmt:ignore the second look only adds a test started between the two, which no test can place there
        if !reaped {
            // tmt:ignore as above
            owned.extend(owned_test_processes(group));
        }
        for surviving in surviving_groups(&owned, &test_processes()) {
            kill_test_group(surviving);
        }
    }
    if !reaped {
        // tmt:ignore the group of a runner that `ps` listed was stopped just above: this is for when `ps` could not be run
        kill_test_group(group);
        let _ = child.kill();
        let _ = child.wait();
    }
}

#[cfg(unix)]
#[derive(Debug, PartialEq)]
pub(super) struct TestProcess {
    pub(super) pid: u32,
    pub(super) parent: u32,
    pub(super) group: u32,
    pub(super) started: String,
}

#[cfg(unix)]
pub(super) fn test_processes() -> Vec<TestProcess> {
    let Ok(processes) = Command::new("ps")
        .args([
            "-e", "-o", "pid=", "-o", "ppid=", "-o", "pgid=", "-o", "lstart=",
        ])
        .output()
    else {
        return vec![];
    };
    String::from_utf8_lossy(&processes.stdout)
        .lines()
        .filter_map(|line| {
            let mut fields = line.split_whitespace();
            Some(TestProcess {
                pid: fields.next()?.parse().ok()?,
                parent: fields.next()?.parse().ok()?,
                group: fields.next()?.parse().ok()?,
                started: fields.collect::<Vec<_>>().join(" "),
            })
        })
        .collect()
}

/// The groups of the processes in `owned` that are still among `current`. A process is
/// the same one only with the same start and still in its group: its number alone may
/// by now be another's, and it may have moved to a group that was never the runner's.
#[cfg(unix)]
pub(super) fn surviving_groups(owned: &[TestProcess], current: &[TestProcess]) -> BTreeSet<u32> {
    current
        .iter()
        .filter(|process| {
            owned.iter().any(|before| {
                process.pid == before.pid
                    && process.group == before.group
                    && process.started == before.started
            })
        })
        .map(|process| process.group)
        .collect()
}

#[cfg(unix)]
pub(super) fn owned_test_processes(root: u32) -> Vec<TestProcess> {
    owned_among(test_processes(), root)
}

/// Of the processes in `data`, those `root` started, directly or through others, that
/// are in a group one of them leads.
#[cfg(unix)]
pub(super) fn owned_among(data: Vec<TestProcess>, root: u32) -> Vec<TestProcess> {
    let mut owned = HashSet::from([root]);
    loop {
        let before = owned.len();
        for process in &data {
            if owned.contains(&process.parent) {
                owned.insert(process.pid);
            }
        }
        if owned.len() == before {
            break;
        }
    }
    // Only signal groups that are independently owned, rather than a group a
    // child happened to join. Retain member identities in case its leader exits.
    let groups: HashSet<_> = data
        .iter()
        .filter(|process| process.pid == process.group && owned.contains(&process.pid))
        .map(|process| process.group)
        .collect();
    data.into_iter()
        .filter(|process| owned.contains(&process.pid) && groups.contains(&process.group))
        .collect()
}

pub(super) fn kill_test_group(id: u32) {
    signal_test_group(id, 9);
}

pub(super) fn signal_test_group(id: u32, signal: i32) {
    // Never signal group 0 (this process's own group) or 1 (init).
    if id <= 1 {
        return;
    }
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    {
        unsafe extern "C" {
            fn killpg(group: std::ffi::c_int, signal: std::ffi::c_int) -> std::ffi::c_int;
        }
        if let Ok(group) = std::ffi::c_int::try_from(id)
            && group > 1
        {
            // SAFETY: the argument is the child PID (> 1) used to create its own test group.
            unsafe { killpg(group, signal) };
        }
    }
    #[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
    let _ = Command::new("kill")
        .args([format!("-{signal}"), "--".to_owned(), format!("-{id}")])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
    #[cfg(not(unix))]
    let _ = (id, signal);
}

pub(super) const DEFAULT_BASELINE_TIMEOUT: Duration = Duration::from_secs(3600);

#[derive(Debug, PartialEq, Eq)]
pub(super) enum BaselineRun {
    Passed,
    TimedOut {
        elapsed: Duration,
        log: Option<PathBuf>,
        log_summary: Vec<String>,
    },
    Failed {
        reason: &'static str,
        elapsed: Duration,
        log: PathBuf,
        log_summary: Vec<String>,
    },
}

fn truncate_utf8_line(line: &str, max_bytes: usize) -> String {
    if line.len() <= max_bytes {
        return line.to_string();
    }
    const ELLIPSIS: &str = "...";
    let budget = max_bytes.saturating_sub(ELLIPSIS.len());
    let mut end = 0usize;
    for (idx, ch) in line.char_indices() {
        let next = idx + ch.len_utf8();
        if next > budget {
            break;
        }
        end = next;
    }
    let mut out = String::with_capacity(end + ELLIPSIS.len());
    out.push_str(&line[..end]);
    out.push_str(ELLIPSIS);
    out
}

/// Extracts high-signal failure/panic lines from a baseline test log (libtest, nextest,
/// or generic test output), bounded by line count, per-line byte limit, and total byte budget.
pub fn summarize_baseline_log(text: &str) -> Vec<String> {
    const MAX_LINES: usize = 20;
    const MAX_FALLBACK_LINES: usize = 10;
    const MAX_LINE_BYTES: usize = 256;
    const MAX_BYTES: usize = 2048;

    let lines: Vec<&str> = text
        .lines()
        .map(|line| line.trim_end_matches('\r'))
        .collect();

    let mut picked: Vec<String> = Vec::new();
    let mut bytes = 0usize;
    let push_line = |picked: &mut Vec<String>, bytes: &mut usize, line: &str| -> bool {
        let sanitized = crate::report::sanitize_inline(line.trim_end());
        if sanitized.is_empty() {
            return true;
        }
        let clipped = truncate_utf8_line(&sanitized, MAX_LINE_BYTES);
        if picked.len() >= MAX_LINES {
            return false;
        }
        let next_bytes = *bytes + clipped.len() + 1;
        if next_bytes > MAX_BYTES {
            return false;
        }
        *bytes = next_bytes;
        picked.push(clipped);
        true
    };

    let mut include_next_panic_detail = false;
    for line in &lines {
        let trimmed = line.trim();
        if include_next_panic_detail {
            include_next_panic_detail = false;
            if !trimmed.is_empty() && !trimmed.starts_with("note:") {
                if !push_line(&mut picked, &mut bytes, line) {
                    break;
                }
                continue;
            }
        }
        let is_panic = trimmed.starts_with("thread '") && trimmed.contains("panicked at");
        let is_signal = is_failure_line(trimmed)
            || trimmed.starts_with("FAIL [")
            || is_panic
            || trimmed.starts_with("test result: FAILED")
            || trimmed.starts_with("error:")
            || trimmed.starts_with("fatal:")
            || trimmed.starts_with("Error:")
            || trimmed.starts_with("FATAL:");
        if is_signal {
            if !push_line(&mut picked, &mut bytes, line) {
                break;
            }
            if is_panic {
                include_next_panic_detail = true;
            }
        }
    }

    if !picked.is_empty() {
        return picked;
    }

    // Fallback when no structured failure/panic line matched: last non-empty lines.
    let non_empty: Vec<&str> = lines
        .into_iter()
        .filter(|line| !line.trim().is_empty())
        .collect();
    let start = non_empty.len().saturating_sub(MAX_FALLBACK_LINES);
    for line in &non_empty[start..] {
        if !push_line(&mut picked, &mut bytes, line) {
            break;
        }
    }
    picked
}

fn read_log_tail_summary(log: &mut fs::File) -> Result<Vec<String>> {
    use std::io::{Read, Seek, SeekFrom};
    const TAIL_LIMIT: u64 = 64 * 1024;
    let len = log.metadata()?.len();
    log.seek(SeekFrom::Start(len.saturating_sub(TAIL_LIMIT)))?;
    let mut tail = Vec::new();
    log.take(TAIL_LIMIT).read_to_end(&mut tail)?;
    let text = String::from_utf8_lossy(&tail);
    Ok(summarize_baseline_log(&text))
}

/// Keeps diagnostics on disk so a descendant holding stdout open cannot hold up the driver.
pub(super) fn run_baseline(
    bin: &TestBinary,
    env: &[(&str, &str)],
    timeout: Duration,
    path: &Path,
    timing_only: bool,
) -> Result<BaselineRun> {
    let mut suffix = 0;
    let (path, mut log) = loop {
        let candidate = if suffix == 0 {
            path.to_path_buf()
        } else {
            path.with_extension(format!("{suffix}.log"))
        };
        match fs::OpenOptions::new()
            .create_new(true)
            .read(true)
            .write(true)
            .open(&candidate)
        {
            Ok(log) => break (candidate, log),
            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => suffix += 1,
            Err(err) => {
                return Err(err)
                    .with_context(|| format!("creating baseline log {}", candidate.display()));
            }
        }
    };
    let started = Instant::now();
    let result =
        run_binary(bin, None, env, timeout, RunOutput::Capture(&log), 1).with_context(|| {
            format!(
                "running baseline for `{}`; output: {}",
                bin.name,
                path.display()
            )
        })?;
    let elapsed = started.elapsed();
    if result == Outcome::Pass {
        drop(log);
        fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
        return Ok(BaselineRun::Passed);
    }
    if result == Outcome::Timeout {
        if timing_only {
            drop(log);
            fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
            return Ok(BaselineRun::TimedOut {
                elapsed,
                log: None,
                log_summary: Vec::new(),
            });
        }
        let log_summary = read_log_tail_summary(&mut log).unwrap_or_default();
        return Ok(BaselineRun::TimedOut {
            elapsed,
            log: Some(path),
            log_summary,
        });
    }
    let reason = match result {
        Outcome::Pass | Outcome::Timeout => unreachable!("handled above"),
        Outcome::Fail => "do not pass on the unmutated code",
        Outcome::Unable => "could not be evaluated on the unmutated code",
    };
    let log_summary = read_log_tail_summary(&mut log)?;
    Ok(BaselineRun::Failed {
        reason,
        elapsed,
        log: path,
        log_summary,
    })
}

pub(super) fn run_source_tests(binaries: &[&TestBinary]) -> Result<Outcome> {
    for bin in binaries {
        bin.warn_timeout_conflict(None);
        let outcome = run_binary(
            bin,
            None,
            &[],
            bin.mutant_limit(bin.baseline),
            RunOutput::FirstFailure,
            1,
        )?;
        if outcome != Outcome::Pass {
            return Ok(outcome);
        }
    }
    Ok(Outcome::Pass)
}

/// A line of libtest output that reports a failed test.
pub(super) fn is_failure_line(line: &str) -> bool {
    line.starts_with("test ") && line.ends_with(" ... FAILED")
}

/// Calls `work(i)` once for every `i < count`, on up to `workers` threads, and returns the
/// results in index order. The first error wins.
pub(super) fn run_pool<T: Send>(
    count: usize,
    workers: usize,
    work: impl Fn(usize) -> Result<T> + Sync,
) -> Result<Vec<T>> {
    let partial = run_pool_partial(count, workers, work)?;
    if crate::interrupt::is_interrupted() {
        return Err(crate::interrupt::Interrupted.into());
    }
    Ok(partial.into_iter().flatten().collect())
}

/// Calls `work(i)` on up to `workers` threads, returning completed items in index order.
/// When interrupted by `SIGINT` / `SIGTERM`, stops scheduling new items and returns `Ok`
/// with `Some(T)` for completed items and `None` for interrupted or unstarted items.
/// Non-interrupt errors still fail the pool (first error in index order wins).
pub(super) fn run_pool_partial<T: Send>(
    count: usize,
    workers: usize,
    work: impl Fn(usize) -> Result<T> + Sync,
) -> Result<Vec<Option<T>>> {
    if count == 0 {
        return Ok(vec![]);
    }
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    let next = AtomicUsize::new(0);
    let stop = AtomicBool::new(false);
    let done: Vec<Vec<(usize, Result<T>)>> = std::thread::scope(|scope| {
        let handles: Vec<_> = (0..workers.clamp(1, count))
            .map(|_| {
                scope.spawn(|| {
                    let mut mine = vec![];
                    while !stop.load(Ordering::Acquire) && !crate::interrupt::is_interrupted() {
                        let index = next.fetch_add(1, Ordering::Relaxed);
                        if index >= count {
                            break;
                        }
                        let result = work(index);
                        if result.is_err() {
                            stop.store(true, Ordering::Release);
                        }
                        mine.push((index, result));
                    }
                    mine
                })
            })
            .collect();
        handles
            .into_iter()
            .map(|handle| handle.join().expect("worker panicked"))
            .collect()
    });
    let mut ordered: Vec<Option<Result<T>>> = (0..count).map(|_| None).collect();
    for (index, result) in done.into_iter().flatten() {
        ordered[index] = Some(result);
    }
    let mut out = Vec::with_capacity(count);
    for slot in ordered {
        match slot {
            Some(Ok(value)) => out.push(Some(value)),
            Some(Err(err)) if crate::interrupt::is_interrupted_err(&err) => out.push(None),
            Some(Err(err)) => return Err(err),
            None => out.push(None),
        }
    }
    Ok(out)
}