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.processes

Requirements index · View definition

evidence Valid

Requirement

Each coverage run MUST retain LLVM coverage profiles independently for each test process, identifying its nextest binary, test name, and attempt. Concurrent tests, tests with the same name in different binaries, retries, and separate runs MUST NOT overwrite or combine one another’s stored profiles. Profiles from instrumented child processes MUST remain separate and associated with the test attempt that spawned them.

Rationale

The tests adequately cover requirements.test-coverage.processes. The main evidence is tests/execution_coverage.rs#fn[real_parallel_processes_retries_child_profiles_and_filtered_reruns]. It builds a real fixture (fn[fixture]) and runs the full habeas coverage flow. I also read collect_process and Attempt, but only to see how attempt identity is formed. I took the expected behaviour from the requirement text.

Obligations and the scenarios that cover them:

  • Per-attempt retention that identifies binary, test and attempt. The run is --workspace --retries 1 -j 2 --no-fail-fast. It asserts that exactly 6 attempt records exist (five tests, one retried). Each record’s binary, test and attempt fields are read and checked. Every record has a non-empty processes list. Every recorded profile path is asserted to be a file under attempts/<attempt id>/. The set of attempt ids has the same size as the record list, so no two attempts share a directory.
  • Concurrent tests do not overwrite or combine. The run uses -j 2 over five tests. The 6 distinct attempt ids and the per-attempt profile files would fail if concurrent tests shared a store. Nothing proves the tests overlapped in time. The isolation is checked by distinct identities and retained profiles, and that is the property the requirement states.
  • Same test name in different binaries. The same_name test exists in both the lib test binary and tests/processes.rs. The test asserts there are exactly 2 records ending in same_name. It asserts their binaries are exactly {coverage-fixture, coverage-fixture::processes}. It asserts they have distinct ids.
  • Retries. The retries test yields two records. One is attempt "1" with outcome failed. The other is attempt "2" with outcome success. Both are kept separately.
  • Separate runs. Several later runs follow: a filtered rerun, a different profile, a failed run, an empty selection, a features change, --no-run and a compile failure. Each later run adds its own run directory, and runs(root).len() becomes 2 after the first rerun. The first run still has 6 attempts (attempts(&saved[0].0).len() == 6), and attempts(first).len() == 6 still holds at the end. The final loop re-asserts that every profile file of the first run’s records still exists, so later runs neither overwrite nor merge it.
  • Child process profiles stay separate and tied to the spawning attempt. child_process spawns the test executable again with COVERAGE_CHILD. Its single attempt record has exactly 2 processes. Each has a null diagnostic and non-empty lines. Both sit in that attempt’s directory. The profile pattern in collect_process is %p-%m.profraw, so each pid gets its own file. The test confirms two separately recorded processes under one attempt.

The unit test runner.rs#mod[tests]/fn[parallel_conversion_is_bounded_and_retains_every_result_in_order] adds a check on the post-run conversion step. It uses real concurrency with a rendezvous and checks that every result is kept in order, including a failed one. That supports the “retain every process’s profile independently” side of the requirement.

I found no plausible requirement-violating behaviour that these assertions would accept. A fixed or shared profile path, merged retry attempts, a same-name collision across binaries, a child profile lost or merged into the parent, and a later run clobbering an earlier one would each fail an assertion above. There are no acknowledgments, and none are needed.

Inputs

Implementation

Input 4: outline src/execution_coverage/runner.rs fn[collect_process]
// {impl}`requirements.test-coverage.processes`
// {impl}`requirements.test-coverage.storage.outcomes`
// {impl}`requirements.test-coverage.failures`
pub fn collect_process(args: &[OsString]) -> io::Result<i32> {
    let executable = args
        .first()
        .ok_or_else(|| io::Error::other("coverage-process requires a test command"))?;
    let Some(run) = std::env::var_os("HABEAS_COVERAGE_RUN") else {
        return Ok(code(Command::new(executable).args(&args[1..]).status()?));
    };
    let dir = PathBuf::from(run)
        .join("attempts")
        .join(uuid::Uuid::new_v4().to_string());
    fs::create_dir_all(&dir)?;
    let mut attempt = Attempt {
        id: dir.file_name().unwrap().to_string_lossy().into_owned(),
        binary: std::env::var("NEXTEST_BINARY_ID").map_err(io::Error::other)?,
        test: std::env::var("NEXTEST_TEST_NAME").map_err(io::Error::other)?,
        attempt: std::env::var("NEXTEST_ATTEMPT").map_err(io::Error::other)?,
        started: now(),
        pid: 0,
        command: args
            .iter()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect(),
        outcome: "interrupted".into(),
        processes: Vec::new(),
        diagnostics: Vec::new(),
    };
    save(&dir.join("attempt.json"), &attempt)?;
    let mut command = Command::new(executable);
    command
        .args(&args[1..])
        .env("LLVM_PROFILE_FILE", dir.join("%p-%m.profraw"));
    if let Ok(environment) = std::env::var("HABEAS_COVERAGE_TEST_BUILD_ENV") {
        let environment: BTreeMap<String, Option<String>> = serde_json::from_str(&environment)?;
        for (name, value) in environment {
            match value {
                Some(value) => {
                    command.env(name, value);
                }
                None => {
                    command.env_remove(name);
                }
            }
        }
    }
    for name in [
        "HABEAS_COVERAGE_RUN",
        "HABEAS_COVERAGE_FEATURE_LEDGER",
        "HABEAS_PREVIOUS_WORKSPACE_WRAPPER",
        "HABEAS_COVERAGE_TEST_BUILD_ENV",
    ] {
        command.env_remove(name);
    }
    let mut child = match command.spawn() {
        Ok(child) => child,
        Err(error) => {
            attempt.outcome = "failed".into();
            attempt
                .diagnostics
                .push(format!("Cannot start test process: {error}"));
            save(&dir.join("attempt.json"), &attempt)?;
            return Err(error);
        }
    };
    attempt.pid = child.id();
    save(&dir.join("attempt.json"), &attempt)?;
    let status = match child.wait() {
        Ok(status) => status,
        Err(error) => {
            attempt.outcome = "failed".into();
            attempt
                .diagnostics
                .push(format!("Cannot wait for test process: {error}"));
            save(&dir.join("attempt.json"), &attempt)?;
            return Err(error);
        }
    };
    attempt.outcome = if status.success() {
        "success"
    } else if status.code().is_none() {
        "interrupted"
    } else {
        "failed"
    }
    .into();
    save(&dir.join("attempt.json"), &attempt)?;
    Ok(code(status))
}
Input 5: outline src/execution_coverage.rs struct[Attempt]
// {impl}`requirements.test-coverage.processes`
// {impl}`requirements.test-coverage.storage.outcomes`
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Attempt {
    id: String,
    binary: String,
    test: String,
    attempt: String,
    started: u128,
    pid: u32,
    command: Vec<String>,
    outcome: String,
    processes: Vec<Process>,
    diagnostics: Vec<String>,
}

Tests

Input 2: outline src/execution_coverage/runner.rs mod[tests]/fn[parallel_conversion_is_bounded_and_retains_every_result_in_order]
    // {test}`requirements.test-coverage.processes`
    // {test}`requirements.test-coverage.processes.reports`
    // {test}`requirements.test-coverage.failures`
    // {test}`requirements.test-coverage.processes.progress`
    #[test]
    fn parallel_conversion_is_bounded_and_retains_every_result_in_order() {
        use std::sync::{Condvar, Mutex};
        use std::time::Duration;

        for workers in [2, 8] {
            let total = workers * 2;
            let active = AtomicUsize::new(0);
            let peak = AtomicUsize::new(0);
            let visits: Vec<_> = (0..total).map(|_| AtomicUsize::new(0)).collect();
            let finished: Vec<_> = (0..total).map(|_| AtomicBool::new(false)).collect();
            let rendezvous = (Mutex::new(false), Condvar::new());
            let mut completed = 0;
            let results = parallel_collect(
                &(0..total).collect::<Vec<_>>(),
                workers,
                |&index| {
                    visits[index].fetch_add(1, Ordering::SeqCst);
                    let concurrent = active.fetch_add(1, Ordering::SeqCst) + 1;
                    peak.fetch_max(concurrent, Ordering::SeqCst);
                    if index < workers {
                        let mut met = rendezvous.0.lock().unwrap();
                        if concurrent == workers {
                            *met = true;
                            rendezvous.1.notify_all();
                        }
                        let (met, timeout) = rendezvous
                            .1
                            .wait_timeout_while(met, Duration::from_secs(5), |met| !*met)
                            .unwrap();
                        assert!(
                            *met && !timeout.timed_out(),
                            "conversion was not concurrent"
                        );
                    }
                    active.fetch_sub(1, Ordering::SeqCst);
                    finished[index].store(true, Ordering::SeqCst);
                    if index == 3 {
                        Err("unreadable profile")
                    } else {
                        Ok(index)
                    }
                },
                |index| {
                    assert!(
                        finished[index].load(Ordering::SeqCst),
                        "progress advanced before conversion finished"
                    );
                    completed += 1;
                },
            );
            assert_eq!(peak.load(Ordering::SeqCst), workers);
            assert!(visits.iter().all(|count| count.load(Ordering::SeqCst) == 1));
            assert_eq!(completed, total, "failed work also completes a conversion");
            assert_eq!(
                results,
                (0..total)
                    .map(|index| if index == 3 {
                        Err("unreadable profile")
                    } else {
                        Ok(index)
                    })
                    .collect::<Vec<_>>()
            );
        }
    }
Input 3: 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.processes
:::{req} processes
Each coverage run MUST retain LLVM coverage profiles independently for each
test process, identifying its nextest binary, test name, and attempt. Concurrent
tests, tests with the same name in different binaries, retries, and separate
runs MUST NOT overwrite or combine one another's stored profiles. Profiles from
instrumented child processes MUST remain separate and associated with the test
attempt that spawned them.
:::
Input 6: outline tests/execution_coverage.rs fn[fixture]
// {cite}`habeas:util`
fn fixture() -> TempDir {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path();
    for directory in ["src", "tests", "md"] {
        fs::create_dir_all(root.join(directory)).unwrap();
    }
    fs::write(
        root.join("Cargo.toml"),
        "[package]\nname = 'coverage-fixture'\nversion = '0.1.0'\nedition = '2024'\n[features]\nalpha = []\nbeta = []\n",
    )
    .unwrap();
    fs::write(root.join("book.toml"), "[book]\nsrc = 'md'\n").unwrap();
    fs::write(root.join("md/SUMMARY.md"), "# Summary\n").unwrap();
    fs::write(
        root.join("src/lib.rs"),
        concat!(
            "pub fn value(flag: bool) -> u32 {\n",
            "    if flag {\n        10\n    } else {\n        20\n    }\n}\n",
            "#[cfg(test)] #[test] fn same_name() { assert_eq!(value(true), 10); }\n",
            "#[cfg(test)] #[test] fn second() { assert_eq!(value(false), 20); }\n",
        ),
    )
    .unwrap();
    fs::write(root.join("tests/processes.rs"), concat!(
        "use std::process::Command;\n",
        "#[test] fn same_name() { assert_eq!(coverage_fixture::value(false), 20); }\n",
        "#[test] fn child_process() {\n",
        "    if std::env::var_os(\"COVERAGE_CHILD\").is_some() {\n",
        "        assert_eq!(coverage_fixture::value(true), 10);\n",
        "    } else {\n",
        "        assert!(Command::new(std::env::current_exe().unwrap()).args([\"--exact\", \"child_process\"]).env(\"COVERAGE_CHILD\", \"1\").status().unwrap().success());\n",
        "    }\n}\n",
        "#[test] fn retries() { assert_eq!(std::env::var(\"NEXTEST_ATTEMPT\").unwrap(), \"2\"); }\n",
    )).unwrap();
    common::coverage_setup(root);
    temp
}
Input 7: outline tests/execution_coverage.rs fn[coverage_progress_on_a_pty_preserves_reports_and_plain_output_policy]
// {test}`requirements.test-coverage.processes.progress`
// {test}`requirements.test-coverage.processes.progress.preparation`
// {test}`requirements.test-coverage.processes.progress.terminal`
#[cfg(target_os = "linux")]
#[test]
fn coverage_progress_on_a_pty_preserves_reports_and_plain_output_policy() {
    use std::io::Read;
    use std::os::fd::FromRawFd;

    #[link(name = "util")]
    unsafe extern "C" {
        fn openpty(
            master: *mut std::ffi::c_int,
            slave: *mut std::ffi::c_int,
            name: *mut std::ffi::c_char,
            termios: *const std::ffi::c_void,
            winsize: *const std::ffi::c_void,
        ) -> std::ffi::c_int;
    }

    let temp = fixture();
    let root = temp.path();
    let source = fs::read_to_string(root.join("src/lib.rs")).unwrap();
    fs::write(root.join("src/lib.rs"), format!("{source}\n#[test] fn deliberate_failure() {{ panic!(\"fixture failure\"); }}\nunsafe extern \"C\" {{ fn _exit(status: i32) -> !; }}\n#[test] fn missing_profile() {{ unsafe {{ _exit(0) }} }}\n")).unwrap();
    let run_on_pty = |term: &str, filter: &str| {
        let mut master = -1;
        let mut slave = -1;
        // The returned descriptors are owned by this test and transferred
        // exactly once into File. Default terminal settings are sufficient.
        assert_eq!(
            unsafe {
                openpty(
                    &mut master,
                    &mut slave,
                    std::ptr::null_mut(),
                    std::ptr::null(),
                    std::ptr::null(),
                )
            },
            0
        );
        let mut master = unsafe { fs::File::from_raw_fd(master) };
        let slave = unsafe { fs::File::from_raw_fd(slave) };
        let reader = std::thread::spawn(move || {
            let mut output = Vec::new();
            if let Err(error) = master.read_to_end(&mut output) {
                // Linux returns EIO when the last slave descriptor closes.
                assert_eq!(error.raw_os_error(), Some(5));
            }
            output
        });
        let child = Command::new(env!("CARGO_BIN_EXE_habeas"))
            .args(["coverage", "--", "-E", filter, "--color=never"])
            .current_dir(root)
            .env("CARGO_NET_OFFLINE", "true")
            .env("TERM", term)
            .env("NO_COLOR", "1")
            .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")
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::piped())
            .stderr(slave)
            .spawn()
            .unwrap();
        let mut output = child.wait_with_output().unwrap();
        output.stderr = reader.join().unwrap();
        output
    };
    let assert_conversion_cleared = |text: &str| {
        let count = text.rfind("1/1 attempts").unwrap();
        let location = text.find("Coverage retained in ").unwrap();
        assert!(text[count..location].contains("\x1b[2K"), "{text}");
        assert!(
            !text[location..].contains("\x1b["),
            "final reports must remain plain and readable: {text}"
        );
    };
    for term in ["xterm", "dumb"] {
        let output = run_on_pty(term, "test(second)");
        assert_success(&output);
        let text = String::from_utf8_lossy(&output.stderr);
        if term == "xterm" {
            assert!(
                text.contains("Preparing coverage: recording inputs"),
                "{text}"
            );
            assert!(
                text.contains("Preparing coverage: capturing maps"),
                "{text}"
            );
            assert!(text.contains("Converting coverage"), "{text}");
            assert!(text.contains("1/1 attempts"), "{text}");
            assert!(text.contains("[00:"), "{text}");
            assert!(
                text.contains("\x1b["),
                "PTY progress should update in place"
            );
            assert!(!text.contains("\x1b[3"), "NO_COLOR must suppress color");
            assert_conversion_cleared(&text);
        } else {
            assert!(!text.contains("Converting coverage"), "{text}");
            assert!(!text.contains("\x1b["), "{text}");
        }
        assert!(text.contains("Coverage retained in "), "{text}");
        let saved = runs(root);
        let records = attempts(&saved.last().unwrap().0);
        assert_eq!(records.len(), 1);
        assert_eq!(records[0]["outcome"], "success");
        assert_eq!(records[0]["processes"].as_array().unwrap().len(), 1);
        assert!(
            !records[0]["processes"][0]["lines"]
                .as_object()
                .unwrap()
                .is_empty()
        );
    }
    let output = coverage(root, &["-E", "test(second)", "--color=never"]);
    assert_success(&output);
    let text = String::from_utf8_lossy(&output.stderr);
    assert!(!text.contains("Converting coverage"), "{text}");
    assert!(!text.contains("\x1b["), "{text}");
    let saved = runs(root);
    let first = attempts(&saved[0].0);
    for (run, _) in &saved[1..] {
        let records = attempts(run);
        assert_eq!(
            records[0]["processes"][0]["lines"],
            first[0]["processes"][0]["lines"]
        );
        assert_eq!(
            records[0]["processes"][0]["functions"],
            first[0]["processes"][0]["functions"]
        );
    }
    for (filter, succeeds, outcome, processes) in [
        ("test(child_process)", true, "success", 2),
        ("test(deliberate_failure)", false, "failed", 1),
        ("test(missing_profile)", false, "success", 0),
    ] {
        let output = run_on_pty("xterm", filter);
        assert_eq!(
            output.status.success(),
            succeeds,
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        let text = String::from_utf8_lossy(&output.stderr);
        assert_conversion_cleared(&text);
        if processes == 0 {
            assert!(text.contains("coverage: "), "{text}");
            assert!(
                text.contains("partial profiles and reports have been retained"),
                "{text}"
            );
        }
        let saved = runs(root);
        let records = attempts(&saved.last().unwrap().0);
        assert_eq!(records.len(), 1);
        assert_eq!(records[0]["outcome"], outcome);
        assert_eq!(records[0]["processes"].as_array().unwrap().len(), processes);
        for process in records[0]["processes"].as_array().unwrap() {
            assert!(!process["lines"].as_object().unwrap().is_empty());
            assert!(process["functions"].is_array());
        }
    }
    // An error during preparation must also clear the stage before the CLI
    // prints its diagnostic, without manufacturing test attempts.
    use std::os::unix::fs::PermissionsExt;
    fs::write(
        root.join("build.rs"),
        "fn main() { println!(\"cargo::rerun-if-changed=input.data\"); }\n",
    )
    .unwrap();
    let input = root.join("input.data");
    fs::write(&input, "unreadable input").unwrap();
    fs::set_permissions(&input, fs::Permissions::from_mode(0o000)).unwrap();
    let output = run_on_pty("xterm", "test(second)");
    fs::set_permissions(input, fs::Permissions::from_mode(0o600)).unwrap();
    assert!(!output.status.success());
    let text = String::from_utf8_lossy(&output.stderr);
    let stage = text.rfind("Preparing coverage: recording inputs").unwrap();
    let diagnostic = text.find("Coverage preparation failed").unwrap();
    assert!(text[stage..diagnostic].contains("\x1b[2K"), "{text}");
    assert!(!text[diagnostic..].contains("\x1b["), "{text}");
    let saved = runs(root);
    assert_eq!(saved.last().unwrap().1["outcome"], "failed");
    assert!(attempts(&saved.last().unwrap().0).is_empty());
}