Lines
60.54 %
Functions
28.57 %
Branches
100 %
//! The coverage phase: an instrumented test run rendered into
//! `web/static/doc/coverage`.
//!
//! Only the workspace's crates are instrumented (see [`wrapper`]), so wasmtime
//! and cranelift run at full speed and leave no profiles to merge or export.
//! grcov can read the raw profiles itself, but it then holds every binary's
//! results at once and runs one `llvm-cov` per CPU — about 13 GiB for this
//! workspace, enough to OOM-kill the job on an 8 GiB CI node. So the profiles
//! are merged here, each test executable and binary is exported to lcov on its
//! own, a few at a time, and grcov only renders. Exporting per object keeps
//! grcov's numbers: one export over every object discards the counters of
//! functions compiled differently in different binaries.
//! Unlike grcov, which skips an object llvm-cov cannot export, a failed export
//! fails the phase: every exported object carries a real coverage map, so a
//! failure means a broken build, and a quietly lower percentage would hide it.
mod elf;
mod export;
mod objects;
pub mod wrapper;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{Context, Result, bail};
use crate::clean::remove_dir_if_present;
use crate::heartbeat::Heartbeat;
use crate::release::{DOC_DIR, run};
use export::{WORKERS, export_objects};
const PROFRAW_DIR: &str = "target/coverage";
const PROFDATA: &str = "target/coverage.profdata";
const LCOV_DIR: &str = "target/coverage-lcov";
const TARGET_DIR: &str = "target/debug";
/// Runtime checks of every anodized `#[spec]`; the macros read it when they
/// compile, so it must reach every crate, not just the instrumented ones.
const INSTRUMENTED_RUSTFLAGS: &str = "--cfg anodized_panic";
const NEXTEST_ARGS: &[&str] = &[
"nextest",
"run",
"--no-fail-fast",
"--all-features",
"--workspace",
"--test-threads",
"4",
];
/// Coverage mapping needs only line tables, and full debuginfo made the
/// instrumented build and its test binaries much larger.
const DEBUG_LEVEL: &str = "line-tables-only";
/// Instrumented test run, then the HTML report.
pub fn run_coverage(heartbeat: &Heartbeat, database_url: &str) -> Result<()> {
let cwd = std::env::current_dir()?;
let profraw_dir = cwd.join(PROFRAW_DIR);
instrumented_test_run(heartbeat, &cwd, &profraw_dir, database_url)?;
let llvm_bin = llvm_bin()?;
let profdata = Path::new(PROFDATA);
heartbeat.phase("merge profiles");
merge_profiles(&llvm_bin.join("llvm-profdata"), &profraw_dir, profdata)?;
heartbeat.phase("llvm-cov export");
let exported = export_objects(
&llvm_bin.join("llvm-cov"),
profdata,
Path::new(TARGET_DIR),
Path::new(LCOV_DIR),
&format!("{}/", cwd.display()),
)?;
println!(">> exported {exported} instrumented objects");
heartbeat.phase("grcov");
render_html(
"grcov",
&PathBuf::from(DOC_DIR).join("coverage"),
)
}
fn instrumented_env(
pattern: &str,
database_url: &str,
wrapper_env: [(&'static str, OsString); 3],
) -> Vec<(&'static str, OsString)> {
let mut env = vec![
("RUSTFLAGS", INSTRUMENTED_RUSTFLAGS.into()),
("CARGO_INCREMENTAL", "0".into()),
("CARGO_PROFILE_DEV_DEBUG", DEBUG_LEVEL.into()),
("CARGO_PROFILE_TEST_DEBUG", DEBUG_LEVEL.into()),
("LLVM_PROFILE_FILE", pattern.into()),
("DATABASE_URL", database_url.into()),
env.extend(wrapper_env);
env
fn profile_pattern(profraw_dir: &Path) -> String {
profraw_dir
.join("nomisync-%4m.profraw")
.to_string_lossy()
.into_owned()
fn instrumented_test_run(
heartbeat: &Heartbeat,
root: &Path,
profraw_dir: &Path,
) -> Result<()> {
// `%4m` merges online into at most four files per binary signature, so the
// pool stays small however many processes the suite starts.
remove_dir_if_present(profraw_dir)?;
std::fs::create_dir_all(profraw_dir).context("cannot make the profraw dir")?;
let profile_pattern = profile_pattern(profraw_dir);
let previous = std::env::var_os("RUSTC_WRAPPER").unwrap_or_default();
let exe = std::env::current_exe().context("cannot find the xtask executable")?;
let env = instrumented_env(
&profile_pattern,
database_url,
wrapper::wrapper_env(&exe, &previous, root),
);
let env: Vec<(&str, &str)> = env
.iter()
.map(|(key, value)| Ok((*key, value.to_str().context("non-UTF-8 environment")?)))
.collect::<Result<_>>()?;
heartbeat.phase("instrumented test run");
// Watched, unlike every other phase here: this one prints a line per test,
// so silence means something is stuck rather than merely slow. A hang here
// once cost an hour and told us nothing about which test caused it.
// Nextest runs every test in its own process and every binary at once, so
// a 4-vCPU node stays busy. Doctests are not run: their binaries are
// temporary and never reach the coverage export.
// `--no-fail-fast`: one red test must not hide the others in the report.
crate::watchdog::run_watched("cargo", NEXTEST_ARGS, &env, Some(database_url))?;
// A coverage run that produced no profiles yields an empty-but-valid grcov
// report: green CI, blank coverage page. Assert instead.
let profraw_count = std::fs::read_dir(profraw_dir)
.context("cannot read the profraw dir")?
.filter_map(Result::ok)
.filter(|entry| entry.path().extension().is_some_and(|ext| ext == "profraw"))
.count();
if profraw_count == 0 {
bail!("no .profraw produced — coverage instrumentation did not run");
println!(">> {profraw_count} profraw files");
Ok(())
/// `llvm-tools` installs its binaries beside the host target's libdir.
fn llvm_bin() -> Result<PathBuf> {
let output = Command::new("rustc")
.args(["--print", "target-libdir"])
.output()
.context("failed to run rustc")?;
if !output.status.success() {
bail!("rustc --print target-libdir exited with {}", output.status);
let libdir = String::from_utf8(output.stdout).context("rustc printed a non-UTF-8 libdir")?;
let bin =
llvm_bin_for(Path::new(libdir.trim())).context("rustc's target libdir has no parent")?;
require_llvm_tools(bin)
fn llvm_bin_for(libdir: &Path) -> Option<PathBuf> {
libdir.parent().map(|host| host.join("bin"))
fn require_llvm_tools(bin: PathBuf) -> Result<PathBuf> {
if !bin.join("llvm-profdata").is_file() {
bail!(
"no llvm-profdata in {} — install it with `rustup component add llvm-tools`",
bin.display()
Ok(bin)
fn merge_profiles(tool: &Path, profraw_dir: &Path, profdata: &Path) -> Result<()> {
run(
&tool.to_string_lossy(),
&[
"merge",
"-sparse",
&format!("--num-threads={WORKERS}"),
"-o",
&profdata.to_string_lossy(),
&profraw_dir.to_string_lossy(),
],
&[],
fn render_html(grcov: &str, lcov_dir: &Path, coverage_dir: &Path) -> Result<()> {
// Stale trees must go first: `mv target/doc <existing>` nests the new tree
// inside the old one, silently pinning published pages to a snapshot.
remove_dir_if_present(coverage_dir)?;
grcov,
&lcov_dir.to_string_lossy(),
"-s",
".",
"-t",
"html",
"--branch",
"--ignore-not-existing",
"--ignore",
"/*",
"*cranelift*",
"*lexicon*",
"*incremental*",
&coverage_dir.to_string_lossy(),
// grcov exits zero on an empty profile set, so the tree existing is not the
// same as the tree having content. This job is the only place that can tell,
// and it is the artifact deploy will overlay.
let pages = std::fs::read_dir(coverage_dir)
.with_context(|| format!("grcov produced no {}", coverage_dir.display()))?
if pages == 0 {
"{} is empty — the coverage report has no pages",
coverage_dir.display()
println!(">> coverage report: {pages} entries");
#[cfg(test)]
mod test_fixtures;
mod tests;
mod tool_tests;