Skip to main content

fallow_api/mutation/scheduler/
control.rs

1//! Control runs: runs of covering tests with no active mutant. A kill with
2//! no executed test, and a kill in a survivor retry by a test that the first
3//! run did not execute, need a control run of their tests. The module also
4//! records the baseline failures of control runs and of the dry runs of
5//! restarted companions.
6
7use std::collections::BTreeMap;
8use std::sync::{Arc, Mutex};
9
10use rustc_hash::{FxHashMap, FxHashSet};
11
12use super::super::protocol::{RunResult, RunStatus, TestStatus};
13use super::dry_facts::bounded_test_error;
14use super::{BaselineFailure, DryRunFacts, ScheduleOutcome};
15
16/// Why a control run did not pass.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub(super) struct ControlFault {
19    /// The run executed no test: the run path is broken.
20    pub(super) no_tests: bool,
21    /// The requested tests that ran and failed. A failed test is a baseline
22    /// failure of the run, not a fault of the run path.
23    pub(super) failed_tests: Vec<FailedTest>,
24    pub(super) detail: String,
25}
26
27/// A test that failed in a control run.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub(super) struct FailedTest {
30    pub(super) test_id: String,
31    /// The error of the test from the companion. An older companion sends
32    /// none.
33    pub(super) error: Option<String>,
34}
35
36impl FailedTest {
37    /// The message of the baseline failure of this test: `reason`, then the
38    /// error of the test. The first line then has the reason and the first
39    /// line of the error, and the stack follows. With no error, the message
40    /// is `reason`.
41    pub(super) fn message(&self, reason: &str) -> String {
42        self.error
43            .as_deref()
44            .and_then(bounded_test_error)
45            .map_or_else(|| reason.to_owned(), |error| format!("{reason}: {error}"))
46    }
47}
48
49impl ControlFault {
50    pub(super) fn untrusted(detail: String) -> Self {
51        Self {
52            no_tests: false,
53            failed_tests: Vec::new(),
54            detail,
55        }
56    }
57}
58
59/// Checks the result of a control run of `tests` with no active mutant. Each
60/// requested test must run and pass, with no error.
61pub(super) fn control_fault(tests: &[String], result: &RunResult) -> Option<ControlFault> {
62    let first_error = result
63        .unhandled_errors
64        .first()
65        .map(|error| format!("; first error: {}", first_line(&error.message)));
66    if result.tests_executed == 0 {
67        return Some(ControlFault {
68            no_tests: true,
69            failed_tests: Vec::new(),
70            detail: format!(
71                "0 of {} requested tests ran{}",
72                tests.len(),
73                first_error.unwrap_or_default()
74            ),
75        });
76    }
77    if let Some(id) = &result.mutant_id {
78        return Some(ControlFault::untrusted(format!(
79            "the run result names mutant `{id}`, expected none"
80        )));
81    }
82    let requested: FxHashSet<&str> = tests.iter().map(String::as_str).collect();
83    let failed_tests: Vec<FailedTest> = result
84        .tests
85        .iter()
86        .filter(|test| test.status == TestStatus::Fail && requested.contains(test.test_id.as_str()))
87        .map(|test| FailedTest {
88            test_id: test.test_id.clone(),
89            error: test.message.clone(),
90        })
91        .collect();
92    if let Some(first) = failed_tests.first() {
93        return Some(ControlFault {
94            no_tests: false,
95            detail: format!("the test `{}` failed", first.test_id),
96            failed_tests,
97        });
98    }
99    if let Some(first_error) = first_error {
100        return Some(ControlFault::untrusted(format!(
101            "the run reported an error{first_error}"
102        )));
103    }
104    let passed: FxHashSet<&str> = result
105        .tests
106        .iter()
107        .filter(|test| test.status == TestStatus::Pass)
108        .map(|test| test.test_id.as_str())
109        .collect();
110    if result.status != RunStatus::Survived
111        || result.tests_executed != tests.len()
112        || tests.iter().any(|test| !passed.contains(test.as_str()))
113    {
114        return Some(ControlFault::untrusted(format!(
115            "{} of {} requested tests ran and passed",
116            passed.len(),
117            tests.len()
118        )));
119    }
120    None
121}
122
123/// The message of a test that fails in a control run. The dry run runs the
124/// whole test file, and a mutant run runs only the covering tests.
125pub(super) const CONTROL_RUN_FAILURE: &str = "the test fails in a mutant run with no active mutant, but passed in the dry run of its whole file; it can depend on another test of its file";
126
127/// The message of a test that fails in the control run of a survivor retry.
128/// That run already has each passing test of the file, so a missing covering
129/// test is not the cause.
130pub(super) const CONFIRMATION_RUN_FAILURE: &str = "the test fails with no active mutant in a run of each test of its file that passed in the dry run, but passed in the dry run of its whole file; it can depend on a test of its file that failed or was skipped in the dry run, or it can be flaky";
131
132/// The message of a covering test that did not pass in the dry run of a
133/// restarted companion.
134pub(super) const RESTARTED_DRY_RUN_FAILURE: &str =
135    "the test did not pass in the dry run of a restarted companion";
136
137const PARALLEL_STATE_HINT: &str = "; try --concurrency 1 or set mutation.concurrency to 1; parallel companions may share files or a database";
138
139pub(super) const fn parallel_state_hint(workers: usize) -> &'static str {
140    if workers > 1 { PARALLEL_STATE_HINT } else { "" }
141}
142
143/// Splits the message of a baseline failure from a control run or from the
144/// dry run of a restarted companion into its fixed reason and the test error
145/// after it. Gives `None` for another message or for a reason with no test
146/// error.
147#[must_use]
148pub fn split_control_run_failure(message: &str) -> Option<(&str, &str)> {
149    [
150        CONTROL_RUN_FAILURE,
151        CONFIRMATION_RUN_FAILURE,
152        RESTARTED_DRY_RUN_FAILURE,
153    ]
154    .into_iter()
155    .find_map(|reason| {
156        let rest = message.strip_prefix(reason)?;
157        let rest = rest.strip_prefix(PARALLEL_STATE_HINT).unwrap_or(rest);
158        let error = rest.strip_prefix(": ")?;
159        Some((&message[..message.len() - rest.len()], error))
160    })
161}
162
163/// The first line of `message`.
164pub(super) fn first_line(message: &str) -> &str {
165    message.lines().next().unwrap_or_default()
166}
167
168/// The result of a control run.
169pub(super) enum ControlOutcome {
170    Passed,
171    Failed(ControlFault),
172    /// The companion did not give a run result.
173    Fault(String),
174    /// A test or the companion passed the timeout of the control run.
175    TimedOut(String),
176}
177
178/// `tests`, sorted.
179pub(super) fn sorted_tests(tests: &[String]) -> Vec<&str> {
180    let mut sorted: Vec<&str> = tests.iter().map(String::as_str).collect();
181    sorted.sort_unstable();
182    sorted
183}
184
185/// The stored control result of one test set.
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub(super) enum ControlVerdict {
188    /// The tests pass with no active mutant.
189    Passed,
190    /// A test failed with no active mutant.
191    Failed,
192    /// The control run timed out, with the reason. A later control run of
193    /// the same tests would wait as long again.
194    TimedOut(String),
195}
196
197/// The control evidence about one test set, from the memo or from a new
198/// control run.
199pub(super) enum ControlCheck {
200    /// The tests pass with no active mutant.
201    Passed,
202    /// The tests do not pass with no active mutant, with the reason. A
203    /// `settled` check is a fact about the tests. A fault of the companion is
204    /// not settled.
205    Failed { detail: String, settled: bool },
206    /// The time budget ended before a control run.
207    NoTime,
208}
209
210/// The control result of one test set: `None` before a control run gave a
211/// result.
212pub(super) type ControlCell = Arc<Mutex<Option<ControlVerdict>>>;
213
214/// The control result of each test set within one run. A mutant kill with
215/// no executed test needs a control run of its tests, and each test set gets
216/// at most one. A timeout is stored, so a hanging test set costs one control
217/// run. A fault of the companion is not stored, so a later mutant with the
218/// same tests runs the control again. The memo also keeps the tests
219/// that failed in a control run, each with the message of its baseline
220/// failure: each later mutant run leaves them out. It also keeps the first
221/// error of each test that failed in the dry run of a restarted companion,
222/// for the baseline failure of that test.
223#[derive(Default)]
224pub(super) struct ControlMemo {
225    entries: Mutex<FxHashMap<Vec<String>, ControlCell>>,
226    pub(super) failed_tests: Mutex<BTreeMap<String, String>>,
227    restarted_dry_run_errors: Mutex<BTreeMap<String, String>>,
228}
229
230impl ControlMemo {
231    /// The cell of `tests`. A thread that holds the lock of the cell runs
232    /// the control, and each other thread with the same tests waits for it.
233    pub(super) fn cell(&self, tests: &[String]) -> ControlCell {
234        let mut key = tests.to_vec();
235        key.sort_unstable();
236        let Ok(mut entries) = self.entries.lock() else {
237            return Arc::new(Mutex::new(None));
238        };
239        Arc::clone(entries.entry(key).or_default())
240    }
241
242    pub(super) fn store(&self, tests: &[String], verdict: ControlVerdict) {
243        if let Ok(mut cell) = self.cell(tests).lock() {
244            *cell = Some(verdict);
245        }
246    }
247
248    /// Marks `tests` as failed for `reason`. The first message of a test
249    /// stays.
250    pub(super) fn mark_failed(&self, tests: &[FailedTest], reason: &str) {
251        if let Ok(mut failed) = self.failed_tests.lock() {
252            for test in tests {
253                failed
254                    .entry(test.test_id.clone())
255                    .or_insert_with(|| test.message(reason));
256            }
257        }
258    }
259
260    pub(super) fn is_failed(&self, test: &str) -> bool {
261        self.failed_tests
262            .lock()
263            .is_ok_and(|failed| failed.contains_key(test))
264    }
265
266    /// Keeps the error of `test` from the dry run of a restarted companion.
267    /// The first error of a test stays.
268    pub(super) fn note_restarted_dry_run_error(&self, test: &str, error: &str) {
269        if let Ok(mut errors) = self.restarted_dry_run_errors.lock()
270            && !errors.contains_key(test)
271        {
272            errors.insert(test.to_owned(), error.to_owned());
273        }
274    }
275
276    /// The first error of `test` from the dry run of a restarted companion.
277    pub(super) fn restarted_dry_run_error(&self, test: &str) -> Option<String> {
278        self.restarted_dry_run_errors
279            .lock()
280            .ok()
281            .and_then(|errors| errors.get(test).cloned())
282    }
283
284    /// Each failed test with the message of its baseline failure.
285    pub(super) fn failed(&self) -> BTreeMap<String, String> {
286        self.failed_tests
287            .lock()
288            .map(|failed| failed.clone())
289            .unwrap_or_default()
290    }
291}
292
293/// Records `test` as a baseline failure of a restarted companion that
294/// affected `mutant_id`. The mutant ran with its other covering tests. The
295/// message keeps the first error of the test from the dry run of a
296/// restarted companion, when the companion sent one.
297pub(super) fn note_restarted_baseline_failure(
298    workers: usize,
299    outcome: &mut ScheduleOutcome,
300    facts: &DryRunFacts,
301    memo: &ControlMemo,
302    test: String,
303    mutant_id: &str,
304) {
305    if let Some(failure) = outcome
306        .baseline_failures
307        .iter_mut()
308        .find(|failure| failure.test_id.as_deref() == Some(test.as_str()))
309    {
310        failure.mutant_ids.push(mutant_id.to_owned());
311        return;
312    }
313    outcome.baseline_failures.push(BaselineFailure {
314        file: facts.passing.get(&test).map(|(file, _)| file.clone()),
315        message: Some(
316            FailedTest {
317                error: memo.restarted_dry_run_error(&test),
318                test_id: test.clone(),
319            }
320            .message(&format!(
321                "{RESTARTED_DRY_RUN_FAILURE}{}",
322                parallel_state_hint(workers)
323            )),
324        ),
325        test_id: Some(test),
326        mutant_ids: vec![mutant_id.to_owned()],
327    });
328}
329
330/// Adds each test that failed in a control run during the mutant runs as a
331/// baseline failure. [`super::record`] then adds the mutants that ran without it.
332pub(super) fn note_control_failures(
333    outcome: &mut ScheduleOutcome,
334    facts: &DryRunFacts,
335    memo: &ControlMemo,
336) {
337    for (test, message) in memo.failed() {
338        if outcome
339            .baseline_failures
340            .iter()
341            .any(|failure| failure.test_id.as_deref() == Some(test.as_str()))
342        {
343            continue;
344        }
345        outcome.baseline_failures.push(BaselineFailure {
346            file: facts.passing.get(&test).map(|(file, _)| file.clone()),
347            test_id: Some(test),
348            message: Some(message),
349            mutant_ids: Vec::new(),
350        });
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn a_control_run_failure_message_splits_into_its_reason_and_the_test_error() {
360        let error = "AssertionError: expected 1 to be 2\n    at test/a.test.ts:3:5";
361        let test = FailedTest {
362            test_id: "test/a.test.ts::adds".to_owned(),
363            error: Some(error.to_owned()),
364        };
365        for reason in [
366            CONTROL_RUN_FAILURE,
367            CONFIRMATION_RUN_FAILURE,
368            RESTARTED_DRY_RUN_FAILURE,
369        ] {
370            let message = test.message(reason);
371            assert_eq!(split_control_run_failure(&message), Some((reason, error)));
372        }
373        let no_error = FailedTest {
374            error: None,
375            ..test
376        };
377        assert_eq!(
378            split_control_run_failure(&no_error.message(CONTROL_RUN_FAILURE)),
379            None
380        );
381        assert_eq!(
382            split_control_run_failure("Cannot find module './setup'"),
383            None
384        );
385    }
386}