requirements.test-coverage.processes.reports
Requirements index · View definition
Requirement
Habeas MUST support deriving both a report for an individual recorded process and a combined report without discarding the separate profiles of
. Retained run data MUST remain sufficient to display those reports using the matching captured source after the project is rebuilt or its source changes.
Rationale
The reviewed tests adequately cover the three obligations in requirements.test-coverage.processes.reports.
Obligations
- An individual report for a recorded process can be derived.
- A combined report can be derived without discarding the separate per-process profiles from
requirements.test-coverage.processes. - The retained run data still displays those reports with the matching captured source after a rebuild or a source change.
Obligations 1 and 2: individual and combined reports, with separate profiles kept
src/execution_coverage/book.rs#mod[tests]/fn[gaps_omit_test_data_and_preserve_saved_profiles_and_sources]builds an attempt with a parent process and a child process. They have different hit counts and separate.profrawfiles.- It loads the saved records with
load_saved. It then derives each process’s report from its stored lines plus the captured source, using a test-local closure. - It asserts that the parent and child reports differ for the same source lines. The parent covers the first function and not the second. The child covers the second with a count of seven and not the first.
- It asserts that the product’s
unionyields the combined view: the child’s count survives and the total of covered locations is the union. The combined view therefore does not replace the separate per-process data. - It asserts that
attempt.json,run.jsonand both profile files are byte-for-byte unchanged afterpopulateand a source change. - The real nextest run in
tests/execution_coverage.rs#fn[real_parallel_processes_retries_child_profiles_and_filtered_reruns]checks the following:- The
child_processattempt retains two separate processes, each with non-empty line data and no diagnostic. - Every attempt has at least one process.
- Every referenced profile file exists on disk, both initially and after later runs and a compile failure.
- Attempt ids are unique, and the same-named tests in different binaries stay distinct.
- The
tests/execution_coverage.rs#fn[passing_tests_with_missing_or_corrupt_profiles_fail_collection_and_retain_partial_reports]checks that good, corrupt and missing profiles are retained as per-process records with diagnostics. Partial profiles stay on disk.src/execution_coverage/runner.rs#mod[tests]/fn[parallel_conversion_is_bounded_and_retains_every_result_in_order]checks that parallel conversion keeps every per-item result in order, including a failed one.
Obligation 3: matching captured source after a rebuild or source change
- In
gaps_omit_test_data_and_preserve_saved_profiles_and_sources, the workspacecode.rsis overwritten with new text. The saved record is still non-fresh, and every archived line maps to the originally captured source text. None of it contains the new text. - The current book is asserted to show “Coverage unavailable”.
filtered_runs_union_latest_attempts_and_invalidate_with_saved_sourcechanges the source and asserts the stale marker. It then asserts that every saved record’s captured source still holds the original text. A new build configuration yields a “historical build configuration” report.- The real run asserts that
run.jsoncaptures thesrc/lib.rssource and thatmaps.jsonexists.
Residual points, not treated as gaps
- No test re-converts raw profiles with
maps.jsonafter a rebuild. The reports are tested from the normalized per-process lines and captured sources that are stored. - The individual-process view is derived by a test-local closure, because the product exposes no separate per-process report. The tests do check that the stored data supports it.
Inputs
Implementation
Input 8: outline src/execution_coverage/book.rs fn[populate]
- File:
src/execution_coverage/book.rs - Selector:
fn[populate] - Kind:
fn src/execution_coverage/book.rs:304–318
// {impl}`requirements.test-coverage.index`
// {impl}`requirements.test-coverage.index.selection`
// {impl}`requirements.test-coverage.index.freshness`
// {impl}`requirements.test-coverage.index.summary`
// {impl}`requirements.test-coverage.index.paths`
// {impl}`requirements.test-coverage.index.unavailable`
// {impl}`requirements.test-coverage.index.render_only`
// {impl}`requirements.test-coverage.index.details`
// {impl}`requirements.test-coverage.processes.reports`
// {impl}`requirements.test-coverage.storage.configuration`
// {impl}`requirements.test-coverage.index.file_map`
// {impl}`requirements.test-coverage.index.file_map.combined.details`
pub(crate) fn populate(book: &mut Book, project: &Path, parent: &Path) -> io::Result<()> {
populate_in(book, project, None, parent)
}
Tests
Input 3: outline src/execution_coverage/book.rs mod[tests]/fn[filtered_runs_union_latest_attempts_and_invalidate_with_saved_source]
- File:
src/execution_coverage/book.rs - Selector:
mod[tests]/fn[filtered_runs_union_latest_attempts_and_invalidate_with_saved_source] - Kind:
fn src/execution_coverage/book.rs:1857–1985
// {test}`requirements.test-coverage.index`
// {test}`requirements.test-coverage.processes.reports`
// {test}`requirements.test-coverage.storage.configuration`
// {test}`requirements.test-coverage.index.selection`
// {test}`requirements.test-coverage.index.summary`
// {test}`requirements.test-coverage.index.details`
// {test}`requirements.test-coverage.index.freshness`
// {test}`requirements.test-coverage.index.render_only`
// {test}`requirements.test-coverage.index.file_map.combined.measurement`
#[test]
fn filtered_runs_union_latest_attempts_and_invalidate_with_saved_source() {
let (temp, book) = fixture();
let root = temp.path();
record(root, "one", 1, "build-a", &[(1, 1), (2, 0)]);
record(root, "two", 2, "build-a", &[(1, 0), (2, 1)]);
let mut combined = book.clone();
populate(&mut combined, root).unwrap();
assert!(
combined
.chapters()
.next()
.unwrap()
.content
.contains("2/2 (100.0%)")
);
assert!(
combined
.chapters()
.next()
.unwrap()
.content
.contains("2 selected test attempts")
);
assert!(
!combined
.chapters()
.next()
.unwrap()
.content
.contains("{coverage-index}")
);
// A failing newest attempt replaces the earlier success, even with no data.
let newest = record(root, "one", 3, "build-a", &[]);
let mut attempt: Attempt = load(&newest.join("attempt.json")).unwrap();
attempt.diagnostics.push("profile missing".into());
for outcome in ["failed", "interrupted"] {
attempt.outcome = outcome.into();
save(&newest.join("attempt.json"), &attempt).unwrap();
let mut combined = book.clone();
populate(&mut combined, root).unwrap();
assert!(
combined
.chapters()
.next()
.unwrap()
.content
.contains("gap counts unavailable")
);
assert!(
combined
.chapters()
.next()
.unwrap()
.content
.contains("missing or unreadable coverage")
);
assert!(
combined
.chapters()
.next()
.unwrap()
.content
.contains("2 selected test attempts")
);
}
fs::write(root.join("code.rs"), "changed source\n").unwrap();
let mut stale = book.clone();
populate(&mut stale, root).unwrap();
assert!(
stale
.chapters()
.next()
.unwrap()
.content
.contains("gap counts unavailable")
);
assert!(
stale
.chapters()
.next()
.unwrap()
.content
.contains("stale coverage; recollect")
);
let saved = load_saved(root, Some(root.join("target")));
assert!(
saved
.records
.iter()
.all(|record| record.run.sources["code.rs"].contains("fn one() {}"))
);
record(root, "one", 4, "build-b", &[(1, 1)]);
let mut other = book;
populate(&mut other, root).unwrap();
assert!(
other
.chapters()
.next()
.unwrap()
.content
.contains("historical build configuration")
);
assert!(
other
.chapters()
.next()
.unwrap()
.content
.contains("1/1 (100.0%)")
);
assert!(
other
.chapters()
.next()
.unwrap()
.content
.contains("1 selected test attempts")
);
}
Input 4: outline src/execution_coverage/book.rs mod[tests]/fn[gaps_omit_test_data_and_preserve_saved_profiles_and_sources]
- File:
src/execution_coverage/book.rs - Selector:
mod[tests]/fn[gaps_omit_test_data_and_preserve_saved_profiles_and_sources] - Kind:
fn src/execution_coverage/book.rs:1987–2144
// {test}`requirements.test-coverage.index.summary`
// {test}`requirements.test-coverage.index.details`
// {test}`requirements.test-coverage.processes.reports`
#[test]
fn gaps_omit_test_data_and_preserve_saved_profiles_and_sources() {
let (temp, book) = fixture();
let root = temp.path();
fs::write(root.join("passing.rs"), "fn passing() {}\n").unwrap();
let first = record(root, "one", 100, "a", &[(1, 1), (2, 0)]);
fs::write(first.join("2-2.profraw"), "child profile fixture").unwrap();
let mut attempt: Attempt = load(&first.join("attempt.json")).unwrap();
attempt.processes.push(Process {
functions: Some(vec![]),
pid: 2,
profiles: vec!["2-2.profraw".into()],
lines: BTreeMap::from([("code.rs".into(), BTreeMap::from([(1, 0), (2, 7)]))]),
diagnostic: None,
});
// A passing file must not appear in the gaps table.
attempt.processes[0]
.lines
.insert("passing.rs".into(), BTreeMap::from([(1, 1)]));
attempt.processes[0]
.functions
.as_mut()
.unwrap()
.push(super::super::FunctionExecution {
file: "passing.rs".into(),
line: 1,
column: 1,
count: 1,
});
save(&first.join("attempt.json"), &attempt).unwrap();
let run_path = first.parent().unwrap().parent().unwrap().join("run.json");
let mut run: Run = load(&run_path).unwrap();
run.sources
.insert("passing.rs".into(), "fn passing() {}\n".into());
save(&run_path, &run).unwrap();
record(root, "two", 200, "a", &[(1, 1), (2, 0)]);
let captured_attempt = fs::read(first.join("attempt.json")).unwrap();
let captured_run = fs::read(&run_path).unwrap();
let mut combined = book.clone();
populate(&mut combined, root).unwrap();
let index = combined.chapters().next().unwrap();
assert!(index.content.contains("3/3 (100.0%)"));
assert!(
index
.content
.contains("not establish that all current tests were measured")
);
assert!(!map_html(&index.content).contains("data-file=\"passing.rs\""));
assert!(
combined
.chapters()
.all(|chapter| chapter.name != "File notes: passing.rs")
);
for chapter in combined.chapters() {
for omitted in [
"Test process coverage",
"Captured source",
"habeas-coverage-test",
"Test runs and provenance",
"application/json",
"habeasRenderCoverage",
"binary / one",
"binary / two",
"fn passing() {}",
] {
assert!(
!chapter.content.contains(omitted),
"report includes {omitted}"
);
}
assert!(!chapter.name.starts_with("binary /"));
assert!(
!chapter
.path
.as_ref()
.unwrap()
.to_string_lossy()
.ends_with("-source.md")
);
assert!(chapter.name == "Coverage gaps" || chapter.name.starts_with("File notes:"));
}
fs::write(root.join("code.rs"), "rebuilt source\n").unwrap();
let mut historical = book;
populate(&mut historical, root).unwrap();
assert!(
historical
.chapters()
.next()
.unwrap()
.content
.contains("Coverage unavailable")
);
assert_eq!(
fs::read(first.join("attempt.json")).unwrap(),
captured_attempt
);
assert_eq!(fs::read(&run_path).unwrap(), captured_run);
assert_eq!(
fs::read_to_string(first.join("1-1.profraw")).unwrap(),
"retained profile fixture"
);
assert_eq!(
fs::read_to_string(first.join("2-2.profraw")).unwrap(),
"child profile fixture"
);
// Archived reports use the saved source, even though freshness excludes
// these attempts from the current workspace's gaps report.
let saved = load_saved(root, Some(root.join("target")));
let archived = saved
.records
.iter()
.find(|record| record.attempt.test == "one")
.unwrap();
assert!(!archived.fresh);
let captured_lines = |locations: BTreeMap<(String, u32), u64>| {
locations
.into_iter()
.map(|((file, line), count)| {
let source_line = archived.run.sources[&file]
.lines()
.nth(line as usize - 1)
.unwrap();
((file, line), (source_line.to_owned(), count))
})
.collect::<BTreeMap<_, _>>()
};
let individual = |process: &Process| {
captured_lines(
process
.lines
.iter()
.flat_map(|(file, lines)| {
lines
.iter()
.map(move |(&line, &count)| ((file.clone(), line), count))
})
.collect(),
)
};
let parent = individual(&archived.attempt.processes[0]);
let child = individual(&archived.attempt.processes[1]);
let combined = captured_lines(union(std::iter::once(archived)));
assert_eq!(parent[&("code.rs".into(), 1)], ("fn one() {}".into(), 1));
assert_eq!(parent[&("code.rs".into(), 2)], ("fn two() {}".into(), 0));
assert_eq!(child[&("code.rs".into(), 1)], ("fn one() {}".into(), 0));
assert_eq!(child[&("code.rs".into(), 2)], ("fn two() {}".into(), 7));
assert_eq!(combined[&("code.rs".into(), 2)], ("fn two() {}".into(), 7));
assert_eq!(parent.values().filter(|(_, count)| *count > 0).count(), 2);
assert_eq!(combined.values().filter(|(_, count)| *count > 0).count(), 3);
assert!(
combined
.values()
.all(|(source, _)| !source.contains("rebuilt source"))
);
}
Input 5: outline src/execution_coverage/runner.rs mod[tests]/fn[parallel_conversion_is_bounded_and_retains_every_result_in_order]
- File:
src/execution_coverage/runner.rs - Selector:
mod[tests]/fn[parallel_conversion_is_bounded_and_retains_every_result_in_order] - Kind:
fn src/execution_coverage/runner.rs:1637–1706
// {test}`requirements.test-coverage.processes`
// {test}`requirements.test-coverage.processes.reports`
// {test}`requirements.test-coverage.failures`
// {test}`requirements.test-coverage.processes.progress`
#[test]
fn parallel_conversion_is_bounded_and_retains_every_result_in_order() {
use std::sync::{Condvar, Mutex};
use std::time::Duration;
for workers in [2, 8] {
let total = workers * 2;
let active = AtomicUsize::new(0);
let peak = AtomicUsize::new(0);
let visits: Vec<_> = (0..total).map(|_| AtomicUsize::new(0)).collect();
let finished: Vec<_> = (0..total).map(|_| AtomicBool::new(false)).collect();
let rendezvous = (Mutex::new(false), Condvar::new());
let mut completed = 0;
let results = parallel_collect(
&(0..total).collect::<Vec<_>>(),
workers,
|&index| {
visits[index].fetch_add(1, Ordering::SeqCst);
let concurrent = active.fetch_add(1, Ordering::SeqCst) + 1;
peak.fetch_max(concurrent, Ordering::SeqCst);
if index < workers {
let mut met = rendezvous.0.lock().unwrap();
if concurrent == workers {
*met = true;
rendezvous.1.notify_all();
}
let (met, timeout) = rendezvous
.1
.wait_timeout_while(met, Duration::from_secs(5), |met| !*met)
.unwrap();
assert!(
*met && !timeout.timed_out(),
"conversion was not concurrent"
);
}
active.fetch_sub(1, Ordering::SeqCst);
finished[index].store(true, Ordering::SeqCst);
if index == 3 {
Err("unreadable profile")
} else {
Ok(index)
}
},
|index| {
assert!(
finished[index].load(Ordering::SeqCst),
"progress advanced before conversion finished"
);
completed += 1;
},
);
assert_eq!(peak.load(Ordering::SeqCst), workers);
assert!(visits.iter().all(|count| count.load(Ordering::SeqCst) == 1));
assert_eq!(completed, total, "failed work also completes a conversion");
assert_eq!(
results,
(0..total)
.map(|index| if index == 3 {
Err("unreadable profile")
} else {
Ok(index)
})
.collect::<Vec<_>>()
);
}
}
Input 6: outline tests/execution_coverage.rs fn[real_parallel_processes_retries_child_profiles_and_filtered_reruns]
- File:
tests/execution_coverage.rs - Selector:
fn[real_parallel_processes_retries_child_profiles_and_filtered_reruns] - Kind:
fn tests/execution_coverage.rs:741–1018
// {test}`requirements.test-coverage.run`
// {test}`requirements.test-coverage.processes`
// {test}`requirements.test-coverage.processes.reports`
// {test}`requirements.test-coverage.storage`
// {test}`requirements.test-coverage.storage.provenance`
// {test}`requirements.test-coverage.storage.configuration`
// {test}`requirements.test-coverage.storage.outcomes`
// {test}`requirements.test-coverage.failures`
#[test]
fn real_parallel_processes_retries_child_profiles_and_filtered_reruns() {
let temp = fixture();
let root = temp.path();
assert_success(&coverage(
root,
&["--workspace", "--retries", "1", "-j", "2", "--no-fail-fast"],
));
let saved = runs(root);
assert_eq!(saved.len(), 1);
let first = &saved[0].0;
assert_eq!(
saved[0].1["id"],
first.file_name().unwrap().to_str().unwrap()
);
assert!(saved[0].1["started"].as_u64().unwrap() > 0);
assert_eq!(saved[0].1["command"][0], "cargo nextest run");
assert!(
saved[0].1["selection"]
.as_array()
.unwrap()
.iter()
.any(|arg| arg == "--workspace")
);
assert!(saved[0].1["revision"].is_null());
assert!(saved[0].1["dirty"].is_null());
assert!(
saved[0].1["inputs"]
.get(root.join("src/lib.rs").to_str().unwrap())
.is_some()
);
let records = attempts(first);
assert_eq!(records.len(), 6); // five tests, one retried
let retry = records
.iter()
.filter(|record| record["test"] == "retries")
.collect::<Vec<_>>();
assert_eq!(retry.len(), 2);
assert!(
retry
.iter()
.any(|record| record["outcome"] == "failed" && record["attempt"] == "1")
);
assert!(
retry
.iter()
.any(|record| record["outcome"] == "success" && record["attempt"] == "2")
);
let child = records
.iter()
.find(|record| record["test"] == "child_process")
.unwrap();
assert_eq!(child["processes"].as_array().unwrap().len(), 2);
assert!(
child["processes"]
.as_array()
.unwrap()
.iter()
.all(|process| process["diagnostic"].is_null()
&& !process["lines"].as_object().unwrap().is_empty())
);
assert!(
records
.iter()
.all(|record| !record["processes"].as_array().unwrap().is_empty())
);
assert_eq!(
records
.iter()
.filter(|record| record["test"].as_str().unwrap().ends_with("same_name"))
.count(),
2
);
let same_named = records
.iter()
.filter(|record| record["test"].as_str().unwrap().ends_with("same_name"))
.collect::<Vec<_>>();
let binaries = same_named
.iter()
.map(|record| record["binary"].as_str().unwrap())
.collect::<std::collections::BTreeSet<_>>();
assert_eq!(
binaries,
std::collections::BTreeSet::from(["coverage-fixture", "coverage-fixture::processes"])
);
let identities = records
.iter()
.map(|record| record["id"].as_str().unwrap())
.collect::<std::collections::BTreeSet<_>>();
assert_eq!(identities.len(), records.len());
for record in &records {
for process in record["processes"].as_array().unwrap() {
for profile in process["profiles"].as_array().unwrap() {
assert!(
first
.join("attempts")
.join(record["id"].as_str().unwrap())
.join(profile.as_str().unwrap())
.is_file()
);
}
}
}
let configuration = &saved[0].1["configuration_inputs"];
assert!(
configuration["rustc"]
.as_str()
.unwrap()
.contains("LLVM version:")
);
assert!(!configuration["target"].as_str().unwrap().is_empty());
assert_eq!(configuration["cargo-profile"], "test");
assert!(
configuration["instrumentation"]
.as_str()
.unwrap()
.contains("-C instrument-coverage")
);
assert!(first.join("maps.json").is_file());
assert!(
saved[0].1["sources"]["src/lib.rs"]
.as_str()
.unwrap()
.contains("pub fn value")
);
assert_success(&coverage(root, &["-E", "test(second)"]));
let saved = runs(root);
assert_eq!(saved.len(), 2);
assert_eq!(attempts(&saved[1].0).len(), 1);
assert_eq!(saved[0].1["configuration"], saved[1].1["configuration"]);
assert_eq!(
saved[1].1["selection"],
serde_json::json!(["-E", "test(second)"])
);
// A scheduling profile doesn't split build compatibility.
let config = root.join(".config/nextest.toml");
let mut source = fs::read_to_string(&config).unwrap();
source.push_str("\n[profile.focused]\ntest-threads = 1\n");
fs::write(config, source).unwrap();
assert_success(&coverage(
root,
&["--profile", "focused", "-E", "test(second)"],
));
let saved = runs(root);
assert_eq!(saved[0].1["configuration"], saved[2].1["configuration"]);
assert_eq!(attempts(&saved[0].0).len(), 6); // historical profiles were retained
// Collection must preserve failure, including a retry's attempt outcome.
let failed = coverage(root, &["-E", "test(retries)", "--retries", "0"]);
assert!(!failed.status.success());
let saved = runs(root);
let newest = saved.last().unwrap();
assert_eq!(newest.1["outcome"], "failed");
assert_eq!(attempts(&newest.0)[0]["outcome"], "failed");
// Empty selection has nextest's own exit result and a visible run diagnostic.
let empty = coverage(
root,
&["-E", "test(definitely_missing)", "--no-tests", "pass"],
);
assert_success(&empty);
let saved = runs(root);
assert!(attempts(&saved.last().unwrap().0).is_empty());
assert!(
saved.last().unwrap().1["diagnostics"][0]
.as_str()
.unwrap()
.contains("Empty test selection")
);
let empty_failure = coverage(root, &["-E", "test(definitely_missing)"]);
assert_eq!(
empty_failure.status.code(),
Some(4),
"{}",
String::from_utf8_lossy(&empty_failure.stderr)
);
let saved = runs(root);
let newest = saved.last().unwrap();
assert_eq!(newest.1["outcome"], "failed");
assert!(attempts(&newest.0).is_empty());
assert!(
newest.1["diagnostics"][0]
.as_str()
.unwrap()
.contains("Empty test selection")
);
assert_success(&coverage(
root,
&["--features", "alpha", "-Fbeta", "-E", "test(second)"],
));
let saved = runs(root);
let newest = saved.last().unwrap();
assert_ne!(newest.1["configuration"], saved[0].1["configuration"]);
let enabled: Value = serde_json::from_str(
newest.1["configuration_inputs"]["enabled-features"]
.as_str()
.unwrap(),
)
.unwrap();
assert!(enabled.as_object().unwrap().values().any(|features| {
features
.as_array()
.unwrap()
.contains(&Value::String("alpha".into()))
&& features
.as_array()
.unwrap()
.contains(&Value::String("beta".into()))
}));
assert_success(&coverage(
root,
&[
"--config",
"build.build-dir='custom-build'",
"-E",
"test(second)",
],
));
let saved = runs(root);
assert_eq!(attempts(&saved.last().unwrap().0).len(), 1);
assert!(!root.join("custom-build").exists());
assert_success(&coverage(root, &["--no-run", "-E", "test(second)"]));
let saved = runs(root);
let newest = saved.last().unwrap();
assert_eq!(newest.1["outcome"], "success");
assert!(attempts(&newest.0).is_empty());
assert!(
newest.1["diagnostics"][0]
.as_str()
.unwrap()
.contains("Compilation-only")
);
assert!(
!newest.1["diagnostics"][0]
.as_str()
.unwrap()
.contains("Empty")
);
// Compilation failures also retain run identity and all earlier process data.
fs::write(
root.join("src/lib.rs"),
"compile_error!(\"deliberate build failure\");\n",
)
.unwrap();
let failed_build = coverage(root, &["-E", "test(second)"]);
assert!(!failed_build.status.success());
let saved = runs(root);
let newest = saved.last().unwrap();
assert_eq!(newest.1["outcome"], "failed");
assert!(attempts(&newest.0).is_empty());
assert!(
newest.1["diagnostics"][0]
.as_str()
.unwrap()
.contains("Instrumented compilation")
);
assert_eq!(attempts(first).len(), 6);
for record in &records {
for process in record["processes"].as_array().unwrap() {
for profile in process["profiles"].as_array().unwrap() {
assert!(
first
.join("attempts")
.join(record["id"].as_str().unwrap())
.join(profile.as_str().unwrap())
.is_file()
);
}
}
}
}
Input 7: outline tests/execution_coverage.rs fn[passing_tests_with_missing_or_corrupt_profiles_fail_collection_and_retain_partial_reports]
- File:
tests/execution_coverage.rs - Selector:
fn[passing_tests_with_missing_or_corrupt_profiles_fail_collection_and_retain_partial_reports] - Kind:
fn tests/execution_coverage.rs:1228–1323
// {test}`requirements.test-coverage.failures`
// {test}`requirements.test-coverage.storage.outcomes`
// {test}`requirements.test-coverage.processes.reports`
// {test}`requirements.test-coverage.test`
#[cfg(unix)]
#[test]
fn passing_tests_with_missing_or_corrupt_profiles_fail_collection_and_retain_partial_reports() {
let temp = fixture();
let root = temp.path();
fs::write(root.join("tests/processes.rs"), "").unwrap();
fs::write(root.join("src/lib.rs"), r#"
#[test] fn good_profile() { assert_eq!(std::hint::black_box(1), 1); }
unsafe extern "C" { fn _exit(status: i32) -> !; }
#[test] fn missing_profile() { unsafe { _exit(0) } }
#[test] fn corrupt_profile() {
let template = std::path::PathBuf::from(std::env::var("LLVM_PROFILE_FILE").unwrap());
std::fs::write(template.parent().unwrap().join(format!("{}-corrupt.profraw", std::process::id())), "not an LLVM profile").unwrap();
}
"#).unwrap();
let output = coverage(root, &["--workspace"]);
assert!(!output.status.success());
assert!(
String::from_utf8_lossy(&output.stderr)
.contains("partial profiles and reports have been retained")
);
let combined = full_flow(root);
assert!(!combined.status.success());
assert!(!String::from_utf8_lossy(&combined.stdout).contains("Coverage check"));
assert!(
String::from_utf8_lossy(&combined.stderr)
.contains("partial profiles and reports have been retained")
);
let saved = runs(root);
assert_eq!(saved[0].1["outcome"], "failed");
let records = attempts(&saved[0].0);
assert_eq!(records.len(), 3);
assert!(
records
.iter()
.all(|attempt| attempt["outcome"] == "success"),
"test execution itself succeeds: {records:?}"
);
let missing = records
.iter()
.find(|attempt| attempt["test"] == "missing_profile")
.unwrap();
assert!(
missing["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|diagnostic| diagnostic
.as_str()
.unwrap()
.contains("No LLVM profile was written"))
);
let corrupt = records
.iter()
.find(|attempt| attempt["test"] == "corrupt_profile")
.unwrap();
assert!(
corrupt["processes"]
.as_array()
.unwrap()
.iter()
.any(|process| !process["diagnostic"].is_null()
&& process["lines"].as_object().unwrap().is_empty())
);
let good = records
.iter()
.find(|attempt| attempt["test"] == "good_profile")
.unwrap();
assert!(
!good["processes"][0]["lines"]
.as_object()
.unwrap()
.is_empty()
);
for attempt in [&good, &corrupt] {
for profile in attempt["processes"]
.as_array()
.unwrap()
.iter()
.flat_map(|process| process["profiles"].as_array().unwrap())
{
assert!(
saved[0]
.0
.join("attempts")
.join(attempt["id"].as_str().unwrap())
.join(profile.as_str().unwrap())
.is_file()
);
}
}
}
Referenced definitions
Input 2: requirements selection requirements.test-coverage.processes
requirements.test-coverage.processes:md/requirements/test-coverage.md:49–56
:::{req} processes
Each coverage run MUST retain LLVM coverage profiles independently for each
test process, identifying its nextest binary, test name, and attempt. Concurrent
tests, tests with the same name in different binaries, retries, and separate
runs MUST NOT overwrite or combine one another's stored profiles. Profiles from
instrumented child processes MUST remain separate and associated with the test
attempt that spawned them.
:::
Other sources
Input 1: requirements selection requirements.test-coverage.processes.reports
requirements.test-coverage.processes.reports:md/requirements/test-coverage.md:58–64
:::{req} processes.reports
Habeas MUST support deriving both a report for an individual recorded process
and a combined report without discarding the separate profiles of
{cite}`requirements.test-coverage.processes`. Retained run data MUST remain
sufficient to display those reports using the matching captured source after
the project is rebuilt or its source changes.
:::
Input 9: outline src/execution_coverage/book.rs fn[union]
- File:
src/execution_coverage/book.rs - Selector:
fn[union] - Kind:
fn src/execution_coverage/book.rs:40–57
// {impl}`requirements.test-coverage.index.summary`
// {impl}`requirements.test-coverage.index.file_map`
pub(super) fn union<'a>(records: impl Iterator<Item = &'a Record>) -> BTreeMap<(String, u32), u64> {
let mut result: BTreeMap<(String, u32), u64> = BTreeMap::new();
for record in records {
for process in &record.attempt.processes {
for (file, lines) in &process.lines {
for (&line, &count) in lines {
result
.entry((file.clone(), line))
.and_modify(|current| *current = (*current).max(count))
.or_insert(count);
}
}
}
}
result
}
Input 10: outline src/execution_coverage/book.rs fn[load_saved]
- File:
src/execution_coverage/book.rs - Selector:
fn[load_saved] - Kind:
fn src/execution_coverage/book.rs:330–524
// {impl}`requirements.test-coverage.index.selection`
// {impl}`requirements.test-coverage.index.freshness`
// {impl}`requirements.test-coverage.check.measurement`
pub(super) fn load_saved(project: &Path, target: Option<PathBuf>) -> SavedCoverage {
let mut diagnostics = Vec::new();
let mut uncertain_history = false;
let mut current_files = BTreeSet::new();
let mut discovery_failed = false;
let mut records = Vec::new();
let workspace = workspace_root(project);
if let Ok(root) = &workspace {
let mut errors = Vec::new();
let discovered = crate::evidence::discovered_files(root, &mut errors);
discovery_failed = !errors.is_empty();
diagnostics.extend(errors);
current_files.extend(
crate::rust_coverage::rust_files(root, &discovered)
.into_iter()
.filter_map(|file| {
file.strip_prefix(root)
.ok()
.map(|relative| relative.to_string_lossy().into_owned())
}),
);
}
let root_and_target = workspace.and_then(|root| {
Ok((
target
.map(Ok)
.unwrap_or_else(|| target_directory(project))?,
root,
))
});
match root_and_target {
Err(error) => diagnostics.push(format!("Coverage storage is unavailable: {error}")),
Ok((target, root)) => {
let storage = target.join("habeas/coverage");
if storage.is_dir() {
let entries = match fs::read_dir(storage) {
Ok(entries) => entries.collect::<Vec<_>>(),
Err(error) => {
uncertain_history = true;
diagnostics.push(format!("Coverage storage is unreadable: {error}"));
Vec::new()
}
};
for entry in entries {
let dir = match entry {
Ok(entry) => entry.path(),
Err(error) => {
uncertain_history = true;
diagnostics.push(error.to_string());
continue;
}
};
if !dir.is_dir() {
continue;
}
let run: Run = match load(&dir.join("run.json")) {
Ok(run) => run,
Err(error) => {
uncertain_history = true;
diagnostics
.push(format!("{}: unavailable run data: {error}", dir.display()));
continue;
}
};
let current = fresh(&run, &root, &target).unwrap_or(false);
uncertain_history |= run.schema != 1;
for diagnostic in &run.diagnostics {
diagnostics.push(format!("Run {} ({}): {diagnostic}", run.id, run.outcome));
}
let attempts = match fs::read_dir(dir.join("attempts")) {
Ok(attempts) => attempts,
Err(error) => {
uncertain_history = true;
diagnostics.push(format!(
"Run {}: unavailable attempts directory {}: {error}",
run.id,
dir.join("attempts").display()
));
continue;
}
};
let run = Arc::new(run);
for entry in attempts {
let attempt_dir = match entry {
Ok(entry) => entry.path(),
Err(error) => {
uncertain_history = true;
diagnostics.push(error.to_string());
continue;
}
};
let mut attempt: Attempt = match load(&attempt_dir.join("attempt.json")) {
Ok(attempt) => attempt,
Err(error) => {
uncertain_history = true;
diagnostics.push(format!(
"{}: unavailable attempt data: {error}",
attempt_dir.display()
));
continue;
}
};
for process in &mut attempt.processes {
if process.profiles.is_empty()
|| process.profiles.iter().any(|profile| {
fs::File::open(attempt_dir.join(profile))
.and_then(|file| file.metadata())
.map_or(true, |metadata| metadata.len() == 0)
})
{
process.diagnostic = Some(
"A retained raw profile is missing, empty or unreadable."
.into(),
);
}
if process
.lines
.keys()
.any(|file| !run.sources.contains_key(file))
|| process
.functions
.iter()
.flatten()
.any(|function| !run.sources.contains_key(&function.file))
{
process.diagnostic = Some(
"Matching captured source is missing; coverage is unavailable."
.into(),
);
}
if process.lines.values().any(|lines| lines.contains_key(&0))
|| process
.functions
.iter()
.flatten()
.any(|function| function.line == 0 || function.column == 0)
{
process.diagnostic =
Some("Corrupt normalized coverage locations.".into());
}
}
// IDs are generated by the collector, but disk data may be corrupt.
if ![&run.id, &attempt.id]
.iter()
.all(|id| uuid::Uuid::parse_str(id).is_ok())
{
diagnostics.push(format!(
"{}: invalid coverage identity",
attempt_dir.display()
));
uncertain_history = true;
continue;
}
records.push(Record {
run: Arc::clone(&run),
attempt,
fresh: current,
});
}
}
}
}
}
records.sort_by(|a, b| {
(a.attempt.started, &a.run.id, &a.attempt.id).cmp(&(
b.attempt.started,
&b.run.id,
&b.attempt.id,
))
});
let active = records
.last()
.map(|record| record.run.configuration.clone());
let mut selected = BTreeMap::new();
for (index, record) in records.iter().enumerate() {
if Some(&record.run.configuration) == active.as_ref() {
selected.insert(
(record.attempt.binary.clone(), record.attempt.test.clone()),
index,
);
}
}
let selected: BTreeSet<_> = selected.into_values().collect();
SavedCoverage {
records,
selected,
diagnostics,
uncertain_history,
current_files,
discovery_failed,
}
}