CI: keep integration test executables out of the gate's crates cache

The gate's `build` job builds the integration tests without recording
their units, so the trim before the cache save was meant to drop them.
actions/cache-trim keeps every unrecorded unit built during the job, so
a cold main build saved all of them: a 9.68 GB gate-crates entry, over
the repository's 10 GB cache budget, which was then evicted and left
every following build cold.

`cargo xtask ci archive` now collects the unit directories of the
integration test executables those builds made and deletes them once
the shard archives are written, in a leg that saves the cache. Units
the record names stay, and a unit that cannot be deleted is named in a
warning. The shards run the executables from their archives, and the
doctests that follow do not use them.
This commit is contained in:
dotCooCoo committed 2026-12-05 14:18:42 -08:00
1 parent 1cf9dd82a3
commit 8faf2a10f2
2 files changed
+203 -11

No files matched your search

+197 -8
View File
@@ -6,7 +6,13 @@
//! every unit a build compiled or found fresh. The builds of `cargo xtask ci archive` append those
//! messages to the file, so the saved entry holds this build and no older builds of updated
//! dependencies. Without `CRAFT_CACHE_UNITS` the commands run as they always have.
//!
//! The trim keeps an unrecorded unit that was built during the job, so the integration tests'
//! builds, which stay out of the record, would put their executables in the entry. `ci archive`
//! collects those units with [`run_unrecorded`] and deletes them with [`drop_units`] once the
//! archives are written.
use std::collections::HashSet;
use std::fs::OpenOptions;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
@@ -31,24 +37,115 @@ pub fn run(cmd: Command, what: &str) -> Result<(), String> {
}
/// [`run`] with the record in `file`.
fn run_recorded(mut cmd: Command, what: &str, file: &Path) -> Result<(), String> {
// After `--` the flag would go to rustc or the test binaries instead of cargo.
if cmd.get_args().any(|a| a == "--") {
return Err(format!("{what}: a recorded build takes no `--` arguments"));
}
fn run_recorded(cmd: Command, what: &str, file: &Path) -> Result<(), String> {
no_separator(&cmd, what)?;
let mut record = OpenOptions::new().create(true).append(true).open(file).map_err(|e| format!("{}: {e}", file.display()))?;
run_routed(cmd, what, &mut record, &format!("recording the build units in {}", file.display()))
}
/// Runs `cmd`, a cargo build shown as `what`, which must exit successfully, with Cargo's messages
/// going to `messages` (`doing` names that in an error) and every other stdout line to stdout.
fn run_routed(mut cmd: Command, what: &str, messages: &mut impl Write, doing: &str) -> Result<(), String> {
no_separator(&cmd, what)?;
cmd.args(MESSAGE_FORMAT);
eprintln!("$ {what} {}", MESSAGE_FORMAT.join(" "));
let mut record = OpenOptions::new().create(true).append(true).open(file).map_err(|e| format!("{}: {e}", file.display()))?;
let mut child = cmd.stdout(Stdio::piped()).spawn().map_err(|e| format!("{what}: failed to spawn: {e}"))?;
let routed = match child.stdout.take() {
Some(stdout) => route(BufReader::new(stdout), &mut record, &mut std::io::stdout().lock()),
Some(stdout) => route(BufReader::new(stdout), messages, &mut std::io::stdout().lock()),
None => Err(std::io::Error::other("no stdout pipe")),
};
let status = child.wait().map_err(|e| format!("{what}: {e}"))?;
routed.map_err(|e| format!("{what}: recording the build units in {}: {e}", file.display()))?;
routed.map_err(|e| format!("{what}: {doing}: {e}"))?;
if status.success() { Ok(()) } else { Err(format!("{what}: exited with {status}")) }
}
/// After `--` the message-format flag would go to rustc or the test binaries instead of cargo.
fn no_separator(cmd: &Command, what: &str) -> Result<(), String> {
if cmd.get_args().any(|a| a == "--") { Err(format!("{what}: a recorded build takes no `--` arguments")) } else { Ok(()) }
}
/// Runs `cmd`, a cargo build shown as `what` whose units stay out of the record, which must exit
/// successfully. When this leg saves the cache, it returns the unit directories of the integration
/// test executables the build compiled or found fresh, for [`drop_units`]; otherwise none.
pub fn run_unrecorded(cmd: Command, what: &str) -> Result<Vec<PathBuf>, String> {
if file().is_none() {
crate::run(cmd, what)?;
return Ok(Vec::new());
}
let mut messages = Vec::new();
run_routed(cmd, what, &mut messages, "reading the build messages")?;
Ok(integration_units(&messages))
}
/// The unit directory of each integration test executable that Cargo's `messages` name, or the
/// executable itself when it lies in no unit directory.
fn integration_units(messages: &[u8]) -> Vec<PathBuf> {
let mut units = Vec::new();
for line in messages.split(|b| *b == b'\n') {
let Ok(m) = serde_json::from_slice::<serde_json::Value>(line) else { continue };
let integration = m["reason"] == "compiler-artifact"
&& m["profile"]["test"] == true
&& m["target"]["kind"].as_array().is_some_and(|k| k.iter().any(|k| k == "test"));
let Some(exe) = m["executable"].as_str().filter(|_| integration) else { continue };
let exe = Path::new(exe);
let unit = unit_of(exe).unwrap_or(exe).to_path_buf();
if !units.contains(&unit) {
units.push(unit);
}
}
units
}
/// The `<profile>/build/<package>/<hash>` directory `path` lies in, as actions/cache-trim finds it.
fn unit_of(path: &Path) -> Option<&Path> {
path.ancestors().find(|d| {
let hash = d.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.len() == 16 && n.bytes().all(|b| b.is_ascii_hexdigit()));
hash && d.parent().and_then(Path::parent).and_then(Path::file_name).is_some_and(|n| n == "build")
})
}
/// Deletes `units` ([`run_unrecorded`]) from the target directory before the cache is saved, except
/// those the record names. Nothing later in the build job runs the integration tests' executables:
/// the shards run them from their archives. A unit that cannot be deleted is named in a warning and
/// stays in the entry.
pub fn drop_units(units: &[PathBuf]) {
if let Some(record) = file().filter(|_| !units.is_empty()) {
drop_units_in(units, &record);
}
}
/// [`drop_units`] with the record in `record`; returns how many units it deleted.
fn drop_units_in(units: &[PathBuf], record: &Path) -> usize {
let recorded = match std::fs::read_to_string(record) {
Ok(text) => recorded_units(&text),
Err(e) => {
println!("::warning::ci archive: {}: {e}; the integration test executables stay in the cache entry", record.display());
return 0;
}
};
let mut dropped = 0;
for unit in units.iter().filter(|u| !recorded.contains(*u)) {
let removed = if unit.is_dir() { std::fs::remove_dir_all(unit) } else { std::fs::remove_file(unit) };
match removed {
Ok(()) => dropped += 1,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => println!("::warning::ci archive: could not delete {}: {e}; it stays in the cache entry", unit.display()),
}
}
eprintln!("ci archive: deleted {dropped} integration test units, which the cache entry does not keep");
dropped
}
/// The unit directories, or files outside one, that the record's messages name.
fn recorded_units(record: &str) -> HashSet<PathBuf> {
let mut units = HashSet::new();
for m in record.lines().filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok()) {
let named = m["filenames"].as_array().into_iter().flatten().chain([&m["executable"], &m["out_dir"]]);
units.extend(named.filter_map(|p| p.as_str()).map(Path::new).map(|p| unit_of(p).unwrap_or(p).to_path_buf()));
}
units
}
/// Records xtask's own units. `cargo xtask` builds xtask before xtask can record anything, and the
/// trim deletes an unrecorded unit from the entry, so the next run would build xtask again. The
/// build is fresh by now, so this only prints the messages.
@@ -145,4 +242,96 @@ mod tests {
}
std::fs::remove_dir_all(dir).unwrap();
}
/// A `compiler-artifact` message for a target of `kind`, built in the test profile or not.
fn artifact(kind: &str, test: bool, executable: Option<&str>, filenames: &[&str]) -> String {
serde_json::json!({
"reason": "compiler-artifact",
"target": { "kind": [kind], "name": "fixture" },
"profile": { "test": test },
"filenames": filenames,
"executable": executable,
"fresh": false,
})
.to_string()
}
#[test]
fn only_integration_test_executables_are_collected() {
let it = "/t/debug/build/fixture/0123456789abcdef/out/it-0123456789abcdef";
let messages = [
artifact("test", true, Some(it), &[it]),
// The same unit found fresh by a later build.
artifact("test", true, Some(it), &[it]),
// The library's test harness: recorded by the unit tests' build, never dropped.
artifact("lib", true, Some("/t/debug/build/fixture/fedcba9876543210/out/fixture-fedcba9876543210"), &[]),
artifact("lib", false, None, &["/t/debug/build/fixture/1111111111111111/out/libfixture.rlib"]),
// An executable outside a unit directory (Cargo's older `deps/` layout).
artifact("test", true, Some("/t/debug/deps/other-2222222222222222"), &[]),
"running 0 tests".into(),
serde_json::json!({ "reason": "build-finished", "success": true }).to_string(),
]
.join("\n");
assert_eq!(
integration_units(messages.as_bytes()),
[PathBuf::from("/t/debug/build/fixture/0123456789abcdef"), PathBuf::from("/t/debug/deps/other-2222222222222222")]
);
}
#[test]
fn dropping_units_keeps_the_ones_the_record_names() {
let dir = std::env::temp_dir().join(format!("xtask-cache-units-drop-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let unit = |hash: &str| dir.join("debug/build/fixture").join(hash);
let (dropped, recorded, missing) = (unit("0123456789abcdef"), unit("fedcba9876543210"), unit("1111111111111111"));
for u in [&dropped, &recorded] {
std::fs::create_dir_all(u.join("out")).unwrap();
std::fs::write(u.join("out/bin"), "x").unwrap();
}
let record = dir.join("units.jsonl");
let named = recorded.join("out/bin");
std::fs::write(&record, artifact("lib", true, named.to_str(), &[]) + "\n").unwrap();
assert_eq!(drop_units_in(&[dropped.clone(), recorded.clone(), missing], &record), 1);
assert!(!dropped.exists());
assert!(named.exists());
// Without a readable record nothing is deleted.
assert_eq!(drop_units_in(std::slice::from_ref(&recorded), &dir.join("absent.jsonl")), 0);
assert!(named.exists());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_real_integration_test_build_is_dropped_and_the_record_kept() {
let dir = std::env::temp_dir().join(format!("xtask-cache-units-it-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::create_dir_all(dir.join("tests")).unwrap();
std::fs::write(dir.join("Cargo.toml"), "[package]\nname = \"cache-unit-it\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n")
.unwrap();
std::fs::write(dir.join("src/lib.rs"), "pub fn one() -> u32 { 1 }\n#[test]\nfn unit() {}\n").unwrap();
std::fs::write(dir.join("tests/it.rs"), "#[test]\nfn it() { assert_eq!(cache_unit_it::one(), 1); }\n").unwrap();
let build = |args: &[&str]| {
let mut c = crate::cargo();
c.current_dir(&dir)
.env("CARGO_TARGET_DIR", dir.join("target"))
.env("CARGO_BUILD_BUILD_DIR", dir.join("target"))
.env("CARGO_NET_OFFLINE", "true")
.args(args);
c
};
let record = dir.join("units.jsonl");
run_recorded(build(&["test", "--lib", "--no-run"]), "cargo test --lib --no-run", &record).unwrap();
let mut messages = Vec::new();
run_routed(build(&["test", "--test", "*", "--no-run"]), "cargo test --test '*' --no-run", &mut messages, "reading").unwrap();
let executable = |m: &serde_json::Value| m["executable"].as_str().map(PathBuf::from);
let parsed: Vec<serde_json::Value> = messages.split(|b| *b == b'\n').filter_map(|l| serde_json::from_slice(l).ok()).collect();
let it = parsed.iter().find(|m| m["target"]["name"] == "it").and_then(executable).unwrap();
let record_text = std::fs::read_to_string(&record).unwrap();
let harness = record_text.lines().map(|l| serde_json::from_str::<serde_json::Value>(l).unwrap()).find_map(|m| executable(&m)).unwrap();
assert!(it.is_file() && harness.is_file());
assert_eq!(drop_units_in(&integration_units(&messages), &record), 1);
assert!(!it.exists(), "{}", it.display());
assert!(harness.is_file(), "{}", harness.display());
std::fs::remove_dir_all(dir).unwrap();
}
}
+6 -3
View File
@@ -465,8 +465,9 @@ fn cmd_ci_shard() -> Result<(), String> {
///
/// In a leg that saves the cache, the library and binary tests' builds record their units in
/// `CRAFT_CACHE_UNITS` (xtask/src/cache_units.rs), xtask's own build included, and the
/// integration tests' builds do not, so the saved entry holds every dependency and
/// dev-dependency the tests build with and none of the integration tests' executables.
/// integration tests' builds do not. The trim keeps an unrecorded unit built during the job, so
/// once the archives are written this deletes the integration tests' executables, and the saved
/// entry holds every dependency and dev-dependency the tests build with and none of them.
fn cmd_ci_archive() -> Result<(), String> {
let var = |key: &str| {
std::env::var(key).ok().filter(|v| !v.is_empty()).ok_or_else(|| format!("ci archive: {key} is not set (the gate workflow sets it)"))
@@ -479,9 +480,10 @@ fn cmd_ci_archive() -> Result<(), String> {
cache_units::record_xtask()?;
let checked = shards::run()?;
let archived = archived_runs(&checked)?;
let mut integration = Vec::new();
for (units, r) in archive_builds(&checked) {
let (c, what) = test_build(&r, units);
if units { cache_units::run(c, &what)? } else { run(c, &what)? }
if units { cache_units::run(c, &what)? } else { integration.extend(cache_units::run_unrecorded(c, &what)?) }
}
for (i, (shard, r)) in checked.iter().zip(archived).enumerate() {
let file = dir.join((i + 1).to_string()).join(&name);
@@ -500,6 +502,7 @@ fn cmd_ci_archive() -> Result<(), String> {
let what = format!("cargo nextest archive {} ({}) --archive-file {}", r.targets.shown(), shards::names(&r.crates), file.display());
run(c, &what)?;
}
cache_units::drop_units(&integration);
Ok(())
}