Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.test-coverage.check.scope

Requirements index · View definition

evidence Valid

Requirement

The coverage check MUST consider every explicitly declared function or method with a body in the first-party Rust sources of cite requirements.references.rust_item_coverage, including test functions, test helpers, and default trait methods. Declarations without bodies MUST NOT create execution-coverage obligations. Source discovery or parsing failures MUST cause the check to fail rather than silently omit functions.

A function whose measurement cannot be established MUST be reported as not measured rather than silently excluded. Functions excluded by the selected build configuration require exception evidence under cite requirements.test-coverage.check.exceptions.

Rationale

The tests adequately cover requirements.test-coverage.check.scope. All the tests are in src/execution_coverage/check.rs#mod[tests].

Obligations and the tests that cover them

  • Every function or method with a body is considered, including test functions, helpers and default trait methods.
    • methods_tests_and_helpers_are_included_and_discovery_failures_are_reported uses an inherent method (impl[S]/fn[method]), a #[test] fn (mod[tests]/fn[case]) and a helper (mod[tests]/fn[helper]). It asserts each one is reported as zero execution.
    • default_trait_bodies_and_cfg_exclusions_are_obligations_but_declarations_are_not asserts that the default body #trait[T]/fn[body] is reported as zero execution.
  • Declarations without bodies create no obligation.
    • The same default-trait-bodies test asserts that fn[declaration] never appears in the report.
    • It also checks inventory directly. A source with only struct S; and a trait declaration yields no obligations. A macro invocation and a #[derive] struct yield none either.
  • Root vendor is out of scope, but src/vendor is first-party.
    • post_suite_scope_excludes_root_vendor_but_includes_source_vendor asserts that src/vendor/first_party.rs is reported and that the check fails.
    • It also asserts - vendor/foreign.rs is absent. Both the file-summary lines and the error lines in check_saved start with - <file>, so this assertion would catch a foreign file in either place.
  • Source discovery and parsing failures make the check fail.
    • The discovery-failure case in methods_tests_and_helpers_are_included_and_discovery_failures_are_reported corrupts .git/index. It asserts the check fails with “cannot discover reference sources”.
    • unmeasured_executable_files_and_parse_failures_do_not_disappear writes malformed Rust (fn malformed(). It asserts the check fails with “cannot parse rust source”.
  • A function whose measurement cannot be established is reported as not measured.
    • unmeasured_executable_files_and_parse_failures_do_not_disappear asserts code.rs: not measured — FAIL and #fn[missing]: not measured when the coverage data has no entry for the function.
    • A file with no executable obligations is shown as passing, which checks that the “not measured” label is not applied indiscriminately.
    • The default-trait-bodies test shows the same for a function that is absent from the coverage data.
  • Functions excluded by build configuration need exception evidence.
    • The #[cfg(any())] fn excluded case in default_trait_bodies_and_cfg_exclusions_are_obligations_but_declarations_are_not asserts #fn[excluded]: not measured and a failed check when no exception exists.
    • The exception mechanism itself belongs to the cited requirements.test-coverage.check.exceptions. Separate tests such as accepted_file_and_function_explanations_remain_separate_from_execution cover it, and the cited requirement is not reassessed here.
  • Nested functions and closures.
    • overlapping_nested_functions_and_closures_do_not_cover_the_parent checks that execution of an inner function or closure does not cover the outer function, and that zero execution of the inner function is attributed to the inner function.
    • This supports “every function” by keeping nested functions as separate obligations.

Gaps

I found no obligation or named boundary case without a test and assertion, so there are no gaps to report. There are no acknowledgments and none are needed.

Inputs

Tests

Input 4: outline src/execution_coverage/check.rs mod[tests]/fn[post_suite_scope_excludes_root_vendor_but_includes_source_vendor]
    // {test}`requirements.test-coverage.check.scope`
    #[test]
    fn post_suite_scope_excludes_root_vendor_but_includes_source_vendor() {
        let temp = fixture("fn main() {}\n");
        let root = temp.path();
        for file in ["vendor/foreign.rs", "src/vendor/first_party.rs"] {
            fs::create_dir_all(root.join(file).parent().unwrap()).unwrap();
            fs::write(root.join(file), "fn unmeasured() {}\n").unwrap();
        }
        record(root, "main", 1, "same", vec![process(root, &[(1, 1)], 1)]);
        let result = report(root);
        assert!(!result.passed);
        assert!(result.text.contains("src/vendor/first_party.rs"));
        assert!(!result.text.contains("- vendor/foreign.rs"));
    }
Input 5: outline src/execution_coverage/check.rs mod[tests]/fn[overlapping_nested_functions_and_closures_do_not_cover_the_parent]
    // {test}`requirements.test-coverage.check.functions`
    // {test}`requirements.test-coverage.check.scope`
    #[test]
    fn overlapping_nested_functions_and_closures_do_not_cover_the_parent() {
        let source = "fn outer() { fn inner() {} let f = || {}; }\n";
        let temp = fixture(source);
        let root = temp.path();
        let mut p = process(root, &[(1, 1)], 0);
        p.functions.as_mut().unwrap()[1].count = 1;
        p.functions.as_mut().unwrap().push(FunctionExecution {
            file: "code.rs".into(),
            line: 1,
            column: (source.find("||").unwrap() + 3) as u32,
            count: 1,
        });
        record(root, "nested", 1, "same", vec![p]);
        let result = report(root);
        assert!(!result.passed);
        assert!(result.text.contains("#fn[outer]: zero execution"));
        assert!(!result.text.contains("#fn[outer]/fn[inner]:"));
        let mut p = process(root, &[(1, 1)], 1);
        p.functions.as_mut().unwrap()[1].count = 0;
        record(root, "nested", 2, "same", vec![p]);
        let result = report(root);
        assert!(result.text.contains("#fn[outer]/fn[inner]: zero execution"));
        assert!(!result.text.contains("#fn[outer]:"));
    }
Input 6: outline src/execution_coverage/check.rs mod[tests]/fn[default_trait_bodies_and_cfg_exclusions_are_obligations_but_declarations_are_not]
    // {test}`requirements.test-coverage.check.scope`
    // {test}`requirements.test-coverage.check.threshold`
    // {test}`requirements.test-coverage.check.functions`
    #[test]
    fn default_trait_bodies_and_cfg_exclusions_are_obligations_but_declarations_are_not() {
        let temp =
            fixture("trait T { fn declaration(); fn body() {} }\n#[cfg(any())] fn excluded() {}\n");
        let root = temp.path();
        let mut p = process(root, &[(1, 1)], 0);
        p.functions.as_mut().unwrap().retain(|f| f.line == 1);
        record(root, "traits", 1, "same", vec![p]);
        let result = report(root);
        assert!(!result.passed);
        assert!(result.text.contains("#fn[excluded]: not measured"));
        assert!(
            result.text.contains("#trait[T]/fn[body]: zero execution"),
            "{}",
            result.text
        );
        assert!(!result.text.contains("fn[declaration]"));
        let parsed = crate::outline::parse_with(
            &crate::outline::RUST_PROFILE,
            "struct S;\ntrait T { fn declaration(); }\n",
        )
        .unwrap();
        assert!(
            inventory("struct S;\ntrait T { fn declaration(); }\n", &parsed)
                .unwrap()
                .1
        );
        let parsed =
            crate::outline::parse_with(&crate::outline::RUST_PROFILE, "make_functions!();")
                .unwrap();
        assert!(!inventory("make_functions!();", &parsed).unwrap().1);
        let parsed =
            crate::outline::parse_with(&crate::outline::RUST_PROFILE, "#[derive(Clone)] struct S;")
                .unwrap();
        assert!(!inventory("#[derive(Clone)] struct S;", &parsed).unwrap().1);
    }
Input 7: outline src/execution_coverage/check.rs mod[tests]/fn[unmeasured_executable_files_and_parse_failures_do_not_disappear]
    // {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 8: outline src/execution_coverage/check.rs mod[tests]/fn[methods_tests_and_helpers_are_included_and_discovery_failures_are_reported]
    // {test}`requirements.test-coverage.check.scope`
    // {test}`requirements.test-coverage.check.functions`
    #[test]
    fn methods_tests_and_helpers_are_included_and_discovery_failures_are_reported() {
        let source = "struct S;\nimpl S { fn method(&self) {} }\n#[cfg(test)] mod tests {\n #[test] fn case() {}\n fn helper() {}\n}\n";
        let temp = fixture(source);
        let root = temp.path();
        record(root, "a", 1, "same", vec![process(root, &[(1, 1)], 0)]);
        let result = report(root);
        for selector in [
            "impl[S]/fn[method]",
            "mod[tests]/fn[case]",
            "mod[tests]/fn[helper]",
        ] {
            assert!(
                result
                    .text
                    .contains(&format!("#{selector}: zero execution")),
                "{}",
                result.text
            );
        }
        git2::Repository::init(root).unwrap();
        fs::write(root.join(".git/index"), "corrupt Git index").unwrap();
        let result = report(root);
        assert!(!result.passed);
        assert!(
            result.text.contains("cannot discover reference sources"),
            "{}",
            result.text
        );
    }

Referenced definitions

Input 2: requirements selection requirements.references.rust_item_coverage
:::{req} rust_item_coverage
During repository validation, Habeas MUST parse every first-party Rust source file: every `.rs` file among the sources reference discovery considers under {cite}`requirements.references.discovery`, except those under the project-root `vendor` directory. Each explicitly declared function or method, including trait methods and test helpers, and each struct, enum, and union is an item that can be covered. An item is covered when it has a valid `{impl}`, `{cite}`, or `{test}` reference to a defined requirement or named example, or a valid citation of the built-in `habeas:util` under {cite}`requirements.references.util`, in a Rust comment attached to it or within its body; or when its outline node, or an outline node containing it, is recorded with its current hash as an outline input of an evidence record, a citation review, or a site review. Outline inputs recorded from selected search snippets under {cite}`requirements.authoring.finish_search.inputs` MUST count alongside mandatory inputs and additional reads. Comments belong to items under {cite}`requirements.references.outline_comments`; a comment before a field, variant, or attribute inside an item belongs to that item. A named example MUST reference a requirement under {cite}`requirements.examples.definition`. A reference in a string literal, on an enclosing module or impl block, or only in an evidence input MUST NOT count for the items it encloses. Habeas MUST report a Rust parse failure instead of silently skipping the file. Only {cite}`requirements.references.coverage.tests` and {cite}`requirements.references.coverage.examples` make an uncovered item a validation error; other items without recent coverage are warned about under {cite}`requirements.references.coverage.report`.
:::
Input 3: requirements selection requirements.test-coverage.check.exceptions
:::{req} check.exceptions
An unmet file threshold or an unexecuted or not-measured function MAY satisfy
the coverage policy only
through current, accepted, independently assessed evidence explaining why its
coverage is incomplete. An exception MUST be attached to the source file or
function whose incomplete coverage it justifies. A file-threshold exception
MUST NOT automatically excuse untested functions.
An exception MUST NOT excuse another source item's incomplete coverage.
Changes to the source item, justification, or other inputs
of its citation review MUST invalidate the affected exception under
{cite}`requirements.references.citation_review`.

A source comment or unassessed justification alone MUST NOT count as accepted
exception evidence. Function and gap identities MUST remain portable between
equivalent local and CI checkouts rather than depend on checkout paths,
run identifiers, timestamps, or process identifiers.
:::

Other sources

Input 1: requirements selection requirements.test-coverage.check.scope
:::{req} check.scope
The coverage check MUST consider every explicitly declared function or method
with a body in the first-party Rust sources of
{cite}`requirements.references.rust_item_coverage`, including test functions,
test helpers, and default trait methods. Declarations without bodies MUST NOT
create execution-coverage obligations. Source discovery or parsing failures
MUST cause the check to fail rather than silently omit functions.

A function whose measurement cannot be established MUST be reported as not
measured rather than silently excluded. Functions excluded by the selected
build configuration require exception evidence under
{cite}`requirements.test-coverage.check.exceptions`.
:::
Input 9: outline src/execution_coverage/check.rs fn[check_saved]
// {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,
    })
}