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