mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
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.
338 lines
17 KiB
Rust
338 lines
17 KiB
Rust
//! The build units a CI build used, for the dependency cache entry the gate saves.
|
|
//!
|
|
//! In a gate leg that saves the dependency cache, craft-common-actions' `rust-cache` action names a
|
|
//! file in `CRAFT_CACHE_UNITS`, and its `cache-trim` action deletes every build unit of the target
|
|
//! directory that the file does not name before the entry is saved. Cargo prints a JSON message for
|
|
//! 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};
|
|
use std::process::{Command, Stdio};
|
|
|
|
/// Cargo prints its messages as JSON on stdout and the diagnostics as text on stderr.
|
|
const MESSAGE_FORMAT: [&str; 2] = ["--message-format", "json-render-diagnostics"];
|
|
|
|
/// The record file, when this leg saves the cache.
|
|
fn file() -> Option<PathBuf> {
|
|
std::env::var_os("CRAFT_CACHE_UNITS").filter(|v| !v.is_empty()).map(PathBuf::from)
|
|
}
|
|
|
|
/// Runs `cmd`, a cargo build shown as `what`, which must exit successfully. When this leg saves the
|
|
/// cache, it adds `--message-format json-render-diagnostics` and appends Cargo's messages to the
|
|
/// record; every other stdout line (test output) still goes to stdout.
|
|
pub fn run(cmd: Command, what: &str) -> Result<(), String> {
|
|
match file() {
|
|
Some(file) => run_recorded(cmd, what, &file),
|
|
None => crate::run(cmd, what),
|
|
}
|
|
}
|
|
|
|
/// [`run`] with the record in `file`.
|
|
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 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), 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}: {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.
|
|
pub fn record_xtask() -> Result<(), String> {
|
|
if file().is_none() {
|
|
return Ok(());
|
|
}
|
|
let mut c = crate::cargo();
|
|
c.args(XTASK_BUILD);
|
|
run(c, &format!("cargo {}", XTASK_BUILD.join(" ")))
|
|
}
|
|
|
|
/// The build `cargo xtask` (the `run --package xtask` alias in `.cargo/config.toml`) runs first.
|
|
const XTASK_BUILD: [&str; 3] = ["build", "-p", "xtask"];
|
|
|
|
/// Lines that are Cargo's JSON messages go to `record`, every other line to `out`.
|
|
fn route(mut input: impl BufRead, record: &mut impl Write, out: &mut impl Write) -> std::io::Result<()> {
|
|
let mut line = Vec::new();
|
|
while input.read_until(b'\n', &mut line)? != 0 {
|
|
if line.starts_with(b"{\"reason\":") {
|
|
record.write_all(&line)?;
|
|
if !line.ends_with(b"\n") {
|
|
record.write_all(b"\n")?;
|
|
}
|
|
} else {
|
|
out.write_all(&line)?;
|
|
}
|
|
line.clear();
|
|
}
|
|
record.flush()?;
|
|
out.flush()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn cargo_messages_are_recorded_and_test_output_passes_through() {
|
|
let input =
|
|
"{\"reason\":\"compiler-artifact\",\"fresh\":true}\nrunning 3 tests\ntest a ... ok\n{\"reason\":\"build-finished\",\"success\":true}";
|
|
let (mut record, mut out) = (Vec::new(), Vec::new());
|
|
route(input.as_bytes(), &mut record, &mut out).unwrap();
|
|
assert_eq!(
|
|
String::from_utf8(record).unwrap(),
|
|
"{\"reason\":\"compiler-artifact\",\"fresh\":true}\n{\"reason\":\"build-finished\",\"success\":true}\n"
|
|
);
|
|
assert_eq!(String::from_utf8(out).unwrap(), "running 3 tests\ntest a ... ok\n");
|
|
}
|
|
|
|
#[test]
|
|
fn a_recorded_build_takes_no_separator() {
|
|
// A program that does not exist: the check comes before anything is spawned.
|
|
let mut c = Command::new("vectorcraft-no-such-cargo");
|
|
c.args(["clippy", "--", "-D", "warnings"]);
|
|
let file = std::env::temp_dir().join(format!("xtask-cache-units-separator-{}.jsonl", std::process::id()));
|
|
let err = run_recorded(c, "cargo clippy -- -D warnings", &file).unwrap_err();
|
|
assert!(err.contains("no `--` arguments"), "{err}");
|
|
assert!(!file.exists());
|
|
}
|
|
|
|
#[test]
|
|
fn xtask_record_build_matches_the_alias() {
|
|
let config = std::fs::read_to_string(crate::root().join(".cargo/config.toml")).unwrap();
|
|
assert!(config.lines().any(|l| l.trim() == "xtask = \"run --package xtask --\""), "{config}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_real_build_appends_its_units_fresh_on_the_second_run() {
|
|
let dir = std::env::temp_dir().join(format!("xtask-cache-units-build-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
std::fs::create_dir_all(dir.join("src")).unwrap();
|
|
std::fs::write(dir.join("Cargo.toml"), "[package]\nname = \"cache-unit-fixture\"\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").unwrap();
|
|
let record = dir.join("units.jsonl");
|
|
for expected_fresh in [false, true] {
|
|
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(["build", "--lib"]);
|
|
run_recorded(c, "cargo build --lib", &record).unwrap();
|
|
let messages: Vec<serde_json::Value> =
|
|
std::fs::read_to_string(&record).unwrap().lines().map(|line| serde_json::from_str(line).unwrap()).collect();
|
|
let artifacts: Vec<&serde_json::Value> =
|
|
messages.iter().filter(|m| m["reason"] == "compiler-artifact" && m["target"]["name"] == "cache_unit_fixture").collect();
|
|
// The record is appended to: the first build's message is still there after the second.
|
|
assert_eq!(artifacts.len(), if expected_fresh { 2 } else { 1 });
|
|
assert_eq!(artifacts.last().unwrap()["fresh"].as_bool(), Some(expected_fresh));
|
|
assert!(artifacts.iter().all(|m| !m["filenames"].as_array().unwrap().is_empty()));
|
|
assert_eq!(messages.last().unwrap()["reason"], "build-finished");
|
|
}
|
|
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();
|
|
}
|
|
}
|