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
148/// The longest test error that a baseline failure keeps, in bytes. The
149/// companion bounds the error too. This bound guards the pipe from the
150/// companion.
151const MAX_TEST_ERROR_BYTES: usize = 8 * 1024;
152
153/// Splits the message of a baseline failure from a control run or from the
154/// dry run of a restarted companion into its fixed reason and the test error
155/// after it. Gives `None` for another message or for a reason with no test
156/// error.
157#[must_use]
158pub fn split_control_run_failure(message: &str) -> Option<(&str, &str)> {
159    [
160        CONTROL_RUN_FAILURE,
161        CONFIRMATION_RUN_FAILURE,
162        RESTARTED_DRY_RUN_FAILURE,
163    ]
164    .into_iter()
165    .find_map(|reason| {
166        let error = message.strip_prefix(reason)?.strip_prefix(": ")?;
167        Some((reason, error))
168    })
169}
170
171/// The first line of `message`.
172pub(super) fn first_line(message: &str) -> &str {
173    message.lines().next().unwrap_or_default()
174}
175
176/// The result of a control run.
177pub(super) enum ControlOutcome {
178    Passed,
179    Failed(ControlFault),
180    /// The companion did not give a run result.
181    Fault(String),
182    /// A test or the companion passed the timeout of the control run.
183    TimedOut(String),
184}
185
186/// `tests`, sorted.
187pub(super) fn sorted_tests(tests: &[String]) -> Vec<&str> {
188    let mut sorted: Vec<&str> = tests.iter().map(String::as_str).collect();
189    sorted.sort_unstable();
190    sorted
191}
192
193/// The stored control result of one test set.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub(super) enum ControlVerdict {
196    /// The tests pass with no active mutant.
197    Passed,
198    /// A test failed with no active mutant.
199    Failed,
200    /// The control run timed out, with the reason. A later control run of
201    /// the same tests would wait as long again.
202    TimedOut(String),
203}
204
205/// The control evidence about one test set, from the memo or from a new
206/// control run.
207pub(super) enum ControlCheck {
208    /// The tests pass with no active mutant.
209    Passed,
210    /// The tests do not pass with no active mutant, with the reason. A
211    /// `settled` check is a fact about the tests. A fault of the companion is
212    /// not settled.
213    Failed { detail: String, settled: bool },
214    /// The time budget ended before a control run.
215    NoTime,
216}
217
218/// The control result of one test set: `None` before a control run gave a
219/// result.
220pub(super) type ControlCell = Arc<Mutex<Option<ControlVerdict>>>;
221
222/// The control result of each test set within one run. A mutant kill with
223/// no executed test needs a control run of its tests, and each test set gets
224/// at most one. A timeout is stored, so a hanging test set costs one control
225/// run. A fault of the companion is not stored, so a later mutant with the
226/// same tests runs the control again. The memo also keeps the tests
227/// that failed in a control run, each with the message of its baseline
228/// failure: each later mutant run leaves them out. It also keeps the first
229/// error of each test that failed in the dry run of a restarted companion,
230/// for the baseline failure of that test.
231#[derive(Default)]
232pub(super) struct ControlMemo {
233    entries: Mutex<FxHashMap<Vec<String>, ControlCell>>,
234    pub(super) failed_tests: Mutex<BTreeMap<String, String>>,
235    restarted_dry_run_errors: Mutex<BTreeMap<String, String>>,
236}
237
238impl ControlMemo {
239    /// The cell of `tests`. A thread that holds the lock of the cell runs
240    /// the control, and each other thread with the same tests waits for it.
241    pub(super) fn cell(&self, tests: &[String]) -> ControlCell {
242        let mut key = tests.to_vec();
243        key.sort_unstable();
244        let Ok(mut entries) = self.entries.lock() else {
245            return Arc::new(Mutex::new(None));
246        };
247        Arc::clone(entries.entry(key).or_default())
248    }
249
250    pub(super) fn store(&self, tests: &[String], verdict: ControlVerdict) {
251        if let Ok(mut cell) = self.cell(tests).lock() {
252            *cell = Some(verdict);
253        }
254    }
255
256    /// Marks `tests` as failed for `reason`. The first message of a test
257    /// stays.
258    pub(super) fn mark_failed(&self, tests: &[FailedTest], reason: &str) {
259        if let Ok(mut failed) = self.failed_tests.lock() {
260            for test in tests {
261                failed
262                    .entry(test.test_id.clone())
263                    .or_insert_with(|| test.message(reason));
264            }
265        }
266    }
267
268    pub(super) fn is_failed(&self, test: &str) -> bool {
269        self.failed_tests
270            .lock()
271            .is_ok_and(|failed| failed.contains_key(test))
272    }
273
274    /// Keeps the error of `test` from the dry run of a restarted companion.
275    /// The first error of a test stays.
276    pub(super) fn note_restarted_dry_run_error(&self, test: &str, error: &str) {
277        if let Ok(mut errors) = self.restarted_dry_run_errors.lock()
278            && !errors.contains_key(test)
279        {
280            errors.insert(test.to_owned(), error.to_owned());
281        }
282    }
283
284    /// The first error of `test` from the dry run of a restarted companion.
285    pub(super) fn restarted_dry_run_error(&self, test: &str) -> Option<String> {
286        self.restarted_dry_run_errors
287            .lock()
288            .ok()
289            .and_then(|errors| errors.get(test).cloned())
290    }
291
292    /// Each failed test with the message of its baseline failure.
293    pub(super) fn failed(&self) -> BTreeMap<String, String> {
294        self.failed_tests
295            .lock()
296            .map(|failed| failed.clone())
297            .unwrap_or_default()
298    }
299}
300
301/// Records `test` as a baseline failure of a restarted companion that
302/// affected `mutant_id`. The mutant ran with its other covering tests. The
303/// message keeps the first error of the test from the dry run of a
304/// restarted companion, when the companion sent one.
305pub(super) fn note_restarted_baseline_failure(
306    outcome: &mut ScheduleOutcome,
307    facts: &DryRunFacts,
308    memo: &ControlMemo,
309    test: String,
310    mutant_id: &str,
311) {
312    if let Some(failure) = outcome
313        .baseline_failures
314        .iter_mut()
315        .find(|failure| failure.test_id.as_deref() == Some(test.as_str()))
316    {
317        failure.mutant_ids.push(mutant_id.to_owned());
318        return;
319    }
320    outcome.baseline_failures.push(BaselineFailure {
321        file: facts.passing.get(&test).map(|(file, _)| file.clone()),
322        message: Some(
323            FailedTest {
324                error: memo.restarted_dry_run_error(&test),
325                test_id: test.clone(),
326            }
327            .message(RESTARTED_DRY_RUN_FAILURE),
328        ),
329        test_id: Some(test),
330        mutant_ids: vec![mutant_id.to_owned()],
331    });
332}
333
334/// Adds each test that failed in a control run during the mutant runs as a
335/// baseline failure. [`super::record`] then adds the mutants that ran without it.
336pub(super) fn note_control_failures(
337    outcome: &mut ScheduleOutcome,
338    facts: &DryRunFacts,
339    memo: &ControlMemo,
340) {
341    for (test, message) in memo.failed() {
342        if outcome
343            .baseline_failures
344            .iter()
345            .any(|failure| failure.test_id.as_deref() == Some(test.as_str()))
346        {
347            continue;
348        }
349        outcome.baseline_failures.push(BaselineFailure {
350            file: facts.passing.get(&test).map(|(file, _)| file.clone()),
351            test_id: Some(test),
352            message: Some(message),
353            mutant_ids: Vec::new(),
354        });
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    #[test]
363    fn a_control_run_failure_message_splits_into_its_reason_and_the_test_error() {
364        let error = "AssertionError: expected 1 to be 2\n    at test/a.test.ts:3:5";
365        let test = FailedTest {
366            test_id: "test/a.test.ts::adds".to_owned(),
367            error: Some(error.to_owned()),
368        };
369        for reason in [
370            CONTROL_RUN_FAILURE,
371            CONFIRMATION_RUN_FAILURE,
372            RESTARTED_DRY_RUN_FAILURE,
373        ] {
374            let message = test.message(reason);
375            assert_eq!(split_control_run_failure(&message), Some((reason, error)));
376        }
377        let no_error = FailedTest {
378            error: None,
379            ..test
380        };
381        assert_eq!(
382            split_control_run_failure(&no_error.message(CONTROL_RUN_FAILURE)),
383            None
384        );
385        assert_eq!(
386            split_control_run_failure("Cannot find module './setup'"),
387            None
388        );
389    }
390}