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.storage.configuration

Requirements index · View definition

evidence Valid

Requirement

Each coverage record MUST identify the recorded toolchain, compilation target, Cargo build profile, enabled features, and instrumentation-affecting compiler settings. These settings MUST determine build-configuration compatibility for the combined view. A nextest scheduling profile alone MUST NOT make otherwise compatible build configurations incompatible.

Rationale

The reviewed tests adequately cover every obligation in requirements.test-coverage.storage.configuration.

Record identifies the build settings

  • The unit test runner.rs#mod[tests]/fn[compiler_inputs_determine_compatibility_and_scheduling_does_not] asserts the recorded inputs directly. rustc holds the toolchain text, target the compilation target, and cargo-profile the profile. instrumentation contains -C instrument-coverage.
  • That test also covers the --release, -r and --cargo-profile custom profile variants, plus --all-features and --no-default-features.
  • Instrumentation-affecting compiler settings are covered by .cargo/config.toml rustflags and by the RUSTFLAGS, CARGO_PROFILE_* and CARGO_TARGET_* environment variables. The environment case runs in a child process so it doesn’t change the parent’s environment.
  • tests/execution_coverage.rs#fn[real_parallel_processes_retries_child_profiles_and_filtered_reruns] checks end to end that a saved run has configuration_inputs with rustc containing LLVM version:, a non-empty target, cargo-profile equal to test, and instrumentation containing -C instrument-coverage.
  • Enabled features are covered in two places. That integration test runs with --features alpha -Fbeta and asserts the enabled-features input holds both features. runner.rs#mod[tests]/fn[compiler_wrapper_preserves_arguments_status_and_prior_wrapper_and_records_features] checks that the feature ledger records are unique, sorted, and free of non-feature cfgs. It also checks that there is one record per package and target, and that compiler queries create no records.

Settings determine compatibility

  • The unit test asserts assert_ne! on the digest of the inputs for each of these changes: target, profile (several forms), all-features, no-default-features, the compiler version, config-file rustflags, a changed config file, and environment rustflags. This confirms each setting changes the compatibility key.
  • The integration test asserts the saved run’s configuration differs once features change.
  • book.rs#mod[tests]/fn[filtered_runs_union_latest_attempts_and_invalidate_with_saved_source] covers the combined view. Runs with the same configuration (build-a) are unioned (2 selected test attempts). A newer run with a different configuration (build-b) produces historical build configuration and 1 selected test attempts. The fixture sets configuration as a string. Together with the integration test, which ties the configuration field to the real inputs, this covers the combined-view requirement.

Scheduling profile must not split compatibility

  • The unit test passes --profile focused and asserts the key equals the baseline.
  • The integration test adds a nextest focused profile, runs with it, and asserts the saved configuration equals that of the earlier runs. It also asserts the historical attempts are retained.

I found no obligation or named boundary that lacks a test with an assertion on the outcome.

Inputs

Implementation

Input 8: outline src/execution_coverage/runner.rs fn[run]
// {impl}`requirements.test-coverage.run`
// {impl}`requirements.test-coverage.storage`
// {impl}`requirements.test-coverage.processes.reports`
// {impl}`requirements.test-coverage.processes.progress.preparation`
// {impl}`requirements.test-coverage.storage.provenance`
// {impl}`requirements.test-coverage.storage.configuration`
// {impl}`requirements.test-coverage.storage.outcomes`
// {impl}`requirements.test-coverage.failures`
pub fn run(project: &Path, supplied: &[String]) -> io::Result<i32> {
    let root = configuration::workspace_root(project)?;
    let invocation = std::env::current_dir()?;
    let args = if supplied.is_empty() {
        vec!["--workspace".to_owned()]
    } else {
        supplied.to_vec()
    };
    verify_configuration(&root, &args)?;
    let compiler_command = cargo_override_setting(&invocation, &args, "rustc")?
        .or(std::env::var("RUSTC")
            .ok()
            .or(std::env::var("CARGO_BUILD_RUSTC").ok()))
        .or(cargo_build_setting(&invocation, "rustc")?)
        .unwrap_or_else(|| "rustc".into());
    let (cov, profdata, rustc) = tools(&compiler_command)?;
    let mut metadata_command = Command::new("cargo");
    metadata_command
        .args(["metadata", "--format-version", "1", "--no-deps"])
        .current_dir(&invocation);
    for flag in [
        "--locked",
        "--offline",
        "--frozen",
        "--all-features",
        "--no-default-features",
    ] {
        if has(&args, flag) {
            metadata_command.arg(flag);
        }
    }
    for flag in ["--manifest-path"] {
        if let Some(value) = option(&args, &[flag]) {
            metadata_command.arg(flag).arg(value);
        }
    }
    let requested_features = features(&args);
    if !requested_features.is_empty() {
        metadata_command.arg("--features").arg(requested_features);
    }
    for value in options(&args, &["--config"]) {
        metadata_command.arg("--config").arg(value);
    }
    let metadata: serde_json::Value = serde_json::from_str(&output(&mut metadata_command)?)?;
    if metadata["workspace_root"].as_str().map(Path::new) != Some(root.as_path()) {
        return Err(io::Error::other(
            "--manifest-path selects a different Cargo workspace; cannot establish its collector configuration from this Habeas project",
        ));
    }
    let target = option(&args, &["--target-dir"])
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from(metadata["target_directory"].as_str().unwrap()));
    let target = if target.is_absolute() {
        target
    } else {
        invocation.join(target)
    };
    fs::create_dir_all(&target)?;
    let target = fs::canonicalize(target)?;
    let dir = target
        .join("habeas/coverage")
        .join(uuid::Uuid::new_v4().to_string());
    fs::create_dir_all(dir.join("attempts"))?;
    fs::create_dir_all(dir.join("tools"))?;
    fs::create_dir_all(dir.join("setup"))?;
    // A per-run copy avoids races with concurrent builds of the CLI itself.
    let executable = std::env::current_exe()?;
    // Keep the compiler-wrapper path stable for identical CLI builds, so a
    // focused rerun can reuse Cargo's instrumented compilation cache.
    let executable_metadata = fs::metadata(&executable)?;
    let compiler_key = digest(
        format!(
            "{}:{}:{:?}",
            executable.display(),
            executable_metadata.len(),
            executable_metadata.modified()?
        )
        .as_bytes(),
    );
    let compiler = target
        .join("habeas/tools")
        .join(compiler_key)
        .join(format!("habeas-rustc{}", std::env::consts::EXE_SUFFIX));
    let collector = compiler
        .parent()
        .unwrap()
        .join(format!("habeas{}", std::env::consts::EXE_SUFFIX));
    if !collector.is_file() {
        fs::create_dir_all(collector.parent().unwrap())?;
        let temporary = collector.with_extension(uuid::Uuid::new_v4().to_string());
        fs::copy(&executable, &temporary)?;
        fs::rename(temporary, &collector)?;
    }
    if !compiler.is_file() {
        fs::create_dir_all(compiler.parent().unwrap())?;
        let temporary = compiler.with_extension(uuid::Uuid::new_v4().to_string());
        fs::copy(&executable, &temporary)?;
        fs::rename(temporary, &compiler)?;
    }
    let config = build_configuration(&invocation, &args, &rustc)?;
    let mut inputs = input_hashes(&workspace_inputs(&root, &target)?)?;
    inputs.extend(input_hashes(&super::cargo_configs(&invocation))?);
    for value in options(&args, &["--config"])
        .into_iter()
        .filter(|value| !value.contains('='))
    {
        inputs.extend(input_hashes(&[invocation.join(value)])?);
    }
    let mut run = Run {
        schema: 1,
        id: dir.file_name().unwrap().to_string_lossy().into_owned(),
        started: now(),
        command: std::iter::once("cargo nextest run".into())
            .chain(args.iter().cloned())
            .collect(),
        selection: args.clone(),
        configuration: digest(&serde_json::to_vec(&config)?),
        configuration_inputs: config,
        sources: BTreeMap::new(),
        inputs,
        environment_inputs: BTreeMap::new(),
        revision: output(
            Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(&root),
        )
        .ok(),
        dirty: output(
            Command::new("git")
                .args(["status", "--porcelain"])
                .current_dir(&root),
        )
        .ok()
        .map(|status| !status.is_empty()),
        outcome: "interrupted".into(),
        diagnostics: Vec::new(),
    };
    save(&dir.join("run.json"), &run)?;
    let interrupts = Interrupts::new()?;
    let instrumented = target.join("habeas/instrumented").join(&run.configuration);
    let mut paths = vec![collector.parent().unwrap().to_path_buf()];
    paths.extend(std::env::split_paths(
        &std::env::var_os("PATH").unwrap_or_default(),
    ));
    // Keep compilation in its own cache, including when native Cargo settings
    // select an external build directory. Coverage storage keeps the chosen target.
    let forwarded = {
        let split = args
            .iter()
            .position(|arg| arg == "--")
            .unwrap_or(args.len());
        let mut forwarded = Vec::new();
        let mut index = 0;
        while index < split {
            if args[index] == "--target-dir" {
                index += 2;
                continue;
            }
            if args[index].starts_with("--target-dir=") {
                index += 1;
                continue;
            }
            forwarded.push(args[index].clone());
            index += 1;
        }
        forwarded.push(format!("--target-dir={}", instrumented.display()));
        forwarded.push("--config".into());
        forwarded.push(format!(
            "build.build-dir={}",
            toml::Value::String(instrumented.to_string_lossy().into_owned())
        ));
        forwarded.extend_from_slice(&args[split..]);
        forwarded
    };
    let mut command = Command::new("cargo");
    command
        .args(["nextest", "run"])
        .args(forwarded)
        .current_dir(&invocation)
        .env("HABEAS_COVERAGE_RUN", &dir)
        .env("LLVM_PROFILE_FILE", dir.join("setup/%p-%m.profraw"))
        .env("CARGO_TARGET_DIR", &instrumented)
        .env("CARGO_BUILD_BUILD_DIR", &instrumented)
        .env("RUSTC_WORKSPACE_WRAPPER", &compiler)
        .env(
            "HABEAS_COVERAGE_FEATURE_LEDGER",
            instrumented.join("features"),
        )
        .env(
            "PATH",
            std::env::join_paths(paths).map_err(io::Error::other)?,
        );
    if let Some(previous) = std::env::var_os("RUSTC_WORKSPACE_WRAPPER") {
        command.env("HABEAS_PREVIOUS_WORKSPACE_WRAPPER", previous);
    }
    // The instrumented cache is for this compilation. Tests that invoke Cargo
    // must still observe the caller's build environment.
    let test_environment = [
        "CARGO_TARGET_DIR",
        "CARGO_BUILD_BUILD_DIR",
        "RUSTC_WORKSPACE_WRAPPER",
    ]
    .map(|name| (name, std::env::var(name).ok()))
    .into_iter()
    .collect::<BTreeMap<_, _>>();
    command.env(
        "HABEAS_COVERAGE_TEST_BUILD_ENV",
        serde_json::to_string(&test_environment)?,
    );
    // Capture dep-info and source text after compilation but before any test
    // process can mutate source or generated inputs.
    let mut build = Command::new(command.get_program());
    let mut build_args = preparation_args(
        &command
            .get_args()
            .map(|arg| arg.to_os_string())
            .collect::<Vec<_>>(),
    );
    let separator = build_args
        .iter()
        .position(|arg| arg == "--")
        .unwrap_or(build_args.len());
    if !has(&args, "--no-run") {
        build_args.insert(separator, "--no-run".into());
    }
    build.args(build_args).current_dir(&invocation);
    for (key, value) in command.get_envs() {
        match value {
            Some(value) => {
                build.env(key, value);
            }
            None => {
                build.env_remove(key);
            }
        }
    }
    let build_status = match interrupts.execute(&mut build) {
        Ok(status) => status,
        Err(error) => {
            run.outcome = "failed".into();
            run.diagnostics
                .push(format!("Cannot start instrumented compilation: {error}"));
            save(&dir.join("run.json"), &run)?;
            return Err(error);
        }
    };
    if !build_status.success() {
        run.outcome = if interrupts.happened() {
            "interrupted"
        } else {
            "failed"
        }
        .into();
        run.diagnostics.push("Instrumented compilation or nextest configuration validation failed before test startup.".into());
        save(&dir.join("run.json"), &run)?;
        return Ok(code(build_status));
    }
    let preparation: io::Result<()> = (|| {
        let progress = Progress::preparation();
        capture_inputs(&root, &target, &instrumented, &mut run)?;
        let mut features = BTreeMap::new();
        for path in walk(&instrumented.join("features"), &[])? {
            let (package, enabled): (String, std::collections::BTreeSet<String>) = load(&path)?;
            features.insert(package, enabled);
        }
        run.configuration_inputs
            .insert("enabled-features".into(), serde_json::to_string(&features)?);
        run.configuration = digest(&serde_json::to_vec(&run.configuration_inputs)?);
        progress.stage("Preparing coverage: capturing maps");
        snapshot_maps(&instrumented, &dir, &cov)
    })();
    if let Err(error) = preparation {
        run.outcome = if interrupts.happened() {
            "interrupted"
        } else {
            "failed"
        }
        .into();
        let message = format!("Coverage preparation failed before test startup: {error}");
        run.diagnostics.push(message.clone());
        save(&dir.join("run.json"), &run)?;
        return Err(io::Error::other(message));
    }
    save(&dir.join("run.json"), &run)?;
    if interrupts.happened() {
        return Ok(130);
    }
    let execution = interrupts.execute(&mut command);
    let status = match execution {
        Ok(status) => {
            run.outcome = if interrupts.happened() || status.code().is_none() {
                "interrupted"
            } else if status.success() {
                "success"
            } else {
                "failed"
            }
            .into();
            if interrupts.happened() {
                130
            } else {
                code(status)
            }
        }
        Err(error) => {
            run.diagnostics.push(error.to_string());
            run.outcome = "failed".into();
            1
        }
    };
    let collection = finish(&root, &dir, &cov, &profdata, &mut run);
    if let Err(error) = collection {
        run.diagnostics.push(error.to_string());
        if run.outcome == "success" {
            run.outcome = "failed".into();
        }
    }
    if fs::read_dir(dir.join("attempts"))?.next().is_none() {
        run.diagnostics.push(
            if has(&args, "--no-run") {
                "Compilation-only run (--no-run): no test attempt started."
            } else if status == 0 || status == 4 {
                // Nextest's NO_TESTS_RUN exit code.
                "Empty test selection: no test attempt started."
            } else {
                "Nextest stopped before test startup; no test attempt was recorded."
            }
            .into(),
        );
    }
    save(&dir.join("run.json"), &run)?;
    eprintln!("Coverage retained in {}", dir.display());
    for diagnostic in &run.diagnostics {
        eprintln!("coverage: {diagnostic}");
    }
    if status != 0 {
        Ok(status)
    } else if run.outcome == "success" {
        Ok(0)
    } else {
        Ok(1)
    }
}

Tests

Input 2: 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 3: outline src/execution_coverage/runner.rs mod[tests]/fn[compiler_wrapper_preserves_arguments_status_and_prior_wrapper_and_records_features]
    // {test}`requirements.test-coverage.run`
    // {test}`requirements.test-coverage.storage.configuration`
    #[cfg(unix)]
    #[test]
    fn compiler_wrapper_preserves_arguments_status_and_prior_wrapper_and_records_features() {
        use std::os::unix::fs::PermissionsExt;

        const TEST_NAME: &str = "execution_coverage::runner::tests::compiler_wrapper_preserves_arguments_status_and_prior_wrapper_and_records_features";
        if let Ok(arguments) = std::env::var("HABEAS_COMPILER_TEST_ARGUMENTS") {
            let arguments: Vec<String> = serde_json::from_str(&arguments).unwrap();
            let arguments = arguments
                .into_iter()
                .map(OsString::from)
                .collect::<Vec<_>>();
            assert_eq!(
                compile_process(&arguments).unwrap(),
                std::env::var("HABEAS_COMPILER_TEST_STATUS")
                    .unwrap()
                    .parse::<i32>()
                    .unwrap()
            );
            return;
        }
        assert_eq!(
            compile_process(&[]).unwrap_err().to_string(),
            "missing rustc invocation"
        );
        let root = tempfile::tempdir().unwrap();
        let compiler = root.path().join("fixture rustc");
        let wrapper = root.path().join("prior wrapper");
        fs::write(
            &compiler,
            "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$HABEAS_COMPILER_TEST_CAPTURE\"\nif [ \"${LLVM_PROFILE_FILE+x}\" = x ]; then exit 99; fi\nexit \"$HABEAS_COMPILER_TEST_STATUS\"\n",
        )
        .unwrap();
        fs::write(
            &wrapper,
            "#!/bin/sh\nprintf '%s\\n' \"$1\" > \"$HABEAS_COMPILER_TEST_WRAPPER_CAPTURE\"\nexec \"$@\"\n",
        )
        .unwrap();
        for path in [&compiler, &wrapper] {
            fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
        }
        for (name, wrapped, args, status, expected_features) in [
            ("query", false, vec!["--print", "sysroot"], 0, None),
            (
                "compile",
                false,
                vec![
                    "--crate-name",
                    "fixture",
                    "--cfg",
                    "feature=\"zeta\"",
                    "--cfg",
                    "feature=\"alpha\"",
                    "--cfg",
                    "feature=\"zeta\"",
                    "--cfg",
                    "test",
                    "--target",
                    "fixture-target",
                    "source with spaces.rs",
                ],
                0,
                Some(vec!["alpha", "zeta"]),
            ),
            (
                "wrapped",
                true,
                vec!["--crate-name", "fixture", "-C", "opt-level=2"],
                17,
                Some(vec![]),
            ),
        ] {
            let capture = root.path().join(format!("{name}.args"));
            let wrapper_capture = root.path().join(format!("{name}.wrapper"));
            let ledger = root.path().join(format!("{name}.ledger"));
            let mut arguments = vec![compiler.to_string_lossy().into_owned()];
            arguments.extend(args.iter().map(|arg| (*arg).to_owned()));
            let mut child = Command::new(std::env::current_exe().unwrap());
            child
                .args(["--exact", TEST_NAME])
                .env(
                    "HABEAS_COMPILER_TEST_ARGUMENTS",
                    serde_json::to_string(&arguments).unwrap(),
                )
                .env("HABEAS_COMPILER_TEST_STATUS", status.to_string())
                .env("HABEAS_COMPILER_TEST_CAPTURE", &capture)
                .env("HABEAS_COMPILER_TEST_WRAPPER_CAPTURE", &wrapper_capture)
                .env("HABEAS_COVERAGE_FEATURE_LEDGER", &ledger)
                .env("CARGO_MANIFEST_DIR", root.path())
                .env_remove("HABEAS_PREVIOUS_WORKSPACE_WRAPPER");
            if wrapped {
                child.env("HABEAS_PREVIOUS_WORKSPACE_WRAPPER", &wrapper);
            }
            let result = child.output().unwrap();
            assert!(
                result.status.success(),
                "{name}: {}\n{}",
                String::from_utf8_lossy(&result.stdout),
                String::from_utf8_lossy(&result.stderr)
            );
            assert!(String::from_utf8_lossy(&result.stdout).contains("1 passed"));
            let mut expected = args.iter().map(|arg| (*arg).to_owned()).collect::<Vec<_>>();
            if let Some(features) = expected_features {
                expected.extend(["-C".into(), "instrument-coverage".into()]);
                let records = fs::read_dir(&ledger)
                    .unwrap()
                    .collect::<Result<Vec<_>, _>>()
                    .unwrap();
                assert_eq!(
                    records.len(),
                    1,
                    "one feature record per package and target"
                );
                let record: (String, Vec<String>) = load(&records[0].path()).unwrap();
                let target = if name == "compile" {
                    "fixture-target"
                } else {
                    "host"
                };
                assert_eq!(record.0, format!("{} [{target}]", root.path().display()));
                assert_eq!(
                    record.1, features,
                    "features are unique, sorted, and omit non-feature cfgs"
                );
            } else {
                assert!(
                    !ledger.exists(),
                    "compiler queries create no feature records"
                );
            }
            assert_eq!(
                fs::read_to_string(capture)
                    .unwrap()
                    .lines()
                    .collect::<Vec<_>>(),
                expected
            );
            if wrapped {
                assert_eq!(
                    fs::read_to_string(wrapper_capture).unwrap().trim(),
                    compiler.to_str().unwrap()
                );
            } else {
                assert!(!wrapper_capture.exists());
            }
        }
        assert_eq!(
            compile_process(&[root.path().join("missing-rustc").into_os_string()])
                .unwrap_err()
                .kind(),
            io::ErrorKind::NotFound
        );
    }
Input 4: outline src/execution_coverage/runner.rs mod[tests]/fn[compiler_inputs_determine_compatibility_and_scheduling_does_not]
    // {test}`requirements.test-coverage.storage.configuration`
    #[test]
    fn compiler_inputs_determine_compatibility_and_scheduling_does_not() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();
        let rustc = "rustc 1.97.0\nhost: test-host\nLLVM version: 22.1.6\n";
        let baseline =
            build_configuration(root, &["--target".into(), "test-host".into()], rustc).unwrap();
        let key = |inputs: &BTreeMap<String, String>| digest(&serde_json::to_vec(inputs).unwrap());
        assert_eq!(baseline["rustc"], rustc);
        assert_eq!(baseline["target"], "test-host");
        assert_eq!(baseline["cargo-profile"], "test");
        assert!(baseline["instrumentation"].contains("-C instrument-coverage"));
        for (args, field, value) in [
            (
                vec!["--target", "wasm32-unknown-unknown"],
                "target",
                "wasm32-unknown-unknown",
            ),
            (
                vec!["--target", "test-host", "--release"],
                "cargo-profile",
                "release",
            ),
            (
                vec!["--target", "test-host", "-r"],
                "cargo-profile",
                "release",
            ),
            (
                vec!["--target", "test-host", "--cargo-profile", "custom"],
                "cargo-profile",
                "custom",
            ),
            (
                vec!["--target", "test-host", "--all-features"],
                "all-features",
                "true",
            ),
            (
                vec!["--target", "test-host", "--no-default-features"],
                "no-default-features",
                "true",
            ),
        ] {
            let args = args.into_iter().map(String::from).collect::<Vec<_>>();
            let inputs = build_configuration(root, &args, rustc).unwrap();
            assert_eq!(inputs[field], value);
            assert_ne!(key(&inputs), key(&baseline), "{args:?}");
        }
        let different_compiler = build_configuration(
            root,
            &["--target".into(), "test-host".into()],
            &rustc.replace("1.97.0", "1.98.0"),
        )
        .unwrap();
        assert_ne!(key(&different_compiler), key(&baseline));
        let scheduled = build_configuration(
            root,
            &[
                "--target".into(),
                "test-host".into(),
                "--profile".into(),
                "focused".into(),
            ],
            rustc,
        )
        .unwrap();
        assert_eq!(key(&scheduled), key(&baseline));
        fs::create_dir(root.join(".cargo")).unwrap();
        let config = root.join(".cargo/config.toml");
        fs::write(
            &config,
            "[build]\nrustflags = ['-C', 'opt-level=1']\n[env]\nBUILD_INPUT = 'one'\n",
        )
        .unwrap();
        let configured =
            build_configuration(root, &["--target".into(), "test-host".into()], rustc).unwrap();
        assert!(configured[config.to_str().unwrap()].contains("opt-level=1"));
        assert_ne!(key(&configured), key(&baseline));
        fs::write(
            &config,
            "[build]\nrustflags = ['-C', 'opt-level=2']\n[env]\nBUILD_INPUT = 'two'\n",
        )
        .unwrap();
        let changed =
            build_configuration(root, &["--target".into(), "test-host".into()], rustc).unwrap();
        assert_ne!(key(&changed), key(&configured));

        // A child has its own environment, without changing any other test's process.
        if std::env::var_os("HABEAS_CONFIGURATION_TEST_CHILD").is_some() {
            assert_eq!(baseline["RUSTFLAGS"], "-Copt-level=3");
            assert_eq!(baseline["CARGO_PROFILE_TEST_DEBUG"], "false");
            assert_eq!(baseline["CARGO_TARGET_TEST_HOST_LINKER"], "fixture-linker");
            assert_ne!(
                key(&baseline),
                std::env::var("HABEAS_CONFIGURATION_BASELINE").unwrap()
            );
            return;
        }
        let child = Command::new(std::env::current_exe().unwrap())
            .args(["--exact", "execution_coverage::runner::tests::compiler_inputs_determine_compatibility_and_scheduling_does_not"])
            .env("HABEAS_CONFIGURATION_TEST_CHILD", "1")
            .env("HABEAS_CONFIGURATION_BASELINE", key(&baseline))
            .env("RUSTFLAGS", "-Copt-level=3")
            .env("CARGO_PROFILE_TEST_DEBUG", "false")
            .env("CARGO_TARGET_TEST_HOST_LINKER", "fixture-linker")
            .output().unwrap();
        assert!(
            child.status.success(),
            "{}",
            String::from_utf8_lossy(&child.stderr)
        );
        assert!(String::from_utf8_lossy(&child.stdout).contains("1 passed"));
    }
Input 5: outline tests/execution_coverage.rs fn[real_parallel_processes_retries_child_profiles_and_filtered_reruns]
// {test}`requirements.test-coverage.run`
// {test}`requirements.test-coverage.processes`
// {test}`requirements.test-coverage.processes.reports`
// {test}`requirements.test-coverage.storage`
// {test}`requirements.test-coverage.storage.provenance`
// {test}`requirements.test-coverage.storage.configuration`
// {test}`requirements.test-coverage.storage.outcomes`
// {test}`requirements.test-coverage.failures`
#[test]
fn real_parallel_processes_retries_child_profiles_and_filtered_reruns() {
    let temp = fixture();
    let root = temp.path();
    assert_success(&coverage(
        root,
        &["--workspace", "--retries", "1", "-j", "2", "--no-fail-fast"],
    ));
    let saved = runs(root);
    assert_eq!(saved.len(), 1);
    let first = &saved[0].0;
    assert_eq!(
        saved[0].1["id"],
        first.file_name().unwrap().to_str().unwrap()
    );
    assert!(saved[0].1["started"].as_u64().unwrap() > 0);
    assert_eq!(saved[0].1["command"][0], "cargo nextest run");
    assert!(
        saved[0].1["selection"]
            .as_array()
            .unwrap()
            .iter()
            .any(|arg| arg == "--workspace")
    );
    assert!(saved[0].1["revision"].is_null());
    assert!(saved[0].1["dirty"].is_null());
    assert!(
        saved[0].1["inputs"]
            .get(root.join("src/lib.rs").to_str().unwrap())
            .is_some()
    );
    let records = attempts(first);
    assert_eq!(records.len(), 6); // five tests, one retried
    let retry = records
        .iter()
        .filter(|record| record["test"] == "retries")
        .collect::<Vec<_>>();
    assert_eq!(retry.len(), 2);
    assert!(
        retry
            .iter()
            .any(|record| record["outcome"] == "failed" && record["attempt"] == "1")
    );
    assert!(
        retry
            .iter()
            .any(|record| record["outcome"] == "success" && record["attempt"] == "2")
    );
    let child = records
        .iter()
        .find(|record| record["test"] == "child_process")
        .unwrap();
    assert_eq!(child["processes"].as_array().unwrap().len(), 2);
    assert!(
        child["processes"]
            .as_array()
            .unwrap()
            .iter()
            .all(|process| process["diagnostic"].is_null()
                && !process["lines"].as_object().unwrap().is_empty())
    );
    assert!(
        records
            .iter()
            .all(|record| !record["processes"].as_array().unwrap().is_empty())
    );
    assert_eq!(
        records
            .iter()
            .filter(|record| record["test"].as_str().unwrap().ends_with("same_name"))
            .count(),
        2
    );
    let same_named = records
        .iter()
        .filter(|record| record["test"].as_str().unwrap().ends_with("same_name"))
        .collect::<Vec<_>>();
    let binaries = same_named
        .iter()
        .map(|record| record["binary"].as_str().unwrap())
        .collect::<std::collections::BTreeSet<_>>();
    assert_eq!(
        binaries,
        std::collections::BTreeSet::from(["coverage-fixture", "coverage-fixture::processes"])
    );
    let identities = records
        .iter()
        .map(|record| record["id"].as_str().unwrap())
        .collect::<std::collections::BTreeSet<_>>();
    assert_eq!(identities.len(), records.len());
    for record in &records {
        for process in record["processes"].as_array().unwrap() {
            for profile in process["profiles"].as_array().unwrap() {
                assert!(
                    first
                        .join("attempts")
                        .join(record["id"].as_str().unwrap())
                        .join(profile.as_str().unwrap())
                        .is_file()
                );
            }
        }
    }
    let configuration = &saved[0].1["configuration_inputs"];
    assert!(
        configuration["rustc"]
            .as_str()
            .unwrap()
            .contains("LLVM version:")
    );
    assert!(!configuration["target"].as_str().unwrap().is_empty());
    assert_eq!(configuration["cargo-profile"], "test");
    assert!(
        configuration["instrumentation"]
            .as_str()
            .unwrap()
            .contains("-C instrument-coverage")
    );
    assert!(first.join("maps.json").is_file());
    assert!(
        saved[0].1["sources"]["src/lib.rs"]
            .as_str()
            .unwrap()
            .contains("pub fn value")
    );

    assert_success(&coverage(root, &["-E", "test(second)"]));
    let saved = runs(root);
    assert_eq!(saved.len(), 2);
    assert_eq!(attempts(&saved[1].0).len(), 1);
    assert_eq!(saved[0].1["configuration"], saved[1].1["configuration"]);
    assert_eq!(
        saved[1].1["selection"],
        serde_json::json!(["-E", "test(second)"])
    );
    // A scheduling profile doesn't split build compatibility.
    let config = root.join(".config/nextest.toml");
    let mut source = fs::read_to_string(&config).unwrap();
    source.push_str("\n[profile.focused]\ntest-threads = 1\n");
    fs::write(config, source).unwrap();
    assert_success(&coverage(
        root,
        &["--profile", "focused", "-E", "test(second)"],
    ));
    let saved = runs(root);
    assert_eq!(saved[0].1["configuration"], saved[2].1["configuration"]);
    assert_eq!(attempts(&saved[0].0).len(), 6); // historical profiles were retained
    // Collection must preserve failure, including a retry's attempt outcome.
    let failed = coverage(root, &["-E", "test(retries)", "--retries", "0"]);
    assert!(!failed.status.success());
    let saved = runs(root);
    let newest = saved.last().unwrap();
    assert_eq!(newest.1["outcome"], "failed");
    assert_eq!(attempts(&newest.0)[0]["outcome"], "failed");
    // Empty selection has nextest's own exit result and a visible run diagnostic.
    let empty = coverage(
        root,
        &["-E", "test(definitely_missing)", "--no-tests", "pass"],
    );
    assert_success(&empty);
    let saved = runs(root);
    assert!(attempts(&saved.last().unwrap().0).is_empty());
    assert!(
        saved.last().unwrap().1["diagnostics"][0]
            .as_str()
            .unwrap()
            .contains("Empty test selection")
    );
    let empty_failure = coverage(root, &["-E", "test(definitely_missing)"]);
    assert_eq!(
        empty_failure.status.code(),
        Some(4),
        "{}",
        String::from_utf8_lossy(&empty_failure.stderr)
    );
    let saved = runs(root);
    let newest = saved.last().unwrap();
    assert_eq!(newest.1["outcome"], "failed");
    assert!(attempts(&newest.0).is_empty());
    assert!(
        newest.1["diagnostics"][0]
            .as_str()
            .unwrap()
            .contains("Empty test selection")
    );
    assert_success(&coverage(
        root,
        &["--features", "alpha", "-Fbeta", "-E", "test(second)"],
    ));
    let saved = runs(root);
    let newest = saved.last().unwrap();
    assert_ne!(newest.1["configuration"], saved[0].1["configuration"]);
    let enabled: Value = serde_json::from_str(
        newest.1["configuration_inputs"]["enabled-features"]
            .as_str()
            .unwrap(),
    )
    .unwrap();
    assert!(enabled.as_object().unwrap().values().any(|features| {
        features
            .as_array()
            .unwrap()
            .contains(&Value::String("alpha".into()))
            && features
                .as_array()
                .unwrap()
                .contains(&Value::String("beta".into()))
    }));
    assert_success(&coverage(
        root,
        &[
            "--config",
            "build.build-dir='custom-build'",
            "-E",
            "test(second)",
        ],
    ));
    let saved = runs(root);
    assert_eq!(attempts(&saved.last().unwrap().0).len(), 1);
    assert!(!root.join("custom-build").exists());
    assert_success(&coverage(root, &["--no-run", "-E", "test(second)"]));
    let saved = runs(root);
    let newest = saved.last().unwrap();
    assert_eq!(newest.1["outcome"], "success");
    assert!(attempts(&newest.0).is_empty());
    assert!(
        newest.1["diagnostics"][0]
            .as_str()
            .unwrap()
            .contains("Compilation-only")
    );
    assert!(
        !newest.1["diagnostics"][0]
            .as_str()
            .unwrap()
            .contains("Empty")
    );
    // Compilation failures also retain run identity and all earlier process data.
    fs::write(
        root.join("src/lib.rs"),
        "compile_error!(\"deliberate build failure\");\n",
    )
    .unwrap();
    let failed_build = coverage(root, &["-E", "test(second)"]);
    assert!(!failed_build.status.success());
    let saved = runs(root);
    let newest = saved.last().unwrap();
    assert_eq!(newest.1["outcome"], "failed");
    assert!(attempts(&newest.0).is_empty());
    assert!(
        newest.1["diagnostics"][0]
            .as_str()
            .unwrap()
            .contains("Instrumented compilation")
    );
    assert_eq!(attempts(first).len(), 6);
    for record in &records {
        for process in record["processes"].as_array().unwrap() {
            for profile in process["profiles"].as_array().unwrap() {
                assert!(
                    first
                        .join("attempts")
                        .join(record["id"].as_str().unwrap())
                        .join(profile.as_str().unwrap())
                        .is_file()
                );
            }
        }
    }
}

Other sources

Input 1: requirements selection requirements.test-coverage.storage.configuration
:::{req} storage.configuration
Each coverage record MUST identify the recorded toolchain, compilation target,
Cargo build profile, enabled features, and instrumentation-affecting compiler
settings. These settings MUST determine build-configuration compatibility for
the combined view. A nextest scheduling profile alone MUST NOT make otherwise
compatible build configurations incompatible.
:::
Input 6: 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,
    }
}
Input 7: 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(())
}