requirements.test-coverage.check.measurement
Requirements index · View definition
Requirement
The coverage check MUST fail when no usable coverage has been collected, or when a selected latest attempt has missing, unreadable, or stale coverage. It MUST distinguish these measurement failures from measured lines with zero execution and from individual functions absent from otherwise usable coverage. Exception evidence MUST NOT excuse measurement failures or permit substitution of an older attempt. Excluded historical runs and incompatible configurations MUST NOT by themselves cause failure.
Coverage whose format does not support the function attribution required by
MUST be rejected with guidance to recollect coverage. When missing or corrupt metadata prevents establishing the latest-per-test selection or active configuration, the check MUST fail rather than silently use remaining records. Historical data MAY be disregarded without failure only when its exclusion can be established.
Rationale
The reviewed tests cover each obligation of requirements.test-coverage.check.measurement. All of them are in src/execution_coverage/check.rs under mod[tests].
- No usable coverage, or a selected latest attempt that is missing or stale.
fn[stale_missing_legacy_and_uncertain_history_cannot_use_older_success]starts with no records and asserts the report fails. It then records a good attempt and asserts it passes.- It then adds a newer attempt whose
profile.profrawis deleted and asserts the report says “missing or unreadable”. An older good attempt does not rescue it, so older-attempt substitution is ruled out. - It then makes the source stale and asserts “stale coverage”.
- A newer fresh attempt then makes the report pass again, even though attempts 2 to 4 are bad. Superseded historical attempts therefore do not cause failure.
- Legacy format. The same test, and the “legacy” case in
fn[accepted_exceptions_cannot_waive_invalid_measurement_and_checks_still_collect_errors], assert the “lacks function attribution” and “recollect coverage with this Habeas version” guidance. - Corrupt metadata.
- A corrupt
run.jsonproduces “cannot establish latest-per-test”, checked infn[stale_missing_legacy_and_uncertain_history_cannot_use_older_success]. - The “corrupt history” case in the exceptions test also fails the report.
- The “corrupt counters” and “empty lines” cases assert “corrupt function attribution” and “No usable instrumented lines”.
- Only
run.jsoncorruption is exercised in this file. Failures fromattempt.jsonor the storage directory are not tested here. I judged that acceptable because they all set the sameuncertain_historyflag, which therun.jsoncase already asserts.
- A corrupt
- Excluded or incompatible history does not fail. In
fn[stale_missing_legacy_and_uncertain_history_cannot_use_older_success], an “other-config” attempt with no function attribution is recorded and the report still passes (“excluded legacy data cannot invalidate a supported active configuration”). - Exceptions cannot excuse measurement failures.
fn[accepted_exceptions_cannot_waive_invalid_measurement_and_checks_still_collect_errors]runs seven failure kinds: absent, missing profile, legacy, corrupt counters, stale, corrupt history and empty lines. Each has accepted file and function citations. Each must fail, must not show “accepted exception”, and must not show a “0/1 (0.0%)” measurement. - Measurement failures versus zero execution or an absent function.
fn[accepted_file_and_function_explanations_remain_separate_from_execution]asserts “zero execution” for measured zero lines. It asserts “not measured” for an absent function and for an unmeasured file.fn[unmeasured_executable_files_and_parse_failures_do_not_disappear]asserts “not measured — FAIL” and “#fn[missing]: not measured”.fn[readable_failed_execution_can_contribute_but_outcomes_remain_visible]shows a readable failed attempt still contributes. A reported process diagnostic then fails the check.
I found no gap in the tests for this requirement, and no acknowledgments apply.
Inputs
Implementation
Input 9: 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,
}
}
Tests
Input 3: outline src/execution_coverage/check.rs mod[tests]/fn[stale_missing_legacy_and_uncertain_history_cannot_use_older_success]
- File:
src/execution_coverage/check.rs - Selector:
mod[tests]/fn[stale_missing_legacy_and_uncertain_history_cannot_use_older_success] - Kind:
fn src/execution_coverage/check.rs:1302–1337
// {test}`requirements.test-coverage.check.measurement`
// {test}`requirements.test-coverage.check.threshold`
#[test]
fn stale_missing_legacy_and_uncertain_history_cannot_use_older_success() {
let temp = fixture("fn a() {}");
let root = temp.path();
assert!(!report(root).passed);
record(root, "a", 1, "same", vec![process(root, &[(1, 1)], 1)]);
assert!(report(root).passed);
let mut old = process(root, &[(1, 1)], 1);
old.functions = None;
record(root, "old", 0, "other-config", vec![old]);
assert!(
report(root).passed,
"excluded legacy data cannot invalidate a supported active configuration"
);
let current = record(root, "a", 2, "same", vec![process(root, &[(1, 1)], 1)]);
fs::remove_file(current.join("profile.profraw")).unwrap();
assert!(report(root).text.contains("missing or unreadable"));
let mut legacy = process(root, &[(1, 1)], 1);
legacy.functions = None;
record(root, "a", 3, "same", vec![legacy]);
assert!(report(root).text.contains("lacks function attribution"));
record(root, "a", 4, "same", vec![process(root, &[(1, 1)], 1)]);
fs::write(root.join("code.rs"), "fn a() { let changed=1; }").unwrap();
assert!(report(root).text.contains("stale coverage"));
record(root, "a", 5, "same", vec![process(root, &[(1, 1)], 1)]);
assert!(report(root).passed);
fs::create_dir(root.join("target/habeas/coverage/corrupt")).unwrap();
fs::write(root.join("target/habeas/coverage/corrupt/run.json"), "{").unwrap();
assert!(
report(root)
.text
.contains("cannot establish latest-per-test")
);
}
Input 4: outline src/execution_coverage/check.rs mod[tests]/fn[accepted_file_and_function_explanations_remain_separate_from_execution]
- File:
src/execution_coverage/check.rs - Selector:
mod[tests]/fn[accepted_file_and_function_explanations_remain_separate_from_execution] - Kind:
fn src/execution_coverage/check.rs:1339–1419
// {test}`requirements.test-coverage.check.exceptions`
// {test}`requirements.test-coverage.check.exceptions.reviews`
// {test}`requirements.test-coverage.check.exceptions.binding`
// {test}`requirements.test-coverage.check.report`
// {test}`requirements.test-coverage.check.functions`
// {test}`requirements.test-coverage.check.measurement`
// {test}`requirements.test-coverage.check.threshold`
#[test]
fn accepted_file_and_function_explanations_remain_separate_from_execution() {
let temp = fixture(
"//! :::{cite} habeas:coverage\n//! Generated platform glue lacks a harness.\n//! :::\n\nfn a() {}\n",
);
let root = temp.path();
reviews(root, json!(true));
record(root, "a", 1, "same", vec![process(root, &[(5, 0)], 0)]);
let result = report(root);
assert!(!result.passed, "file exception cannot waive its function");
assert!(
result
.text
.contains("code.rs: 0/1 (0.0%) — accepted exception")
);
assert!(result.text.contains("#fn[a]: zero execution"));
fs::write(root.join("code.rs"),"//! :::{cite} habeas:coverage\n//! File rationale.\n//! :::\n\n// :::{cite} habeas:coverage\n// Function rationale, describing only a Linux condition.\n// :::\nfn a() {}\n").unwrap();
reviews(root, json!(true));
record(root, "a", 2, "linux", vec![process(root, &[(8, 0)], 0)]);
let result = report(root);
assert!(result.passed, "{}", result.text);
assert!(result.text.contains("0/1 (0.0%)"));
let exceptions = result
.text
.split_once("\nAccepted exceptions (do not increase execution coverage):\n")
.unwrap()
.1;
assert!(exceptions.contains("- code.rs: file threshold (0/1 (0.0%))"));
assert!(exceptions.contains("- code.rs#fn[a]: zero execution"));
let mut absent = process(root, &[(8, 0)], 0);
absent.functions = Some(vec![]);
record(root, "a", 3, "windows", vec![absent]);
let result = report(root);
assert!(
result.passed,
"same accepted citation covers unmeasured functions without conditional matching"
);
let exceptions = result
.text
.split_once("\nAccepted exceptions (do not increase execution coverage):\n")
.unwrap()
.1;
assert!(exceptions.contains("- code.rs#fn[a]: not measured"));
record(root, "a", 4, "covered", vec![process(root, &[(8, 1)], 1)]);
assert!(
report(root).passed,
"citation may remain when no exception is needed"
);
fs::write(root.join("driver.rs"), "fn driver() {}").unwrap();
let mut p = process(root, &[], 0);
p.lines.insert("driver.rs".into(), BTreeMap::from([(1, 1)]));
p.functions.as_mut().unwrap().push(FunctionExecution {
file: "driver.rs".into(),
line: 1,
column: 1,
count: 1,
});
record(root, "a", 5, "unmeasured-file", vec![p]);
let result = report(root);
assert!(result.passed, "{}", result.text);
assert!(
result
.text
.contains("code.rs: not measured — accepted exception"),
"{}",
result.text
);
assert!(!result.text.contains("code.rs: 0/"), "{}", result.text);
reviews(root, json!(false));
assert!(!report(root).passed);
assert!(report(root).text.contains("determination is false"));
reviews(root, json!({"FIXME":["acknowledgment"]}));
assert!(report(root).text.contains("cannot accept a {fixme}"));
}
Input 5: outline src/execution_coverage/check.rs mod[tests]/fn[unmeasured_executable_files_and_parse_failures_do_not_disappear]
- File:
src/execution_coverage/check.rs - Selector:
mod[tests]/fn[unmeasured_executable_files_and_parse_failures_do_not_disappear] - Kind:
fn src/execution_coverage/check.rs:1484–1538
// {test}`requirements.test-coverage.check.measurement`
// {test}`requirements.test-coverage.check.scope`
// {test}`requirements.test-coverage.check.threshold`
// {test}`requirements.test-coverage.check.report`
// {test}`requirements.test-coverage.check.functions`
#[test]
fn unmeasured_executable_files_and_parse_failures_do_not_disappear() {
let temp = fixture("struct S; trait T { fn declaration(); }");
let root = temp.path();
fs::write(root.join("driver.rs"), "fn driver() {}").unwrap();
let mut p = process(root, &[], 1);
p.lines.insert("driver.rs".into(), BTreeMap::from([(1, 1)]));
p.functions.as_mut().unwrap().push(FunctionExecution {
file: "driver.rs".into(),
line: 1,
column: 1,
count: 1,
});
record(root, "driver", 1, "same", vec![p]);
let result = report(root);
assert!(result.passed, "{}", result.text);
assert!(
result
.text
.contains("code.rs: no executable obligations — pass"),
"{}",
result.text
);
fs::write(root.join("code.rs"), "fn missing() {}").unwrap();
let mut p = process(root, &[], 1);
p.functions = Some(vec![]);
p.lines.insert("driver.rs".into(), BTreeMap::from([(1, 1)]));
p.functions.as_mut().unwrap().push(FunctionExecution {
file: "driver.rs".into(),
line: 1,
column: 1,
count: 1,
});
record(root, "driver", 2, "same", vec![p.clone()]);
let result = report(root);
assert!(result.text.contains("code.rs: not measured — FAIL"));
assert!(result.text.contains("#fn[missing]: not measured"));
fs::write(root.join("code.rs"), "fn malformed(").unwrap();
record(root, "driver", 3, "same", vec![p]);
let result = report(root);
assert!(!result.passed);
assert!(
result
.text
.to_lowercase()
.contains("cannot parse rust source"),
"{}",
result.text
);
}
Input 6: outline src/execution_coverage/check.rs mod[tests]/fn[readable_failed_execution_can_contribute_but_outcomes_remain_visible]
- File:
src/execution_coverage/check.rs - Selector:
mod[tests]/fn[readable_failed_execution_can_contribute_but_outcomes_remain_visible] - Kind:
fn src/execution_coverage/check.rs:1540–1556
// {test}`requirements.test-coverage.check.measurement`
// {test}`requirements.test-coverage.check.report`
#[test]
fn readable_failed_execution_can_contribute_but_outcomes_remain_visible() {
let temp = fixture("fn a() {}");
let root = temp.path();
let path = record(root, "a", 1, "same", vec![process(root, &[(1, 1)], 1)]);
let mut attempt: Attempt = load(&path.join("attempt.json")).unwrap();
attempt.outcome = "failed".into();
save(&path.join("attempt.json"), &attempt).unwrap();
let result = report(root);
assert!(result.passed, "{}", result.text);
assert!(result.text.contains("attempt failed"));
attempt.processes[0].diagnostic = Some("broken coverage map".into());
save(&path.join("attempt.json"), &attempt).unwrap();
assert!(!report(root).passed);
}
Input 7: outline src/execution_coverage/check.rs mod[tests]/fn[accepted_exceptions_cannot_waive_invalid_measurement_and_checks_still_collect_errors]
- File:
src/execution_coverage/check.rs - Selector:
mod[tests]/fn[accepted_exceptions_cannot_waive_invalid_measurement_and_checks_still_collect_errors] - Kind:
fn src/execution_coverage/check.rs:1676–1774
// {test}`requirements.test-coverage.check.measurement`
// {test}`requirements.ci.errors`
#[test]
fn accepted_exceptions_cannot_waive_invalid_measurement_and_checks_still_collect_errors() {
let source = "//! :::{cite} habeas:coverage\n//! File rationale.\n//! :::\n// :::{cite} habeas:coverage\n// Function rationale.\n// :::\nfn a() {}\n";
for failure in [
"absent",
"missing profile",
"legacy",
"corrupt counters",
"stale",
"corrupt history",
"empty lines",
] {
let temp = fixture(source);
let root = temp.path();
reviews(root, json!(true));
if failure != "absent" {
record(root, "a", 1, "same", vec![process(root, &[(7, 1)], 1)]);
let mut p = process(root, &[(7, 0)], 0);
if failure == "legacy" {
p.functions = None;
}
if failure == "corrupt counters" {
p.functions.as_mut().unwrap()[0].line = 0;
}
if failure == "empty lines" {
p.lines.clear();
}
let newest = record(root, "a", 2, "same", vec![p]);
match failure {
"missing profile" => fs::remove_file(newest.join("profile.profraw")).unwrap(),
"stale" => fs::write(
root.join("code.rs"),
format!("{source}\n// changed build input\n"),
)
.unwrap(),
"corrupt history" => fs::write(
newest.parent().unwrap().parent().unwrap().join("run.json"),
"{",
)
.unwrap(),
_ => {}
}
}
let result = report(root);
assert!(!result.passed, "{failure}: {}", result.text);
assert!(
!result.text.contains("accepted exception"),
"{failure}: {}",
result.text
);
assert!(
!result.text.contains("0/1 (0.0%)"),
"{failure}: {}",
result.text
);
if failure == "legacy" {
assert!(
result
.text
.contains("recollect coverage with this Habeas version")
);
}
if failure == "corrupt counters" {
assert!(result.text.contains("corrupt function attribution"));
}
if failure == "empty lines" {
assert!(result.text.contains("No usable instrumented lines"));
}
fs::remove_file(root.join("evidence/citations/code.rs/fn[a].json")).unwrap();
let result = report(root);
assert!(
result.text.contains("missing citation review"),
"{failure}: {}",
result.text
);
let mut seen = std::collections::BTreeSet::new();
for line in result.text.lines().filter(|line| line.starts_with("- ")) {
assert!(seen.insert(line), "duplicate finding: {line}");
}
fs::write(root.join("broken.rs"), "fn malformed(").unwrap();
fs::write(root.join("book.toml"), "[book]\nsrc = 7\n").unwrap();
let result = report(root);
assert!(
result
.text
.to_lowercase()
.contains("cannot parse rust source"),
"{}",
result.text
);
assert!(
result.text.contains("book.src must be a string"),
"{}",
result.text
);
}
}
Referenced definitions
Input 2: requirements selection requirements.test-coverage.check.functions
requirements.test-coverage.check.functions:md/requirements/test-coverage.md:605–616
:::{req} check.functions
Every function under {cite}`requirements.test-coverage.check.scope` without
recorded execution attributable to it MUST have current accepted exception
evidence under {cite}`requirements.test-coverage.check.exceptions`, even when
its containing file meets the target of
{cite}`requirements.test-coverage.check.threshold`.
Execution attributable only to another function, including a nested function
or closure, MUST NOT establish coverage of the enclosing function merely
because their source locations overlap. Having no recorded lines alone MUST
NOT establish that a function has no executable coverage obligations.
:::
Other sources
Input 1: requirements selection requirements.test-coverage.check.measurement
requirements.test-coverage.check.measurement:md/requirements/test-coverage.md:618–633
:::{req} check.measurement
The coverage check MUST fail when no usable coverage has been collected, or when
a selected latest attempt has missing, unreadable, or stale coverage. It MUST
distinguish these measurement failures from measured lines with zero execution
and from individual functions absent from otherwise usable coverage. Exception
evidence MUST NOT excuse measurement failures or permit substitution of an
older attempt. Excluded historical runs and incompatible configurations MUST
NOT by themselves cause failure.
Coverage whose format does not support the function attribution required by
{cite}`requirements.test-coverage.check.functions` MUST be rejected with guidance
to recollect coverage. When missing or corrupt metadata prevents establishing
the latest-per-test selection or active configuration, the check MUST fail
rather than silently use remaining records. Historical data MAY be disregarded
without failure only when its exclusion can be established.
:::
Input 8: outline src/execution_coverage/check.rs fn[check_saved]
- File:
src/execution_coverage/check.rs - Selector:
fn[check_saved] - Kind:
fn src/execution_coverage/check.rs:294–559
// {impl}`requirements.test-coverage.index.gaps`
// {impl}`requirements.test-coverage.index.gaps.summary`
pub(super) fn check_saved(root: &Path, saved: &book::SavedCoverage) -> io::Result<PolicyReport> {
let mut errors = Vec::new();
if saved.uncertain_history {
errors.push("Coverage history is incomplete: cannot establish latest-per-test selection or active build configuration. Repair or remove corrupt build artifacts, then recollect coverage.".into());
}
if saved.selected.is_empty() {
errors.push(
"No usable coverage has been collected. Run `habeas coverage -- --workspace`.".into(),
);
}
if saved.uncertain_history || saved.selected.is_empty() {
errors.extend(saved.diagnostics.iter().cloned());
}
let selected: Vec<_> = saved
.selected
.iter()
.map(|&index| &saved.records[index])
.collect();
for record in &selected {
let label = format!("{} / {}", record.attempt.binary, record.attempt.test);
if !record.fresh {
errors.push(format!(
"{label}: stale coverage; recollect after source or build-input changes."
));
}
if !book::readable(record) {
errors.push(format!(
"{label}: missing or unreadable coverage: {}.",
record
.attempt
.diagnostics
.iter()
.chain(
record
.attempt
.processes
.iter()
.filter_map(|process| process.diagnostic.as_ref())
)
.cloned()
.collect::<Vec<_>>()
.join("; ")
));
}
if record
.attempt
.processes
.iter()
.any(|process| process.functions.is_none())
{
errors.push(format!("{label}: coverage format lacks function attribution; recollect coverage with this Habeas version."));
}
for process in &record.attempt.processes {
if process.functions.iter().flatten().any(|function| {
function.line == 0
|| function.column == 0
|| !record.run.sources.contains_key(&function.file)
}) {
errors.push(format!(
"{label}: corrupt function attribution; recollect coverage."
));
}
}
}
let totals = book::union(selected.iter().copied());
if totals.is_empty() && !selected.is_empty() {
errors.push("No usable instrumented lines are available; recollect coverage.".into());
}
// Source discovery, parsing and citation checks remain independent of
// measurement. No exception can clear a measurement failure.
let measured = errors.is_empty();
let mut counters = BTreeMap::<(String, u32, u32), u64>::new();
for record in &selected {
for process in &record.attempt.processes {
for function in process.functions.iter().flatten() {
counters
.entry((function.file.clone(), function.line, function.column))
.and_modify(|count| *count = (*count).max(function.count))
.or_insert(function.count);
}
}
}
let outlines = OutlineCache::default();
let accepted = exceptions(root, &outlines, &mut errors)?;
let before_discovery = errors.len();
let files = crate::evidence::discovered_files(root, &mut errors);
let mut counts_complete =
measured && !saved.discovery_failed && errors.len() == before_discovery;
let mut policies = Vec::new();
let mut text = String::from("File execution coverage (80% target):\n");
let mut used = Vec::new();
for path in crate::rust_coverage::rust_files(root, &files) {
let file = path
.strip_prefix(root)
.map_err(io::Error::other)?
.to_string_lossy()
.into_owned();
let parsed = outlines.parse(root, &file);
let inventory = match parsed.as_ref() {
Ok(parsed) => inventory(&parsed.source, &parsed.outline)
.map_err(|error| format!("{file}: {error}")),
Err(error) => Err(error.clone()),
};
let inventory = match inventory {
Ok(inventory) => Some(inventory),
Err(error) => {
errors.push(error);
counts_complete = false;
None
}
};
if !measured {
continue;
}
let lines: Vec<_> = totals
.range((file.clone(), 0)..=(file.clone(), u32::MAX))
.map(|((_, line), count)| (*line, *count))
.collect();
let covered = lines.iter().filter(|(_, count)| *count > 0).count();
let total = lines.len();
// Measured file thresholds do not depend on parsing. Inventory is
// needed only for function attribution and zero-line exemptions.
if inventory.is_none() && total == 0 {
continue;
}
let (functions, no_obligations) = inventory.unwrap_or_default();
let passes = threshold(covered, total);
let exempt = total == 0 && no_obligations;
let exception = accepted.get(&(file.clone(), String::new())).cloned();
let waiver = exception
.as_ref()
.is_some_and(|exception| exception.accepted);
let mut obligations = Vec::new();
let label = if total == 0 {
if exempt {
"no executable obligations".to_owned()
} else {
"not measured".to_owned()
}
} else {
format!(
"{covered}/{total} ({:.1}%)",
100.0 * covered as f64 / total as f64
)
};
text.push_str(&format!(
"- {file}: {label} — {}\n",
if passes || exempt {
"pass"
} else if waiver {
"accepted exception"
} else {
"FAIL"
}
));
if !passes && !exempt {
obligations.push(Obligation {
selector: String::new(),
line: 1,
measurement: format!(
"{label}; 80% target; uncovered lines: {}",
gaps(
lines
.iter()
.filter(|(_, count)| *count == 0)
.map(|(line, _)| *line)
)
),
exception,
});
if waiver {
used.push(format!("{file}: file threshold ({label})"));
} else {
errors.push(format!("{file}: {} without a current accepted `habeas:coverage` citation on the file root.",
if total == 0 { "executable code is not measured".to_owned() } else { format!("below 80%; uncovered lines: {}", gaps(lines.iter().filter(|(_, count)| *count == 0).map(|(line, _)| *line))) }));
}
}
for function in functions {
// Attribute expansion can remove modifiers: tokio::test's wrapper
// starts at the original fn keyword rather than the async token.
// Both points belong to this declaration, never a nested body.
let keys = [
(file.clone(), function.line, function.column),
(file.clone(), function.keyword.0, function.keyword.1),
];
if keys
.iter()
.any(|key| counters.get(key).is_some_and(|&count| count > 0))
{
continue;
}
let state = if keys.iter().any(|key| counters.contains_key(key)) {
"zero execution"
} else {
"not measured"
};
let exception = accepted
.get(&(file.clone(), function.selector.clone()))
.cloned();
let waiver = exception
.as_ref()
.is_some_and(|exception| exception.accepted);
obligations.push(Obligation {
selector: function.selector.clone(),
line: function.line,
measurement: state.into(),
exception,
});
if waiver {
used.push(format!("{file}#{}: {state}", function.selector));
} else {
errors.push(format!("{file}:{} #{}: {state}; requires a current accepted `habeas:coverage` citation on this function.", function.line, function.selector));
}
}
policies.push(FilePolicy {
file,
covered,
total,
obligations,
});
}
text.push_str(&format!(
"\nSelected {} test attempts in the active build configuration.\n",
selected.len()
));
for record in &selected {
if record.run.outcome != "success" || record.attempt.outcome != "success" {
text.push_str(&format!(
"Recorded outcome: {} / {}: run {}, attempt {}.\n",
record.attempt.binary,
record.attempt.test,
record.run.outcome,
record.attempt.outcome
));
}
}
if !used.is_empty() {
text.push_str("\nAccepted exceptions (do not increase execution coverage):\n");
for exception in used {
text.push_str(&format!("- {exception}\n"));
}
}
let mut seen = std::collections::BTreeSet::new();
errors.retain(|error| seen.insert(error.clone()));
if !errors.is_empty() {
text.push_str("\nUnsatisfied obligations and invalid evidence:\n");
for error in &errors {
text.push_str(&format!("- {error}\n"));
}
}
let passed = errors.is_empty();
text.push_str(if passed {
"\nCoverage check passed.\n"
} else {
"\nCoverage check failed.\n"
});
Ok(PolicyReport {
report: CheckReport { passed, text },
files: policies,
counts_complete,
measured,
findings: errors,
})
}