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

Requirements index · View definition

evidence Valid

Requirement

During report conversion, on a terminal enabled under cite requirements.test-coverage.processes.progress.terminal, Habeas MUST display updating progress with elapsed time and completed and total test-attempt counts. The total MUST count the recorded attempts selected for conversion. An attempt MUST advance the completed count only after its conversion has finished or reported a collection failure, including processing its associated child-process profiles. These counts MUST measure conversion work regardless of the attempt’s test outcome.

Rationale

The reviewed tests cover each obligation of requirements.test-coverage.processes.progress.

  • Updating display with elapsed time and completed/total counts.
    • src/execution_coverage/progress.rs#mod[tests]/fn[stage_and_conversion_counts_are_visible_then_cleared] builds a conversion Progress with totals 0 and 2. It calls completed() and asserts that the bar position and the drawn text show {n}/{total} attempts and a [00:00: elapsed field. It also asserts the display is monochrome and clears on drop.
    • tests/execution_coverage.rs#fn[coverage_progress_on_a_pty_preserves_reports_and_plain_output_policy] runs the real binary on a PTY with TERM=xterm. It asserts Converting coverage, 1/1 attempts, [00: and in-place escape sequences. NO_COLOR is set, and the test asserts no color codes appear.
  • Total counts the recorded attempts selected for conversion.
    • In the implementation, fn[finish] passes attempts.len() to Progress::conversion. This is a pass-through with no conditional.
    • The unit test checks displayed totals of 0 and 2. The PTY test checks 1/1 against exactly one recorded attempt, and it asserts the saved run has one record.
  • Advance only after conversion has finished, including child-process profiles.
    • src/execution_coverage/runner.rs#mod[tests]/fn[parallel_conversion_is_bounded_and_retains_every_result_in_order] asserts in the completion callback that the work for that item has already finished. It runs with 2 and 8 workers over twice as many items. It also asserts every item is visited once and results keep their order.
    • The PTY test(child_process) case has two profiles per attempt. It asserts a 1/1 attempts display that is cleared, and it asserts both child-process profiles are retained.
  • Counts measure work regardless of test outcome, and collection failures also complete.
    • The runner test makes one item return Err. It asserts completed == total, so failed work still advances the count.
    • The PTY test runs a failing test (deliberate_failure, outcome failed) and a test whose profile is missing (missing_profile, which gives a collection diagnostic). It checks the cleared 1/1 attempts conversion display in both cases.
  • Terminal gating and clearing. These obligations sit in the cited processes.progress.terminal requirement, so they only need to be applied in this case. The tests apply them:
    • The PTY test runs dumb and a redirected stderr. Neither emits the conversion display or escape sequences.
    • The unit test asserts the display clears for empty (total 0) and completed conversions.

I found no plausible violating behavior that these tests would accept.

Inputs

Implementation

Input 6: outline src/execution_coverage/runner.rs fn[finish]
// {impl}`requirements.test-coverage.processes.reports`
// {impl}`requirements.test-coverage.storage.provenance`
// {impl}`requirements.test-coverage.processes.progress`
fn finish(root: &Path, dir: &Path, cov: &Path, profdata: &Path, run: &mut Run) -> io::Result<()> {
    let maps: Vec<Map> = load(&dir.join("maps.json"))?;
    let mut attempts = fs::read_dir(dir.join("attempts"))?
        .map(|entry| entry.map(|entry| entry.path()))
        .collect::<io::Result<Vec<_>>>()?;
    attempts.sort();
    let progress = Progress::conversion(attempts.len());
    // Parallelize across attempts using the available CPUs. Each LLVM command
    // uses one thread so its own pool does not multiply this concurrency.
    let workers = std::thread::available_parallelism()
        .map(usize::from)
        .unwrap_or(1);
    let results = parallel_collect(
        &attempts,
        workers,
        |attempt| finish_attempt(attempt, dir, &maps, cov, profdata, root, &run.sources),
        |_| progress.completed(),
    );
    let mut failed = false;
    for (attempt_dir, result) in attempts.iter().zip(results) {
        match result {
            Ok(complete) => failed |= !complete,
            Err(error) => {
                run.diagnostics
                    .push(format!("{}: {error}", attempt_dir.display()));
                failed = true;
            }
        }
    }
    if failed {
        return Err(io::Error::other(
            "Some process coverage is missing or unreadable; partial profiles and reports have been retained.",
        ));
    }
    Ok(())
}

Tests

Input 3: outline src/execution_coverage/progress.rs mod[tests]/fn[stage_and_conversion_counts_are_visible_then_cleared]
    // {test}`requirements.test-coverage.processes.progress`
    // {test}`requirements.test-coverage.processes.progress.preparation`
    // {test}`requirements.test-coverage.processes.progress.terminal`
    #[test]
    fn stage_and_conversion_counts_are_visible_then_cleared() {
        let terminal = RecordingTerm::default();
        let target = || Some(ProgressDrawTarget::term_like(Box::new(terminal.clone())));
        {
            let preparation = Progress::with_target("Recording inputs", None, target());
            assert!(terminal.text.lock().unwrap().contains("Recording inputs"));
            preparation.stage("Capturing coverage maps");
            assert!(
                terminal
                    .text
                    .lock()
                    .unwrap()
                    .contains("Capturing coverage maps")
            );
            let before_drop = *terminal.clears.lock().unwrap();
            drop(preparation);
            assert!(*terminal.clears.lock().unwrap() > before_drop);
        }
        let cleared = *terminal.clears.lock().unwrap();
        assert!(cleared > 0);
        for total in [0, 2] {
            let conversion = Progress::with_target("Converting coverage", Some(total), target());
            let bar = conversion.bar.as_ref().unwrap();
            assert_eq!(bar.position(), 0);
            for expected in 1..=total {
                conversion.completed();
                bar.force_draw();
                assert_eq!(bar.position(), expected as u64);
                let text = terminal.text.lock().unwrap();
                assert!(
                    text.contains(&format!("{expected}/{total} attempts")),
                    "{text}"
                );
                assert!(text.contains("[00:00:"));
                assert!(!text.contains("\x1b["), "display must be monochrome");
            }
            let before_drop = *terminal.clears.lock().unwrap();
            drop(conversion);
            assert!(
                *terminal.clears.lock().unwrap() > before_drop,
                "completed and empty displays must both clear on drop"
            );
        }
        assert!(*terminal.clears.lock().unwrap() > cleared);
    }
Input 4: 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 5: 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());
}

Referenced definitions

Input 2: requirements selection requirements.test-coverage.processes.progress.terminal
:::{req} processes.progress.terminal
Habeas coverage progress MUST be displayed when stderr is an interactive
terminal and `TERM` is not `dumb`. `NO_COLOR` MUST disable color without
disabling progress. When stderr is redirected or `TERM=dumb`, Habeas coverage
progress MUST NOT emit animation or terminal control sequences.

Temporary progress displays MUST be cleared when their stage ends, including
empty work and early collection failures. Final diagnostics and the coverage
artifact location MUST remain readable. Progress reporting MUST NOT change
coverage results, retained profiles, or command exit status.
:::

Other sources

Input 1: requirements selection requirements.test-coverage.processes.progress
:::{req} processes.progress
During report conversion, on a terminal enabled under
{cite}`requirements.test-coverage.processes.progress.terminal`, Habeas MUST
display updating progress with elapsed time and completed and total
test-attempt counts. The total MUST count the recorded attempts selected for
conversion. An attempt MUST advance the completed count only after its
conversion has finished or reported a collection failure, including processing
its associated child-process profiles. These counts MUST measure conversion
work regardless of the attempt's test outcome.
:::
Input 7: outline src/execution_coverage/runner.rs fn[parallel_collect]
// {cite}`habeas:util`
fn parallel_collect<T: Sync, R: Send>(
    items: &[T],
    workers: usize,
    work: impl Fn(&T) -> R + Sync,
    mut completed: impl FnMut(usize),
) -> Vec<R> {
    let next = AtomicUsize::new(0);
    std::thread::scope(|scope| {
        let (sender, receiver) = std::sync::mpsc::channel();
        for _ in 0..workers.max(1).min(items.len()) {
            let sender = sender.clone();
            let next = &next;
            let work = &work;
            scope.spawn(move || {
                loop {
                    let index = next.fetch_add(1, Ordering::Relaxed);
                    let Some(item) = items.get(index) else {
                        break;
                    };
                    if sender.send((index, work(item))).is_err() {
                        break;
                    }
                }
            });
        }
        drop(sender);
        let mut results: Vec<Option<R>> =
            std::iter::repeat_with(|| None).take(items.len()).collect();
        for (index, result) in receiver {
            results[index] = Some(result);
            completed(index);
        }
        results
            .into_iter()
            .map(|result| result.expect("every conversion returned a result"))
            .collect()
    })
}
Input 8: outline src/execution_coverage/progress.rs mod[tests]/fn[terminal_policy_and_hidden_progress_emit_no_display]
    // {test}`requirements.test-coverage.processes.progress.terminal`
    #[test]
    fn terminal_policy_and_hidden_progress_emit_no_display() {
        for (terminal, term, expected) in [
            (true, None, true),
            (true, Some("xterm"), true),
            (true, Some("dumb"), false),
            (false, None, false),
            (false, Some("xterm"), false),
        ] {
            assert_eq!(enabled(terminal, term.map(std::ffi::OsStr::new)), expected);
        }
        let hidden = Progress::with_target("Converting coverage", Some(1), None);
        hidden.completed();
        hidden.stage("No display");
        assert!(hidden.bar.is_none());
    }