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.index.freshness

Requirements index · View definition

evidence Valid

Requirement

Only records whose captured source inputs match the current project source and whose build configurations are compatible MAY contribute execution counts to the combined view of cite requirements.test-coverage.index.selection. Records invalidated by a source change, or whose compatibility cannot be established, MUST be identified as stale or unavailable and excluded from the combined coverage totals. Their per-process reports and matching captured source MUST remain retained in the build artifacts until those artifacts are removed.

Rationale

The reviewed tests adequately check requirements.test-coverage.index.freshness. Each obligation maps to at least one marked test with assertions.

Only fresh, compatible records contribute.

  • src/execution_coverage/book.rs#mod[tests]/fn[filtered_runs_union_latest_attempts_and_invalidate_with_saved_source] first shows 2/2 (100.0%) for fresh records. After code.rs changes, it asserts “gap counts unavailable” and “stale coverage; recollect”.
  • The same test records a newer attempt under a different build configuration (build-b). It then asserts “historical build configuration”, 1/1 (100.0%) and “1 selected test attempts”. So records from the other configuration are excluded from the totals.
  • src/execution_coverage.rs#mod[tests]/fn[source_and_build_inputs_invalidate_on_addition_removal_and_dirty_content] exercises fresh directly. It asserts staleness for a modified source file, an added source file, a removed source file, and changed, added or removed Cargo.toml, Cargo.lock and rust-toolchain.toml. It also covers new files in watched input directories, a watched path that did not exist when captured, and a dirty working tree with an unchanged revision. It asserts freshness again after each restore.
  • src/execution_coverage/book.rs#mod[tests]/fn[cargo_launch_metadata_does_not_invalidate_but_caller_build_environment_does] shows that Cargo-supplied package metadata keeps a record fresh. It also shows that changes to CC, RUSTFLAGS, CARGO_PROFILE_*, CARGO_TARGET_*_LINKER and a user build variable make it stale.
  • tests/execution_coverage.rs#fn[real_build_captures_dependency_files_and_environment_for_read_only_freshness_checks] uses a real build. It checks that include_str! files, build.rs, Cargo.lock and rerun-if-changed inputs are captured, along with compile-time and build-script environment variables. Changing any of them makes the rendered book report “1 stale test attempts”.

Stale or unavailable records are identified and excluded.

  • src/execution_coverage/book.rs#mod[tests]/fn[incomplete_attempts_do_not_label_their_files_as_unmeasured_in_a_partial_map] covers a fresh record alongside an unavailable one, and then alongside a stale one. It asserts “1 unavailable test attempts” and “1 stale test attempts”. It also asserts that no per-file map is shown, so the unavailable record does not produce partial totals.

  • src/execution_coverage/book.rs#mod[tests]/fn[unreadable_history_cannot_reintroduce_an_older_success] covers each way compatibility or availability cannot be established:

    • an unreadable newest attempt;
    • missing captured source (“Matching captured source is missing”);
    • unsupported schema 99 (“Coverage history is incomplete”);
    • a missing raw profile (“A retained raw profile is missing”).

    Each case asserts “gap counts unavailable”, and the first asserts the old 1/1 (100.0%) is not reintroduced.

Reports and captured source stay retained.

  • In filtered_runs_union_latest_attempts_and_invalidate_with_saved_source, load_saved still returns every record after the source change. Each record’s run.sources["code.rs"] still contains the original fn one() {}.
  • The real-build test asserts retained_files(&storage) == before after the stale renders. That covers the retained per-process reports and profiles after the stale renders.

Gaps. The stale-selected-plus-fresh-selected mix is only asserted through “unavailable” and “stale” indicators and the absence of the per-file map. Stale totals are never directly asserted absent. The source also suggests the implementation withholds all totals in that case. That is an acceptable reading of “excluded from the combined totals”, and I did not treat it as a gap.

Inputs

Implementation

Input 9: outline src/execution_coverage/book.rs fn[populate]
// {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)
}
Input 10: outline src/execution_coverage/book.rs fn[load_saved]
// {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/book.rs mod[tests]/fn[incomplete_attempts_do_not_label_their_files_as_unmeasured_in_a_partial_map]
    // {test}`requirements.test-coverage.index.file_map`
    // {test}`requirements.test-coverage.index.file_map.table`
    // {test}`requirements.test-coverage.index.file_map.combined`
    // {test}`requirements.test-coverage.index.file_map.combined.measurement`
    // {test}`requirements.test-coverage.index.freshness`
    // {test}`requirements.test-coverage.index.file_map.minimum`
    // {test}`requirements.test-coverage.index.file_map.minimum.statuses`
    #[test]
    fn incomplete_attempts_do_not_label_their_files_as_unmeasured_in_a_partial_map() {
        let (temp, book) = fixture();
        let root = temp.path();
        fs::create_dir_all(root.join("src/nested")).unwrap();
        fs::write(root.join("src/nested/other.rs"), "fn other() {}\n").unwrap();
        let good = record(root, "good", 1, "a", &[(1, 1)]);
        let bad = record(root, "bad", 2, "a", &[]);
        let mut attempt: Attempt = load(&bad.join("attempt.json")).unwrap();
        attempt.processes[0].lines =
            BTreeMap::from([("src/nested/other.rs".into(), BTreeMap::from([(1, 1)]))]);
        save(&bad.join("attempt.json"), &attempt).unwrap();
        for path in [&good, &bad] {
            let run_path = path.parent().unwrap().parent().unwrap().join("run.json");
            let mut run: Run = load(&run_path).unwrap();
            run.sources
                .insert("src/nested/other.rs".into(), "fn other() {}\n".into());
            save(&run_path, &run).unwrap();
        }
        fs::remove_file(bad.join("1-1.profraw")).unwrap();
        let mut partial = book.clone();
        populate(&mut partial, root).unwrap();
        let index = &partial.chapters().next().unwrap().content;
        assert!(index.contains("Coverage unavailable"));
        assert!(!map_html(index).contains("data-file="));
        assert!(!map_html(index).contains("not measured"));
        assert!(!map_html(index).contains("class=\"gap-directory\""));
        assert!(!map_html(index).contains("data-min-covered="));
        assert!(!map_html(index).contains("gap-coverage-bar\""));
        assert!(index.contains("1 unavailable test attempts"));
        // A stale selected attempt leaves the same unknown per-file state.
        let run_path = bad.parent().unwrap().parent().unwrap().join("run.json");
        let mut run: Run = load(&run_path).unwrap();
        run.inputs
            .insert("missing-build-input".into(), "old-hash".into());
        save(&run_path, &run).unwrap();
        let mut stale = book;
        populate(&mut stale, root).unwrap();
        let index = &stale.chapters().next().unwrap().content;
        assert!(index.contains("Coverage unavailable"));
        assert!(!map_html(index).contains("data-file="));
        assert!(!map_html(index).contains("class=\"gap-directory\""));
        assert!(!map_html(index).contains("data-min-covered="));
        assert!(!map_html(index).contains("not measured"));
        assert!(index.contains("1 stale test attempts"));
    }
Input 4: outline src/execution_coverage/book.rs mod[tests]/fn[cargo_launch_metadata_does_not_invalidate_but_caller_build_environment_does]
    // {test}`requirements.test-coverage.storage.provenance`
    // {test}`requirements.test-coverage.index.freshness`
    #[test]
    fn cargo_launch_metadata_does_not_invalidate_but_caller_build_environment_does() {
        let (temp, book) = fixture();
        let root = temp.path();
        let attempt = record(root, "one", 1, "build-a", &[(1, 1), (2, 0)]);
        let path = attempt.parent().unwrap().parent().unwrap().join("run.json");
        let mut run: Run = load(&path).unwrap();
        // An older report captured package-specific compiler values. Reading
        // through `cargo run` supplies values for Habeas instead of this package.
        for name in [
            "CARGO_MANIFEST_DIR",
            "CARGO_PKG_VERSION",
            "CARGO_CFG_TARGET_OS",
            "CARGO_FEATURE_ALPHA",
            "CARGO_BIN_EXE_fixture",
            "OUT_DIR",
        ] {
            run.environment_inputs
                .insert(name.into(), Some("different compiled package".into()));
        }
        save(&path, &run).unwrap();
        let mut rendered = book.clone();
        populate(&mut rendered, root).unwrap();
        assert!(
            rendered
                .chapters()
                .next()
                .unwrap()
                .content
                .contains("1/2 (50.0%)")
        );
        for name in [
            "CC",
            "RUSTFLAGS",
            "CARGO_PROFILE_TEST_DEBUG",
            "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER",
            "HABEAS_FIXTURE_BUILD_INPUT",
        ] {
            let changed = format!("changed-{}", uuid::Uuid::new_v4());
            assert_ne!(std::env::var(name).ok().as_deref(), Some(changed.as_str()));
            run.environment_inputs.insert(name.into(), Some(changed));
            save(&path, &run).unwrap();
            let mut rendered = book.clone();
            populate(&mut rendered, root).unwrap();
            assert!(
                rendered
                    .chapters()
                    .next()
                    .unwrap()
                    .content
                    .contains("stale coverage; recollect"),
                "{name}"
            );
            run.environment_inputs.remove(name);
        }
    }
Input 5: outline src/execution_coverage/book.rs mod[tests]/fn[filtered_runs_union_latest_attempts_and_invalidate_with_saved_source]
    // {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 6: outline src/execution_coverage/book.rs mod[tests]/fn[unreadable_history_cannot_reintroduce_an_older_success]
    // {test}`requirements.test-coverage.index.selection`
    // {test}`requirements.test-coverage.index.unavailable`
    // {test}`requirements.test-coverage.index.freshness`
    // {test}`requirements.test-coverage.storage.outcomes`
    // {test}`requirements.test-coverage.index.file_map.combined.measurement`
    #[test]
    fn unreadable_history_cannot_reintroduce_an_older_success() {
        let (temp, mut book) = fixture();
        record(temp.path(), "one", 1, "a", &[(1, 1)]);
        let newest = record(temp.path(), "one", 2, "a", &[(1, 0)]);
        fs::write(newest.join("attempt.json"), "not JSON").unwrap();
        populate(&mut book, temp.path()).unwrap();
        let index = &book.chapters().next().unwrap().content;
        assert!(index.contains("cannot establish latest-per-test selection"));
        assert!(index.contains("gap counts unavailable"));
        assert!(!index.contains("1/1 (100.0%)"));
        let (temp, mut book) = fixture();
        let newest = record(temp.path(), "one", 1, "a", &[(1, 1)]);
        let path = newest.parent().unwrap().parent().unwrap().join("run.json");
        let mut run: Run = load(&path).unwrap();
        run.sources.clear();
        save(&path, &run).unwrap();
        populate(&mut book, temp.path()).unwrap();
        assert!(
            book.chapters()
                .next()
                .unwrap()
                .content
                .contains("missing or unreadable coverage")
        );
        assert!(
            book.chapters()
                .next()
                .unwrap()
                .content
                .contains("Matching captured source is missing")
        );
        // Unsupported metadata cannot establish compatibility for combined totals.
        let (temp, mut book) = fixture();
        let attempt = record(temp.path(), "one", 1, "a", &[(1, 1)]);
        let path = attempt.parent().unwrap().parent().unwrap().join("run.json");
        let mut run: Run = load(&path).unwrap();
        run.schema = 99;
        save(&path, &run).unwrap();
        populate(&mut book, temp.path()).unwrap();
        let index = &book.chapters().next().unwrap().content;
        assert!(index.contains("Coverage history is incomplete"));
        assert!(index.contains("gap counts unavailable"));
        // A retained result with an unreadable/missing raw profile is unavailable.
        let (temp, mut book) = fixture();
        let attempt = record(temp.path(), "one", 1, "a", &[(1, 1)]);
        fs::remove_file(attempt.join("1-1.profraw")).unwrap();
        populate(&mut book, temp.path()).unwrap();
        assert!(
            book.chapters()
                .next()
                .unwrap()
                .content
                .contains("missing or unreadable coverage")
        );
        assert!(
            book.chapters()
                .next()
                .unwrap()
                .content
                .contains("gap counts unavailable")
        );
        assert!(
            book.chapters()
                .next()
                .unwrap()
                .content
                .contains("A retained raw profile is missing")
        );
    }
Input 7: outline src/execution_coverage.rs mod[tests]/fn[source_and_build_inputs_invalidate_on_addition_removal_and_dirty_content]
  • File: src/execution_coverage.rs
  • Selector: mod[tests]/fn[source_and_build_inputs_invalidate_on_addition_removal_and_dirty_content]
  • Kind: fn
  • src/execution_coverage.rs:357–435
    // {test}`requirements.test-coverage.storage.provenance`
    // {test}`requirements.test-coverage.index.freshness`
    #[test]
    fn source_and_build_inputs_invalidate_on_addition_removal_and_dirty_content() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();
        let target = root.join("target");
        fs::write(root.join("Cargo.toml"), "[workspace]\n").unwrap();
        fs::write(root.join("Cargo.lock"), "lock content").unwrap();
        fs::write(root.join("code.rs"), "fn original() {}\n").unwrap();
        fs::create_dir(root.join("generated-inputs")).unwrap();
        fs::create_dir(root.join("generated-inputs/node_modules")).unwrap();
        fs::write(root.join("generated-inputs/data"), "initial").unwrap();
        let mut inputs = input_hashes(&workspace_inputs(root, &target).unwrap()).unwrap();
        for path in [root.join("generated-inputs"), root.join("not-created-yet")] {
            inputs.insert(
                path.to_string_lossy().into_owned(),
                input_digest(&path, Some(&target)).unwrap(),
            );
        }
        let run = Run {
            schema: 1,
            id: "fixture".into(),
            started: 1,
            command: vec![],
            selection: vec![],
            configuration: "config".into(),
            configuration_inputs: BTreeMap::new(),
            sources: BTreeMap::new(),
            inputs,
            environment_inputs: BTreeMap::new(),
            revision: Some("unchanged revision".into()),
            dirty: Some(true),
            outcome: "success".into(),
            diagnostics: vec![],
        };
        assert!(fresh(&run, root, &target).unwrap());
        for (path, content) in [
            ("code.rs", "fn dirty() {}\n"),
            ("added.rs", "fn added() {}\n"),
            ("Cargo.lock", "different lock"),
            (
                "Cargo.toml",
                "[workspace]\n[workspace.package]\nversion = '2.0.0'\n",
            ),
            (
                "member/Cargo.toml",
                "[package]\nname = 'other'\nversion = '1.0.0'\n",
            ),
            ("rust-toolchain.toml", "[toolchain]\nchannel = 'stable'\n"),
            ("generated-inputs/new", "new watched input"),
            (
                "generated-inputs/node_modules/data",
                "watched non-Rust input",
            ),
            ("not-created-yet", "now created"),
        ] {
            let path = root.join(path);
            let previous = fs::read(&path).ok();
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            fs::write(&path, content).unwrap();
            assert!(!fresh(&run, root, &target).unwrap(), "{}", path.display());
            match previous {
                Some(previous) => fs::write(path, previous).unwrap(),
                None => fs::remove_file(path).unwrap(),
            }
            assert!(fresh(&run, root, &target).unwrap());
        }
        for name in ["Cargo.toml", "Cargo.lock"] {
            let path = root.join(name);
            let original = fs::read(&path).unwrap();
            fs::remove_file(&path).unwrap();
            assert!(!fresh(&run, root, &target).unwrap(), "{name}");
            fs::write(path, original).unwrap();
            assert!(fresh(&run, root, &target).unwrap());
        }
        fs::remove_file(root.join("code.rs")).unwrap();
        assert!(!fresh(&run, root, &target).unwrap());
    }
Input 8: outline tests/execution_coverage.rs fn[real_build_captures_dependency_files_and_environment_for_read_only_freshness_checks]
// {test}`requirements.test-coverage.storage.provenance`
// {test}`requirements.test-coverage.index.freshness`
#[test]
fn real_build_captures_dependency_files_and_environment_for_read_only_freshness_checks() {
    use mdbook_preprocessor::book::{Book, Chapter};
    use std::io::Write;
    use std::process::Stdio;
    let temp = fixture();
    let root = temp.path();
    fs::write(root.join("included data.txt"), "included").unwrap();
    fs::write(root.join("build-input.data"), "build input").unwrap();
    fs::write(
        root.join("build.rs"),
        "fn main() {\nprintln!(\"cargo:rerun-if-changed=build-input.data\");\nprintln!(\"cargo:rerun-if-env-changed=HABEAS_FIXTURE_BUILD_ENV\");\n}\n",
    )
    .unwrap();
    let source = root.join("src/lib.rs");
    fs::write(
        &source,
        fs::read_to_string(&source).unwrap().replace(
            "fn second() {",
            "fn second() { assert_eq!(include_str!(\"../included data.txt\"), \"included\"); assert_eq!(env!(\"HABEAS_FIXTURE_RUST_ENV\"), \"compiler-value\");",
        ),
    )
    .unwrap();
    assert_success(
        &Command::new(env!("CARGO_BIN_EXE_habeas"))
            .args(["coverage", "--", "-E", "test(second)"])
            .current_dir(root)
            .env("HABEAS_FIXTURE_RUST_ENV", "compiler-value")
            .env("HABEAS_FIXTURE_BUILD_ENV", "build-value")
            .env("CARGO_NET_OFFLINE", "true")
            .env_remove("CARGO_TARGET_DIR")
            .env_remove("CARGO_BUILD_TARGET_DIR")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .env_remove("HABEAS_PREVIOUS_WORKSPACE_WRAPPER")
            .env_remove("HABEAS_COVERAGE_RUN")
            .env_remove("HABEAS_COVERAGE_FEATURE_LEDGER")
            .output()
            .unwrap(),
    );
    let saved = runs(root);
    assert_eq!(saved.len(), 1);
    let recorded_inputs = saved[0].1["inputs"].as_object().unwrap();
    for file in [
        "included data.txt",
        "build-input.data",
        "build.rs",
        "Cargo.lock",
    ] {
        assert!(
            recorded_inputs.keys().any(|path| {
                fs::canonicalize(path).ok() == Some(fs::canonicalize(root.join(file)).unwrap())
            }),
            "capture omitted {file}: {:?}",
            recorded_inputs.keys().collect::<Vec<_>>()
        );
    }
    assert_eq!(
        saved[0].1["environment_inputs"]["HABEAS_FIXTURE_RUST_ENV"],
        "compiler-value"
    );
    assert_eq!(
        saved[0].1["environment_inputs"]["HABEAS_FIXTURE_BUILD_ENV"],
        "build-value"
    );
    let render = |compiler: &str, build: &str| {
        let mut book = Book::new();
        book.push_item(Chapter::new(
            "Coverage",
            ":::{coverage-index}\n:::\n".into(),
            "coverage.md",
            vec![],
        ));
        let input = serde_json::json!([{
            "root": root, "config": {"book":{"src":"md"}}, "renderer":"html", "mdbook_version":"0.5.3"
        }, book]);
        let mut child = Command::new(env!("CARGO_BIN_EXE_habeas"))
            .arg("mdbook")
            .current_dir(root)
            .env("HABEAS_FIXTURE_RUST_ENV", compiler)
            .env("HABEAS_FIXTURE_BUILD_ENV", build)
            .env("CARGO_NET_OFFLINE", "true")
            .env_remove("CARGO_TARGET_DIR")
            .env_remove("CARGO_BUILD_TARGET_DIR")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(input.to_string().as_bytes())
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert_success(&output);
        serde_json::from_slice::<Book>(&output.stdout)
            .unwrap()
            .chapters()
            .find(|chapter| chapter.name == "Coverage gaps")
            .unwrap()
            .content
            .clone()
    };
    let storage = root.join("target/habeas/coverage");
    let before = retained_files(&storage);
    assert!(!render("compiler-value", "build-value").contains("stale test attempts"));
    for file in ["included data.txt", "build-input.data"] {
        let path = root.join(file);
        let original = fs::read(&path).unwrap();
        fs::write(&path, "changed").unwrap();
        assert!(
            render("compiler-value", "build-value").contains("1 stale test attempts"),
            "{file}"
        );
        fs::write(path, original).unwrap();
        assert!(!render("compiler-value", "build-value").contains("stale test attempts"));
    }
    for (compiler, build) in [("changed", "build-value"), ("compiler-value", "changed")] {
        assert!(render(compiler, build).contains("1 stale test attempts"));
    }
    assert_eq!(retained_files(&storage), before);
}

Referenced definitions

Input 2: requirements selection requirements.test-coverage.index.selection
:::{req} index.selection
The coverage index MUST combine the most recent recorded test attempt for each
nextest binary and test name among the retained runs. "Most recent" MUST refer
to when the attempt started, including failed or interrupted attempts. A newer
filtered run MUST update only the tests it executes, leaving other compatible
test records available to the combined view. A newer attempt with missing or
unreadable coverage MUST be shown as unavailable rather than replaced with an
older successful attempt. Results from incompatible instrumented build
configurations MUST NOT be combined under
{cite}`requirements.test-coverage.storage.configuration`.

The main combined view MUST use the instrumented build configuration of the
most recently started recorded test attempt. Latest-per-test selection MUST
occur within that configuration. Records from other configurations MUST be
identified as excluded historical coverage. Configuration selection MUST use
recorded metadata without building or executing tests.
:::

Other sources

Input 1: requirements selection requirements.test-coverage.index.freshness
:::{req} index.freshness
Only records whose captured source inputs match the current project source and
whose build configurations are compatible MAY contribute execution counts to
the combined view of {cite}`requirements.test-coverage.index.selection`.
Records invalidated by a source change, or whose compatibility cannot be
established, MUST be identified as stale or unavailable and excluded from the
combined coverage totals. Their per-process reports and matching captured source
MUST remain retained in the build artifacts until those artifacts are removed.
:::
Input 11: outline src/execution_coverage/book.rs fn[populate_in]
// {impl}`requirements.test-coverage.index.navigation`
// {impl}`requirements.test-coverage.index.source`
// {impl}`requirements.test-coverage.index.guidance`
// {impl}`requirements.test-coverage.index.summary`
// {impl}`requirements.test-coverage.index.details`
// {impl}`requirements.test-coverage.index.file_map.test`
// {impl}`requirements.test-coverage.index.file_map.combined.details`
pub(super) fn populate_in(
    book: &mut Book,
    project: &Path,
    target: Option<PathBuf>,
    parent: &Path,
) -> io::Result<()> {
    let index_path = parent.with_extension("").join("coverage.md");
    let saved = load_saved(project, target);
    let root = workspace_root(project).unwrap_or_else(|_| project.to_path_buf());
    let policy = super::check::check_saved(&root, &saved)?;
    let SavedCoverage {
        records,
        selected,
        diagnostics,
        uncertain_history,
        current_files,
        discovery_failed: _,
    } = saved;
    let note_files = if policy.measured {
        policy
            .files
            .iter()
            .filter(|file| !file.obligations.is_empty())
            .map(|file| file.file.clone())
            .collect()
    } else {
        current_files
    };
    let mut summary = String::from("# Coverage gaps\n\n");
    summary.push_str(&gaps_map(&policy, &index_path, selected.len()));
    if policy.measured {
        let totals = union(selected.iter().map(|&index| &records[index]));
        let covered = totals.values().filter(|&&count| count > 0).count();
        summary.push_str(&format!("Line coverage: **{covered}/{} ({:.1}%)** from the union of instrumented file-and-line locations.\n\n", totals.len(), 100.0 * covered as f64 / totals.len() as f64));
    }
    if uncertain_history {
        summary.push_str("Coverage history is incomplete: cannot establish latest-per-test selection. Combined totals are unavailable until the affected build artifacts are repaired or removed.\n\n");
    }
    if records.is_empty() {
        summary.push_str("No test coverage is available. Run `habeas coverage` (or `cargo habeas coverage` in this repository), then rebuild the book.\n\n");
    }
    let stale = selected
        .iter()
        .filter(|&&index| !records[index].fresh)
        .count();
    let incomplete = selected
        .iter()
        .filter(|&&index| records[index].fresh && !readable(&records[index]))
        .count();
    let historical = records.last().map_or(0, |latest| {
        records
            .iter()
            .filter(|record| record.run.configuration != latest.run.configuration)
            .count()
    });
    if stale > 0 || incomplete > 0 || historical > 0 {
        summary.push_str(&format!(
            "**Excluded coverage:** {stale} stale test attempts; {incomplete} unavailable test attempts; {historical} attempts from a historical build configuration.\n\n"
        ));
    }
    for diagnostic in diagnostics {
        summary.push_str(&format!(
            "**Coverage diagnostic:** {}\n\n",
            escaped(&diagnostic)
        ));
    }
    let existing: BTreeSet<_> = book
        .chapters()
        .filter_map(|chapter| chapter.path.clone())
        .collect();
    let mut generated = BTreeSet::from([index_path.clone()]);
    if existing.contains(&index_path) {
        return Err(io::Error::other(format!(
            "coverage index path conflicts with an existing chapter: {}",
            index_path.display()
        )));
    }
    let mut details = Vec::new();
    let notes_root = workspace_root(project).unwrap_or_else(|_| project.to_path_buf());
    for chapter in super::notes::pages(&notes_root, &note_files, &index_path) {
        let path = chapter
            .path
            .as_ref()
            .expect("file notes have a render path");
        if existing.contains(path) || !generated.insert(path.clone()) {
            return Err(io::Error::other(format!(
                "coverage report path conflicts with an existing chapter: {}",
                path.display()
            )));
        }
        details.push(BookItem::Chapter(chapter));
    }
    summary.push_str("## Collect coverage and check CI policy\n\n");
    summary.push_str(super::GUIDANCE);
    summary.push('\n');
    let mut coverage = Some(Chapter::new("Coverage gaps", summary, &index_path, vec![]));
    let mut found = false;
    book.for_each_chapter_mut(|chapter| {
        if chapter.path.as_deref() == Some(parent) {
            found = true;
            chapter.content.push_str(&format!(
                "\n\n[Coverage gaps]({}) — uncovered obligations and their explanations.\n",
                crate::chapter_href(parent, &index_path, None)
            ));
            let mut page = coverage.take().expect("requirements index occurs once");
            page.source_path = None;
            page.parent_names = chapter.parent_names.clone();
            page.parent_names.push(chapter.name.clone());
            page.number = chapter.number.as_ref().map(|number| {
                let mut parts = number.to_vec();
                parts.push(1);
                SectionNumber::new(parts)
            });
            for (offset, item) in details.iter_mut().enumerate() {
                let BookItem::Chapter(child) = item else {
                    unreachable!()
                };
                child.parent_names = page.parent_names.clone();
                child.parent_names.push(page.name.clone());
                child.number = page.number.as_ref().map(|number| {
                    let mut parts = number.to_vec();
                    parts.push(offset as u32 + 1);
                    SectionNumber::new(parts)
                });
            }
            page.sub_items.append(&mut details);
            fn renumber(chapter: &mut Chapter, number: Vec<u32>) {
                chapter.number = Some(SectionNumber::new(number.clone()));
                let mut next = 1;
                for item in &mut chapter.sub_items {
                    if let BookItem::Chapter(child) = item {
                        let mut parts = number.clone();
                        parts.push(next);
                        renumber(child, parts);
                        next += 1;
                    }
                }
            }
            if let Some(number) = &chapter.number {
                let mut next = 2;
                for item in &mut chapter.sub_items {
                    if let BookItem::Chapter(child) = item {
                        let mut parts = number.to_vec();
                        parts.push(next);
                        renumber(child, parts);
                        next += 1;
                    }
                }
            }
            chapter.sub_items.insert(0, BookItem::Chapter(page));
        }
    });
    if !found {
        return Err(io::Error::other(
            "requirements index chapter disappeared before coverage generation",
        ));
    }
    Ok(())
}
Input 12: outline src/execution_coverage/book.rs mod[tests]/fn[gaps_omit_test_data_and_preserve_saved_profiles_and_sources]
    // {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"))
        );
    }