use fallow_output::MutantStatus;
use rustc_hash::FxHashMap;
use super::super::protocol::Ready;
use super::{
Attempt, Job, JobContext, MutantOutcome, ScheduleConfig, ScheduleOutcome, ScheduledMutant,
retries_unique_kill, retry_status,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CachedResult {
pub status: MutantStatus,
pub killed_by: Option<String>,
pub killing_tests: Vec<String>,
pub kill_matrix_complete: bool,
pub duration_ms: Option<u64>,
}
pub trait ResultLookup: std::fmt::Debug + Send + Sync {
fn key(
&self,
ready: &Ready,
mutant: &ScheduledMutant,
tests: &[String],
test_files: &[String],
) -> String;
fn get(&self, mutant_id: &str, key: &str) -> Option<CachedResult>;
}
pub trait OutcomeJournal: std::fmt::Debug + Send + Sync {
fn key(
&self,
ready: &Ready,
mutant: &ScheduledMutant,
tests: &[String],
test_files: &[String],
) -> String;
fn resumed(&self, mutant_id: &str, key: &str) -> Option<CachedResult>;
fn append(&self, mutant_id: &str, key: &str, result: &CachedResult);
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum StoredSource {
Cache,
Journal,
}
fn stored_result(
context: &JobContext<'_>,
key: Option<&String>,
mutant: &ScheduledMutant,
) -> Option<(CachedResult, StoredSource)> {
let key = key?;
let resumed = context
.journal
.and_then(|journal| journal.resumed(&mutant.id, key))
.map(|hit| (hit, StoredSource::Journal));
resumed
.or_else(|| {
context
.cache
.and_then(|cache| cache.get(&mutant.id, key))
.map(|hit| (hit, StoredSource::Cache))
})
.filter(|(hit, _)| !context.collects_evidence() || hit.kill_matrix_complete)
}
fn stored_outcome(
(hit, source): (CachedResult, StoredSource),
tests: &[String],
static_mutant: bool,
) -> MutantOutcome {
let mut covering_tests = tests.to_vec();
covering_tests.sort_unstable();
MutantOutcome {
status: hit.status,
killing_tests: hit.killing_tests,
kill_matrix_complete: hit.kill_matrix_complete,
killed_by: hit.killed_by,
covering_tests,
static_mutant,
duration_ms: hit.duration_ms,
retried: hit.status == MutantStatus::Survived,
attempts: Vec::new(),
cached: source == StoredSource::Cache,
resumed: source == StoredSource::Journal,
}
}
pub(super) fn job_key(
context: &JobContext<'_>,
mutant: &ScheduledMutant,
(tests, targets): (&[String], &[String]),
test_files: &[String],
) -> Option<String> {
match (context.cache, context.journal) {
(Some(cache), _) => Some(cache.key(context.ready, mutant, tests, test_files)),
(None, Some(journal)) => Some(journal.key(context.ready, mutant, tests, test_files)),
(None, None) => None,
}
.map(|key| {
if context.targets.is_some() && context.target_full {
format!("targets:{}:{key}", targets_digest(targets))
} else if context.targets.is_some() {
format!("targets-first:{}:{key}", targets_digest(targets))
} else if context.kill_matrix {
format!("matrix:{key}")
} else {
key
}
})
}
fn targets_digest(targets: &[String]) -> String {
use sha2::{Digest, Sha256};
use std::fmt::Write as _;
let mut sorted: Vec<&str> = targets.iter().map(String::as_str).collect();
sorted.sort_unstable();
let mut hasher = Sha256::new();
for target in sorted {
hasher.update((target.len() as u64).to_le_bytes());
hasher.update(target.as_bytes());
}
hasher
.finalize()
.iter()
.fold(String::new(), |mut text, byte| {
let _ = write!(text, "{byte:02x}");
text
})
}
pub(super) fn record_stored(
context: &JobContext<'_>,
key: Option<&String>,
mutant: &ScheduledMutant,
tests: &[String],
static_mutant: bool,
outcome: &mut ScheduleOutcome,
) -> bool {
let Some(stored) = stored_result(context, key, mutant) else {
return false;
};
let stored = stored_outcome(stored, tests, static_mutant);
if let (true, Some(key)) = (stored.resumed, key) {
outcome.cache_keys.insert(mutant.id.clone(), key.clone());
}
outcome.results.insert(mutant.id.clone(), stored);
true
}
fn journal_result(config: &ScheduleConfig, job: &Job, result: &CachedResult) {
if (config.kill_matrix || !config.targets.is_empty()) && !result.kill_matrix_complete {
return;
}
if let (Some(journal), Some(key)) = (&config.journal, &job.cache_key) {
journal.append(&job.id, key, result);
}
}
pub(super) fn journal_first_run(config: &ScheduleConfig, job: &Job, attempt: &Attempt) {
let final_status = match attempt.status {
MutantStatus::Killed => !retries_unique_kill(config, job, attempt),
MutantStatus::NotKilledByTarget => true,
_ => false,
};
if !final_status {
return;
}
journal_result(
config,
job,
&CachedResult {
status: attempt.status,
killing_tests: attempt.killing_tests.clone(),
kill_matrix_complete: attempt.kill_matrix_complete,
killed_by: attempt.killed_by.clone(),
duration_ms: attempt.duration_ms,
},
);
}
pub(super) struct FirstRun {
pub(super) status: MutantStatus,
pub(super) duration_ms: Option<u64>,
pub(super) killing_tests: Vec<String>,
}
pub(super) type FirstRuns = FxHashMap<String, FirstRun>;
pub(super) fn journal_retry(
config: &ScheduleConfig,
firsts: &FirstRuns,
job: &Job,
retry: &Attempt,
) {
let (first, first_ms) = firsts
.get(&job.id)
.map_or((MutantStatus::Survived, None), |first| {
(first.status, first.duration_ms)
});
if first == MutantStatus::Killed {
let same_killers = firsts
.get(&job.id)
.is_some_and(|first| sorted(&first.killing_tests) == sorted(&retry.killing_tests));
if retry.status == MutantStatus::Killed && same_killers {
journal_result(
config,
job,
&CachedResult {
status: MutantStatus::Killed,
killing_tests: retry.killing_tests.clone(),
kill_matrix_complete: retry.kill_matrix_complete,
killed_by: retry.killed_by.clone(),
duration_ms: retry.duration_ms,
},
);
}
return;
}
let result = match retry_status(first, job, retry) {
MutantStatus::Killed => CachedResult {
status: MutantStatus::Killed,
killing_tests: retry.killing_tests.clone(),
kill_matrix_complete: retry.kill_matrix_complete,
killed_by: retry.killed_by.clone(),
duration_ms: retry.duration_ms,
},
MutantStatus::Survived if retry.dropped_tests.is_empty() => CachedResult {
status: MutantStatus::Survived,
killing_tests: Vec::new(),
kill_matrix_complete: retry.kill_matrix_complete,
killed_by: None,
duration_ms: first_ms,
},
_ => return,
};
journal_result(config, job, &result);
}
fn sorted(tests: &[String]) -> Vec<&String> {
let mut tests: Vec<&String> = tests.iter().collect();
tests.sort_unstable();
tests.dedup();
tests
}