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
//! Trace-driven mutation planning, job execution, timeout confirmation, and sharding.
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use crate::checkpoint::Phase;
use crate::instrument::{self, LiteralSide, Site, SiteKind};
use crate::plan::{self, Mutation, Obs};
use crate::progress;
use crate::propagation::{self, Change};
use crate::report::{self, Finding};
use crate::trace::Trace;
use super::*;
pub(super) struct Session {
pub(super) progress: bool,
pub(super) serial_timeout_rechecks: bool,
pub(super) package_dir: PathBuf,
pub(super) binaries: Vec<TestBinary>,
}
/// One mutant and the tests it has to face, per test binary.
pub(super) struct Job {
pub(super) site: u32,
pub(super) mutation: Mutation,
/// `(index of the binary, tests to run or None for all of them)`.
pub(super) tests: Vec<(usize, Option<Vec<String>>)>,
}
// Jobs are appended in the same order as the numbered probe sites.
pub(super) fn jobs_for_site(jobs: &[Job], site: u32) -> std::ops::Range<usize> {
let first = jobs.partition_point(|job| job.site < site);
let count = jobs[first..].partition_point(|job| job.site == site);
first..first + count
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(super) struct JobResult {
pub(super) first_pass_timeout: bool,
pub(super) unconfirmed_timeout: bool,
/// The tests the mutant passed, when it passed all of them.
pub(super) survived: Option<Vec<String>>,
pub(super) timed_out: bool,
/// The mutant could not be run as what it is: neither found out nor passed.
pub(super) unable: bool,
}
/// What the re-runs say of a survivor the trace predicted.
#[derive(Debug, PartialEq)]
pub(super) enum Prediction {
/// Every re-run passed all the tests.
Confirmed,
/// A re-run was found out by the tests: the trace did not see everything.
Refuted,
/// No re-run was found out, and one could not be run or was only stopped by a time
/// limit that was not confirmed: neither a finding nor a contradiction.
Unknown,
}
impl Prediction {
pub(super) fn of<'a>(runs: impl Iterator<Item = &'a JobResult>) -> Prediction {
let mut verdict = Prediction::Confirmed;
for run in runs {
if run.unable || run.unconfirmed_timeout {
verdict = Prediction::Unknown;
} else if run.survived.is_none() {
return Prediction::Refuted;
}
}
verdict
}
}
impl report::TimeoutRechecks {
pub(super) fn include(&mut self, result: &JobResult) {
if result.first_pass_timeout {
self.first_pass += 1;
if result.unconfirmed_timeout || result.unable {
self.unconfirmed += 1;
} else if result.timed_out {
self.confirmed += 1;
} else {
self.recovered += 1;
}
}
}
}
impl JobResult {
pub(super) fn progress_outcome(&self) -> progress::Outcome {
if self.unable {
progress::Outcome::Unable
} else if self.timed_out {
progress::Outcome::TimedOut
} else if self.survived.is_some() {
progress::Outcome::Survived
} else {
progress::Outcome::Failed
}
}
}
/// The tests of one binary whose observations satisfy `pick`.
pub(super) fn tests_where<T>(
per_test: Option<&BTreeMap<String, T>>,
pick: impl Fn(&T) -> bool,
) -> BTreeSet<String> {
per_test
.into_iter()
.flatten()
.filter(|(_, obs)| pick(obs))
.map(|(test, _)| test.clone())
.collect()
}
pub(super) type InfectedTests<'a> = Box<dyn Fn(&TestBinary, Mutation) -> BTreeSet<String> + 'a>;
pub(super) type ReachingTests<'a> = Box<dyn Fn(&TestBinary) -> BTreeSet<String> + 'a>;
/// A predicted survivor.
pub(super) struct PlannedGap {
pub(super) finding: Finding,
/// Mutations to confirm the prediction with.
pub(super) survivors: Vec<Mutation>,
/// The gap says nothing more than "the expression in this byte range had one value in
/// every test". If that expression is a site of its own that already says so, the
/// gap is not reported a second time.
pub(super) constant_expr: Option<(usize, usize)>,
}
/// The byte range of an operand without the parentheses and spaces around it.
pub(super) fn core_range(start: usize, text: &str) -> (usize, usize) {
let (mut from, mut to) = (0, text.len());
loop {
let inner = &text[from..to];
let trimmed = inner.trim();
from += inner.len() - inner.trim_start().len();
to = from + trimmed.len();
let wrapped = trimmed.starts_with('(') && trimmed.ends_with(')') && {
// The first parenthesis must be the one the last closes: `(a) && (b)` is not wrapped.
let mut depth = 0usize;
trimmed.char_indices().all(|(i, c)| {
match c {
'(' => depth += 1,
')' => depth -= 1,
_ => {}
}
depth > 0 || i == trimmed.len() - 1
})
};
if !wrapped {
return (start + from, start + to);
}
from += 1;
to -= 1;
}
}
/// What the planner decided for one site.
pub(super) struct SitePlan<'a> {
/// Predicted survivors: the finding to report and the mutations to confirm it with.
pub(super) gaps: Vec<PlannedGap>,
/// The comparison cannot have another outcome within its operand types. A function
/// or condition built on it is constant for a reason no test can change.
pub(super) cannot_differ: bool,
/// The expression had a single value in every test.
pub(super) constant: bool,
/// For `&&` / `||`, every observed evaluation produced a boolean value where
/// `a && b == a || b`: if `LogicSwap` survives, it is a redundant constant survivor
/// rather than an assertion gap.
pub(super) redundant_logic_swap: bool,
/// Mutations some test observes differently.
pub(super) run: Vec<Mutation>,
/// Tests of a binary whose execution the mutation can change.
pub(super) infected: InfectedTests<'a>,
/// Tests of a binary that execute the site at all.
pub(super) reaching: ReachingTests<'a>,
}
pub(super) enum Planned<'a> {
Unreached,
/// Reached, and its mutant cannot be run as a probe here: said, not passed over.
NotEvaluated,
/// Reached, but nothing to mutate (operands that are not numbers).
Nothing,
Plan(SitePlan<'a>),
}
/// A predicted survivor with the jobs that confirm it and the expression it calls constant.
pub(super) type ConfirmedGap = (Finding, Vec<usize>, Option<(usize, usize)>);
/// A site with its jobs: indices into the job list.
pub(super) struct SiteWork<'a> {
pub(super) file: &'a str,
pub(super) site: &'a Site,
pub(super) gaps: Vec<ConfirmedGap>,
pub(super) constant: bool,
pub(super) cannot_differ: bool,
pub(super) redundant_logic_swap: bool,
pub(super) runs: Vec<(Mutation, usize)>,
}
impl Session {
pub(super) fn note(&self, text: &str) {
if self.progress {
eprintln!("tmt: {}", report::sanitize_inline(text));
}
}
pub(super) fn merged<T: Default + Copy>(
&self,
select: impl Fn(&Trace) -> Option<&BTreeMap<String, T>>,
merge: impl Fn(&mut T, &T),
) -> T {
let mut all = T::default();
for obs in self
.binaries
.iter()
.filter_map(|b| select(&b.trace))
.flat_map(|t| t.values())
{
merge(&mut all, obs);
}
all
}
/// `primitive` says of a byte range of the file whether it is an arithmetic
/// operation that was run on primitive numbers.
/// `cast_bounds` returns the runtime-observed `[min, max]` bounds of a cast source
/// expression at `(start, end)` when every test binary agreed on its primitive type.
pub(super) fn plan<'a>(
&'a self,
file: &str,
site: &'a Site,
verify: bool,
primitive: &dyn Fn(usize, usize) -> bool,
primitive_cmp: &dyn Fn(usize, usize) -> bool,
cast_bounds: &dyn Fn(usize, usize) -> Option<(i128, i128)>,
) -> Planned<'a> {
let id = site.id;
let reach_plan = |mutation: Mutation| SitePlan {
gaps: vec![],
constant: false,
cannot_differ: false,
redundant_logic_swap: false,
run: vec![mutation],
infected: Box::new(move |bin, _| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
reaching: Box::new(move |bin| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
};
let reached = || {
self.binaries
.iter()
.any(|b| b.trace.reach.contains_key(&id))
};
Planned::Plan(match &site.kind {
SiteKind::Stmt
| SiteKind::Neg { .. }
| SiteKind::Field { .. }
| SiteKind::Body { .. }
if reached() =>
{
reach_plan(Mutation::Delete)
}
SiteKind::Stmt
| SiteKind::Neg { .. }
| SiteKind::Field { .. }
| SiteKind::Body { .. } => return Planned::Unreached,
SiteKind::Guard { can_be_false } => {
let can_be_false = *can_be_false;
let allowed = move |m: &Mutation| can_be_false || *m != Mutation::Const(false);
let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
let guard_plan = plan::plan_return(&merged);
let any_reached = !guard_plan.unreached || reached();
if !any_reached {
return Planned::Unreached;
}
// Any test that reached `guard_override` without reaching `guard_record`
// exited early (e.g. `return`, `?`, panic) inside the guard expression:
// replacing the guard with a constant changes that control flow.
let has_early_exit = self.binaries.iter().any(|bin| {
let Some(reached_tests) = bin.trace.reach.get(&id) else {
return false;
};
let returned = bin.trace.returns.get(&id);
reached_tests.iter().any(|t| {
returned
.and_then(|m| m.get(t))
.is_none_or(|obs| !obs.reached())
})
});
let pure = !has_early_exit
&& is_strictly_pure_guard(&site.text, primitive_cmp(site.start, site.end));
if pure {
let gaps = guard_plan
.always
.filter(|always| allowed(&Mutation::Const(*always)))
.map(|always| PlannedGap {
finding: report::guard_gap_finding(file, site, always, verify),
survivors: vec![Mutation::Const(always)],
// The guard is the condition it consists of.
constant_expr: Some((site.start, site.end)),
})
.into_iter()
.collect();
SitePlan {
constant: false,
cannot_differ: false,
redundant_logic_swap: false,
gaps,
run: guard_plan.run.into_iter().filter(allowed).collect(),
infected: Box::new(move |bin, m| {
tests_where(bin.trace.returns.get(&id), |obs| match m {
Mutation::Const(value) => obs.infected_by_const(value),
_ => obs.reached(),
})
}),
reaching: Box::new(move |bin| guard_reaching_tests(bin, id)),
}
} else {
// A guard that may have side effects, overloaded ops/methods, or early
// exits cannot be proved equivalent to a constant solely from its return
// value: run all reaching tests (including early-exit tests).
let run = [Mutation::Const(true), Mutation::Const(false)]
.into_iter()
.filter(allowed)
.collect();
SitePlan {
constant: false,
cannot_differ: false,
redundant_logic_swap: false,
gaps: vec![],
run,
infected: Box::new(move |bin, _| guard_reaching_tests(bin, id)),
reaching: Box::new(move |bin| guard_reaching_tests(bin, id)),
}
}
}
SiteKind::Arm { .. } if reached() => reach_plan(Mutation::Delete),
SiteKind::Arm { .. } => return Planned::Unreached,
SiteKind::Quantifier { .. } if reached() => reach_plan(Mutation::QuantifierSwap),
SiteKind::LoopCtrl { .. } if reached() => reach_plan(Mutation::LoopCtrlSwap),
SiteKind::LoopCtrl { .. } => return Planned::Unreached,
SiteKind::LiteralSet { elements, .. } => {
let merged = self.merged(|t| t.lit_set.get(&id), plan::LitSetObs::merge);
if merged.opaque {
return Planned::Nothing;
}
if !merged.reached {
return Planned::Unreached;
}
let mut gaps = vec![];
let mut run = vec![];
for i in 0..elements.len().min(8) {
let idx = i as u8;
let m = Mutation::DropLiteralElem(idx);
if merged.matched_elem(idx) {
run.push(m);
} else if let Some(finding) =
report::literal_set_gap_finding(file, site, idx, verify)
{
gaps.push(PlannedGap {
finding,
survivors: vec![m],
constant_expr: None,
});
}
}
SitePlan {
constant: false,
cannot_differ: false,
redundant_logic_swap: false,
gaps,
run,
infected: Box::new(move |bin, m| {
tests_where(bin.trace.lit_set.get(&id), |obs| match m {
Mutation::DropLiteralElem(idx) => obs.matched_elem(idx),
_ => obs.reached,
})
}),
reaching: Box::new(move |bin| {
tests_where(bin.trace.lit_set.get(&id), |obs| obs.reached)
}),
}
}
SiteKind::Not { .. } if reached() => reach_plan(Mutation::DropNot),
// `a..=b` with `b` the largest value of its type is no range the probe could
// return in place of `a..b`: the mutant would run as the original and pass.
SiteKind::Range { .. } if reached() => {
if self
.binaries
.iter()
.any(|b| b.trace.ranges_at_top.contains(&id))
{
return Planned::NotEvaluated;
}
reach_plan(Mutation::RangeEnd)
}
// `!` on an integer or a user type is not negation of a condition, a range of
// something other than integers has no "one more", and `.all`/`.any` on a
// non-`Iterator` type is opaque.
SiteKind::Not { .. } | SiteKind::Range { .. } | SiteKind::Quantifier { .. } => {
if self
.merged(|t| t.arith.get(&id), plan::ArithObs::merge)
.opaque
{
return Planned::Nothing;
}
return Planned::Unreached;
}
SiteKind::Cmp {
op,
literal,
lhs,
rhs,
gap: operator,
} => {
let op = *op;
let mut merged = Obs::default();
for bin in &self.binaries {
merged.merge(&bin.trace.merged(id));
}
// The types of the operands, where every binary that recorded them
// agrees (a type can be another under `cfg(test)`).
let mut recorded = self.binaries.iter().filter_map(|b| b.trace.bounds.get(&id));
let bounds = recorded
.next()
.filter(|first| recorded.all(|other| other == *first));
// Compared with a number, what cannot be every number has a gap only
// where a value it can be lies between the values the tests gave it,
// and another outcome only if a value it can be gives one.
// Only for an operation of the language: one a type defines for itself
// (`impl Mul<u32> for Eighths`) can give any number.
let against = match literal {
LiteralSide::Rhs(number) => {
Some((lhs, (site.start, operator.0), *number, true))
}
LiteralSide::Lhs(number) => Some((rhs, (operator.1, site.end), *number, false)),
LiteralSide::None => None,
}
.and_then(|(expr, (from, to), number, is_rhs)| {
let (reach, shift) = instrument::reach(expr)?;
// A number past the values of the type it is compared with is
// another number there: nothing is read from how it is written.
let (low, high) = bounds.map(|b| if is_rhs { b.lhs } else { b.rhs })?;
if number < low || number > high {
return None;
}
// A shift by the width of its type or more is a shift by less when
// overflow is not checked: the type says by how much.
let reach = match shift {
Some(bits) => plan::Reach::of_shift(
bits,
bounds.map(|b| if is_rhs { b.lhs } else { b.rhs })?,
)?,
None => reach,
};
// A literal past the largest value of the type is another number
// there (`255i8` is -1 where that is allowed): nothing is read from it.
// Without the type nothing is read from it. A shift was checked
// against the width already (its stride need not be a value).
let fits = |value: i128| {
bounds.is_some_and(|b| value <= if is_rhs { b.lhs.1 } else { b.rhs.1 })
};
let (plan::Reach::Multiples(value)
| plan::Reach::Bits(value)
| plan::Reach::Below(value)) = reach;
((shift.is_some() || fits(value)) && primitive(from, to))
.then_some((reach, number, is_rhs))
});
let mut domain = domain_of(*literal, bounds);
// Between the least and the greatest value it can be: by what it is
// (a mask, a remainder), or within its type (the multiples).
let ends = against.and_then(|(reach, _, is_rhs)| {
reach.interval().or_else(|| {
let (low, high) = bounds.map(|b| if is_rhs { b.lhs } else { b.rhs })?;
reach.within(low, high)
})
});
if let Some((_, number, is_rhs)) = against
&& let Some((low, high)) = ends
&& let (Some(a), Some(b)) = if is_rhs {
(low.checked_sub(number), high.checked_sub(number))
} else {
(number.checked_sub(high), number.checked_sub(low))
}
{
domain = Some(match domain {
Some((lo, hi)) => (lo.max(a), hi.min(b)),
None => (a, b),
});
}
let mut cmp_plan = plan::plan_cmp(op, &merged, domain);
if let Some((reach, number, is_rhs)) = against
&& let Some(gap) = cmp_plan.gap.take()
{
// Equal to a number it cannot be: there is no other outcome.
if matches!(op, plan::CmpOp::Eq | plan::CmpOp::Ne)
&& !reach.holds(number)
&& matches!(gap, plan::InputGap::OneSided { .. })
{
cmp_plan.cannot_differ = true;
} else {
cmp_plan.gap = plan::within_reach(gap, op, &merged, reach, number, is_rhs);
}
}
let mut gaps = vec![];
let mut constant = false;
match &cmp_plan.gap {
Some(plan::InputGap::Unreached) => return Planned::Unreached,
Some(gap) => {
constant = matches!(gap, plan::InputGap::OneSided { .. });
if let Some(finding) =
report::input_gap_finding(file, site, gap, &merged, verify)
{
gaps.push(PlannedGap {
finding,
survivors: gap.survivors(),
constant_expr: None,
});
}
}
None => {}
}
SitePlan {
gaps,
constant,
cannot_differ: cmp_plan.cannot_differ,
redundant_logic_swap: false,
run: cmp_plan.run,
infected: Box::new(move |bin, m| {
tests_where(bin.trace.cmp.get(&id), |obs| plan::infects(op, m, obs))
}),
reaching: Box::new(move |bin| {
tests_where(bin.trace.cmp.get(&id), Obs::reached)
}),
}
}
SiteKind::Logic {
and,
lhs,
rhs,
gap: op_gap,
} => {
let and = *and;
let lhs_range = core_range(site.start, lhs);
let rhs_range = core_range(op_gap.1, rhs);
let merged = self.merged(|t| t.logic.get(&id), plan::LogicObs::merge);
let logic_plan = plan::plan_logic(and, &merged);
if logic_plan.gaps.contains(&plan::LogicGap::Unreached) {
return Planned::Unreached;
}
let gaps: Vec<_> = logic_plan
.gaps
.iter()
.filter_map(|gap| {
// "The operand never decides" is the same statement as "the operand
// had one value whenever it was evaluated".
let (mutation, operand) = match gap {
plan::LogicGap::RhsNeverDecides => (Mutation::LogicDropRhs, rhs_range),
_ => (Mutation::LogicDropLhs, lhs_range),
};
Some(PlannedGap {
finding: report::logic_gap_finding(file, site, *gap, verify)?,
survivors: vec![mutation],
constant_expr: Some(operand),
})
})
.collect();
SitePlan {
constant: merged.constant_value(and).is_some(),
cannot_differ: false,
redundant_logic_swap: merged.swap_never_changes_value(and)
&& instrument::is_pure_logic_operand(rhs),
gaps,
run: logic_plan.run,
infected: Box::new(move |bin, m| {
tests_where(bin.trace.logic.get(&id), |obs| {
plan::logic_infects(and, m, obs)
})
}),
reaching: Box::new(move |bin| {
tests_where(bin.trace.logic.get(&id), plan::LogicObs::reached)
}),
}
}
SiteKind::Arith { .. }
| SiteKind::MinMax { .. }
| SiteKind::SliceEnd { .. }
| SiteKind::StrAffix { .. }
| SiteKind::StrReplace { .. }
| SiteKind::Clamp { .. }
| SiteKind::Rounding { .. }
| SiteKind::SaturatingArith { .. }
| SiteKind::StrTrim { .. }
| SiteKind::StrCaseEq { .. }
| SiteKind::Abs { .. }
| SiteKind::IterLimit { .. }
| SiteKind::EndianSwap { .. }
| SiteKind::BitCount { .. } => {
// `max` / `min` and other value-aware method probes share the 1- or 2-slot
// `ArithObs` recording protocol: they agree when the original and replacement
// compute identical values on every observed input.
let merged = self.merged(|t| t.arith.get(&id), plan::ArithObs::merge);
let mutations: Vec<(Mutation, plan::ArithObs)> = match &site.kind {
SiteKind::MinMax { .. } => vec![(Mutation::MinMax, merged)],
SiteKind::SliceEnd { .. } => vec![(Mutation::OtherEnd, merged)],
SiteKind::StrAffix { .. } => vec![(Mutation::StrContains, merged)],
SiteKind::StrReplace { .. } => {
vec![(Mutation::StrReplaceMultiplicity, merged)]
}
SiteKind::Clamp { .. } => vec![
(Mutation::ClampDropLower, merged),
(Mutation::ClampDropUpper, merged.second()),
],
SiteKind::Rounding { .. } => vec![
(Mutation::RoundAlt1, merged),
(Mutation::RoundAlt2, merged.second()),
],
SiteKind::SaturatingArith { .. } => vec![(Mutation::SaturatingSwap, merged)],
SiteKind::StrTrim { op, .. } => {
let mut out = vec![(Mutation::TrimAlt1, merged)];
if op.alt2().is_some() {
out.push((Mutation::TrimAlt2, merged.second()));
}
out
}
SiteKind::StrCaseEq { .. } => vec![(Mutation::StrExactEq, merged)],
SiteKind::Abs { .. } => vec![(Mutation::DropAbs, merged)],
SiteKind::IterLimit { .. } => vec![(Mutation::IterLimitDrop, merged)],
SiteKind::EndianSwap { .. } => vec![(Mutation::EndianSwap, merged)],
SiteKind::BitCount { .. } => vec![(Mutation::BitCountSwap, merged)],
SiteKind::Arith {
op,
assign,
lhs,
rhs,
gap,
local_types,
shadowed_prims,
..
} if op.second(*assign).is_some() => {
let disjoint_or_xor = !*assign
&& !merged.differs2
&& matches!(
op,
instrument::ArithOp::BitOr | instrument::ArithOp::BitXor
)
&& {
let mut recorded =
self.binaries.iter().filter_map(|b| b.trace.bounds.get(&id));
let bounds = recorded
.next()
.filter(|first| recorded.all(|other| other == *first))
.map(|b| b.lhs);
instrument::disjoint_bits(
lhs,
site.start,
rhs,
gap.1,
bounds,
primitive,
local_types,
shadowed_prims,
cast_bounds,
)
};
if disjoint_or_xor {
vec![(Mutation::ArithSwap, merged)]
} else {
vec![
(Mutation::ArithSwap, merged),
(Mutation::ArithSwap2, merged.second()),
]
}
}
_ => vec![(Mutation::ArithSwap, merged)],
};
// A `first()` that did not give the first element of the sequence is a
// method of another name's making: its `last()` is anyone's guess.
if matches!(
site.kind,
SiteKind::SliceEnd { .. }
| SiteKind::StrAffix { .. }
| SiteKind::StrReplace { .. }
| SiteKind::Clamp { .. }
| SiteKind::Rounding { .. }
| SiteKind::SaturatingArith { .. }
| SiteKind::StrTrim { .. }
| SiteKind::StrCaseEq { .. }
| SiteKind::Abs { .. }
| SiteKind::IterLimit { .. }
| SiteKind::EndianSwap { .. }
| SiteKind::BitCount { .. }
) && merged.opaque
{
return Planned::Nothing;
}
let (mut gaps, mut run) = (vec![], vec![]);
for (mutation, seen) in mutations {
match plan::plan_arith(&seen) {
plan::ArithPlan::Unreached => return Planned::Unreached,
// Not numbers (`String + &str`, `Duration + Duration`): nothing to mutate.
plan::ArithPlan::Opaque => return Planned::Nothing,
plan::ArithPlan::NeverDiffers => {
let finding = match mutation {
Mutation::MinMax => report::min_max_gap_finding(file, site, verify),
Mutation::OtherEnd => {
report::slice_end_gap_finding(file, site, verify)
}
Mutation::StrContains => {
report::str_affix_gap_finding(file, site, verify)
}
Mutation::StrReplaceMultiplicity => {
report::str_replace_gap_finding(file, site, verify)
}
Mutation::ClampDropLower | Mutation::ClampDropUpper => {
report::clamp_gap_finding(file, site, mutation, verify)
}
Mutation::RoundAlt1 | Mutation::RoundAlt2 => {
report::rounding_gap_finding(file, site, mutation, verify)
}
Mutation::SaturatingSwap => {
report::saturating_gap_finding(file, site, verify)
}
Mutation::TrimAlt1 | Mutation::TrimAlt2 => {
report::str_trim_gap_finding(file, site, mutation, verify)
}
Mutation::StrExactEq => {
report::str_case_eq_gap_finding(file, site, verify)
}
Mutation::DropAbs => report::abs_gap_finding(file, site, verify),
Mutation::IterLimitDrop => {
report::iter_limit_gap_finding(file, site, verify)
}
Mutation::EndianSwap => {
report::endian_gap_finding(file, site, verify)
}
Mutation::BitCountSwap => {
report::bit_count_gap_finding(file, site, verify)
}
_ => report::arith_gap_finding(file, site, mutation, verify),
};
gaps.extend(finding.map(|finding| PlannedGap {
finding,
survivors: vec![mutation],
constant_expr: None,
}));
}
plan::ArithPlan::Run => run.push(mutation),
}
}
SitePlan {
gaps,
constant: false,
cannot_differ: false,
redundant_logic_swap: false,
run,
infected: Box::new(move |bin, m| {
tests_where(bin.trace.arith.get(&id), |obs| obs.infected_by(m))
}),
reaching: Box::new(move |bin| {
tests_where(bin.trace.arith.get(&id), |obs| {
obs.same || obs.differs || obs.same2 || obs.differs2
})
}),
}
}
SiteKind::Return {
sole_expr, option, ..
} => {
let sole_expr = *sole_expr;
let is_option = option.is_some();
let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
let return_plan = if is_option {
plan::plan_option_return(&merged)
} else {
plan::plan_return(&merged)
};
if return_plan.unreached {
return Planned::Unreached;
}
let gaps: Vec<_> = return_plan
.always
.and_then(|always| {
Some(PlannedGap {
finding: report::return_gap_finding(file, site, always, verify)?,
survivors: vec![Mutation::Const(always)],
// A body that is one expression returns that expression's value.
constant_expr: sole_expr,
})
})
.into_iter()
.collect();
SitePlan {
constant: false,
cannot_differ: false,
redundant_logic_swap: false,
gaps,
run: return_plan.run,
infected: Box::new(move |bin, m| {
tests_where(bin.trace.returns.get(&id), |obs| match m {
Mutation::Const(value) => obs.infected_by_const(value),
_ => obs.reached(),
})
}),
reaching: Box::new(move |bin| {
tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
}),
}
}
})
}
pub(super) fn job(
&self,
site: u32,
mutation: Mutation,
tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>,
) -> Job {
let tests = self
.binaries
.iter()
.enumerate()
.filter_map(|(index, bin)| {
let tests = tests_of(bin);
if tests.is_empty() {
return None;
}
let filter = match bin.runner {
Runner::Exe(_) => test_filter(&tests, &bin.tests),
Runner::Doc { .. } | Runner::Isolated { .. } | Runner::Nextest { .. } => None,
};
Some((index, filter))
})
.collect();
Job {
site,
mutation,
tests,
}
}
/// Runs one mutant against its tests, stopping at the first test that fails.
/// Runs one mutant while `sharing` jobs run at the same time.
pub(super) fn run_job(&self, job: &Job, sharing: usize) -> Result<JobResult> {
let spec = format!("{}:{}", job.site, job.mutation.encode());
let mut passed = vec![];
// One failure is enough: the quick binaries first.
let mut tests: Vec<&(usize, Option<Vec<String>>)> = job.tests.iter().collect();
tests.sort_by_key(|(index, _)| self.binaries[*index].baseline);
for (index, filter) in tests {
let bin = &self.binaries[*index];
let outcome = run_binary(
bin,
filter.as_deref(),
&[("TMT_MUTANT", &spec)],
bin.filtered_limit(filter.as_deref(), false, sharing),
RunOutput::FirstFailure,
sharing,
)?;
if outcome != Outcome::Pass {
return Ok(JobResult {
first_pass_timeout: false,
unconfirmed_timeout: false,
survived: None,
timed_out: outcome == Outcome::Timeout,
unable: outcome == Outcome::Unable,
});
}
match filter {
Some(names) => passed.extend(names.iter().cloned()),
None if matches!(bin.runner, Runner::Isolated { .. }) => {
passed.push(bin.name.clone())
}
None => passed.push(format!("all tests of `{}`", bin.name)),
}
}
Ok(JobResult {
first_pass_timeout: false,
unconfirmed_timeout: false,
survived: Some(passed),
timed_out: false,
unable: false,
})
}
/// Runs a surviving mutant once more with tracing on, and returns what it changed in
/// each test compared with the original run.
pub(super) fn trace_job(
&self,
job: &Job,
scratch: &Path,
sharing: usize,
) -> Result<BTreeMap<String, BTreeSet<Change>>> {
let spec = format!("{}:{}", job.site, job.mutation.encode());
let mut all: BTreeMap<String, BTreeSet<Change>> = BTreeMap::new();
for (index, filter) in &job.tests {
let bin = &self.binaries[*index];
let path = scratch.join(format!("effects-{}-{index}.tsv", job.site));
let _ = fs::remove_file(&path);
let trace_env = path.to_string_lossy().into_owned();
let outcome = run_binary(
bin,
filter.as_deref(),
&[("TMT_MUTANT", &spec), ("TMT_TRACE", &trace_env)],
bin.filtered_limit(filter.as_deref(), true, sharing),
RunOutput::Quiet,
sharing,
)?;
let text = fs::read_to_string(&path).unwrap_or_default();
let _ = fs::remove_file(&path);
if outcome != Outcome::Pass {
continue; // not the run we saw before: say nothing rather than guess
}
let mutated = Trace::parse(&text);
let ran: Option<BTreeSet<String>> =
filter.as_ref().map(|names| names.iter().cloned().collect());
let baseline = bin
.effects_baseline
.get_or_init(|| propagation::BaselineIndex::new(&bin.trace));
for (test, found) in baseline.changes(&mutated, ran.as_ref(), job.site) {
all.entry(test).or_default().extend(found);
}
}
Ok(all)
}
/// Runs every job exactly once on `workers` threads (formal/tla/JobPool.tla) and
/// returns the results in job order.
/// Runs the mutants, `workers` at a time. A mutant that ran out of time while others
/// were running may only have been slowed down by them: it gets a second run on its
/// own, and that one counts.
pub(super) fn run_jobs(
&self,
jobs: &[Job],
workers: usize,
label: &str,
checkpoint: Option<&Phase<'_>>,
) -> Result<Vec<JobResult>> {
if self
.binaries
.first()
.is_some_and(|bin| bin.timeout.is_some())
{
for (index, filter) in jobs.iter().flat_map(|job| &job.tests) {
self.binaries[*index].warn_timeout_conflict(filter.as_deref());
}
}
if workers > 1 {
// Measure unique slow filtered baselines serially for uncached jobs before
// spawning parallel workers, using the same thread-sharing budget that the
// parallel pool will use so timings are neither contended nor optimistic.
let pending: Vec<usize> = (0..jobs.len())
.filter(|&index| {
checkpoint
.is_none_or(|phase| phase.get::<JobResult>(index).ok().flatten().is_none())
})
.collect();
if pending.len() > 1 {
let parallel_sharing = workers.clamp(1, jobs.len().max(1));
for index in pending {
for (bin_index, filter) in &jobs[index].tests {
self.binaries[*bin_index].filtered_limit(
filter.as_deref(),
false,
parallel_sharing,
);
}
}
}
}
let run = |index: usize, sharing| self.run_job(&jobs[index], sharing);
evaluate_jobs(
jobs.len(),
workers,
self.serial_timeout_rechecks,
self.progress,
label,
checkpoint,
&run,
)
}
}
pub(super) fn evaluate_jobs(
count: usize,
workers: usize,
serial_rechecks: bool,
progress_enabled: bool,
label: &str,
checkpoint: Option<&Phase<'_>>,
run: &(impl Fn(usize, usize) -> Result<JobResult> + Sync),
) -> Result<Vec<JobResult>> {
let sharing = workers.clamp(1, count.max(1));
let mut results = progress::track(progress_enabled, label, count, |progress| {
run_pool(count, workers, |index| {
if let Some(cached) = checkpoint
.map(|phase| phase.get::<JobResult>(index))
.transpose()?
.flatten()
{
progress.complete(cached.progress_outcome());
return Ok((cached, false));
}
let mut result = run(index, sharing)?;
if sharing > 1 && result.timed_out {
result.first_pass_timeout = true;
result.unconfirmed_timeout = true;
}
let pending = result.unconfirmed_timeout && serial_rechecks;
if !pending {
if let Some(phase) = checkpoint {
phase.record(index, &result)?;
}
progress.complete(result.progress_outcome());
}
Ok((result, pending))
})
})?;
let pending: Vec<_> = results
.iter()
.enumerate()
.filter_map(|(index, (_, pending))| pending.then_some(index))
.collect();
if !pending.is_empty() && progress_enabled {
eprintln!(
"tmt: {label}: {} first-pass timeouts, {} pending serial rechecks",
pending.len(),
if serial_rechecks { pending.len() } else { 0 }
);
}
if serial_rechecks {
progress::track_timeout_rechecks(progress_enabled, pending.len(), |progress| {
for index in pending {
let mut confirmed = run(index, 1)?;
confirmed.first_pass_timeout = true;
let outcome = if confirmed.timed_out {
progress::Outcome::TimedOut
} else if confirmed.unable {
progress::Outcome::Unable
} else {
progress::Outcome::Survived
};
if let Some(phase) = checkpoint {
phase.record(index, &confirmed)?;
}
results[index] = (confirmed, false);
progress.complete(outcome);
}
Ok::<_, anyhow::Error>(())
})?;
}
if let Some(phase) = checkpoint {
phase.finish()?;
}
Ok(results.into_iter().map(|(result, _)| result).collect())
}
/// Tests that reached a `match` guard (either returning a bool or exiting early).
fn guard_reaching_tests(bin: &TestBinary, id: u32) -> BTreeSet<String> {
let mut tests = tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached);
if let Some(reached) = bin.trace.reach.get(&id) {
tests.extend(reached.iter().cloned());
}
tests
}
/// Strictly side-effect-free guard expression: no calls, no methods, no indexing, no
/// `Deref` (including implicit field `Deref`), and no user-overloaded operators (including
/// `!`). A top-level binary comparison is accepted only when runtime `trace.bounds` proved
/// it compared primitive numbers/chars and both operands are plain literals or paths.
fn is_strictly_pure_guard(expr_text: &str, is_prim_cmp: bool) -> bool {
fn is_trivial_value(expr: &syn::Expr) -> bool {
match expr {
syn::Expr::Lit(_) | syn::Expr::Path(_) => true,
syn::Expr::Paren(e) => is_trivial_value(&e.expr),
syn::Expr::Group(e) => is_trivial_value(&e.expr),
_ => false,
}
}
let Ok(expr) = syn::parse_str::<syn::Expr>(expr_text) else {
return false;
};
if is_trivial_value(&expr) {
return true;
}
if is_prim_cmp
&& let syn::Expr::Binary(bin) = &expr
&& is_trivial_value(&bin.left)
&& is_trivial_value(&bin.right)
{
return true;
}
false
}
impl std::str::FromStr for report::Shard {
type Err = anyhow::Error;
fn from_str(text: &str) -> Result<Self> {
let (index, count) = text.split_once('/').context("expected a shard index K/N")?;
let index: usize = index.parse().context("invalid shard index")?;
let count: usize = count.parse().context("invalid shard count")?;
if index >= count {
bail!("shard index must be less than the shard count");
}
Ok(Self {
index,
count,
round_robin: false,
})
}
}
impl report::Shard {
pub(super) fn contains(self, candidate: usize, candidates: usize) -> bool {
candidate < candidates
&& (if self.round_robin {
candidate % self.count
} else {
candidate / candidates.div_ceil(self.count)
}) == self.index
}
}