fallow_api/mutation/scheduler/
control.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
17pub(super) struct ControlFault {
18 pub(super) no_tests: bool,
20 pub(super) failed_tests: Vec<FailedTest>,
23 pub(super) detail: String,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub(super) struct FailedTest {
29 pub(super) test_id: String,
30 pub(super) error: Option<String>,
33}
34
35impl FailedTest {
36 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
48pub(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
70pub(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
134pub(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
138pub(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
143pub(super) const RESTARTED_DRY_RUN_FAILURE: &str =
146 "the test did not pass in the dry run of a restarted companion";
147
148const MAX_TEST_ERROR_BYTES: usize = 8 * 1024;
152
153#[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
171pub(super) fn first_line(message: &str) -> &str {
173 message.lines().next().unwrap_or_default()
174}
175
176pub(super) enum ControlOutcome {
178 Passed,
179 Failed(ControlFault),
180 Fault(String),
182 TimedOut(String),
184}
185
186pub(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#[derive(Debug, Clone, PartialEq, Eq)]
195pub(super) enum ControlVerdict {
196 Passed,
198 Failed,
200 TimedOut(String),
203}
204
205pub(super) enum ControlCheck {
208 Passed,
210 Failed { detail: String, settled: bool },
214 NoTime,
216}
217
218pub(super) type ControlCell = Arc<Mutex<Option<ControlVerdict>>>;
221
222#[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 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 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 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 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 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
301pub(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
334pub(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}