From 3512a47d91d58e6a31af400983f4a6285353c582 Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 02:39:21 +0100 Subject: [PATCH 1/6] Record build units during shard planning --- xtask/src/cache_units.rs | 28 ++++++++++++++++++++++++++++ xtask/src/main.rs | 26 +++++++++++++++++--------- 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/xtask/src/cache_units.rs b/xtask/src/cache_units.rs index 892e3ffc86..57b21f82ed 100644 --- a/xtask/src/cache_units.rs +++ b/xtask/src/cache_units.rs @@ -31,6 +31,23 @@ pub fn run(mut cmd: Command, what: &str) -> Result<(), String> { if status.success() { Ok(()) } else { Err(format!("{what}: exited with {status}")) } } +/// Capture non-Cargo output while recording Cargo messages, for a command whose output is data. +pub fn capture(mut cmd: Command, what: &str) -> Result, String> { + eprintln!("$ {what}"); + let mut record = file().map(|file| OpenOptions::new().create(true).append(true).open(&file).map_err(|e| format!("{}: {e}", file.display()))).transpose()?; + let mut child = cmd.stdout(Stdio::piped()).spawn().map_err(|e| format!("{what}: failed to spawn: {e}"))?; + let stdout = child.stdout.take().expect("piped stdout"); + let mut output = Vec::new(); + let routed = if let Some(record) = &mut record { + route(BufReader::new(stdout), record, &mut output) + } else { + std::io::copy(&mut BufReader::new(stdout), &mut output).map(|_| ()) + }; + let status = child.wait().map_err(|e| format!("{what}: {e}"))?; + routed.map_err(|e| format!("{what}: reading output: {e}"))?; + if status.success() { Ok(output) } else { Err(format!("{what}: exited with {status}")) } +} + /// Records xtask's own units: `cargo xtask` builds it before it can record anything, and an /// unrecorded unit is trimmed from the entry and rebuilt next run. The build is fresh, so this only /// prints the messages. @@ -73,4 +90,15 @@ mod tests { 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 mixed_nextest_listing_keeps_json_separate_and_rejects_truncation() { + let input = b"{\"reason\":\"compiler-artifact\",\"fresh\":false}\n{\"rust-suites\":{}}\n"; + let (mut record, mut listing) = (Vec::new(), Vec::new()); + route(input.as_slice(), &mut record, &mut listing).unwrap(); + assert_eq!(record, b"{\"reason\":\"compiler-artifact\",\"fresh\":false}\n"); + assert!(serde_json::from_slice::(&listing).is_ok()); + listing.truncate(listing.len() - 3); + assert!(serde_json::from_slice::(&listing).is_err()); + } } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index fa1eae5e52..f3d403c3ea 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -526,16 +526,24 @@ fn build_tests(o: &CiOptions) -> Result<(), String> { } /// `cargo nextest list --profile ci --message-format json` of the test build, with `args`. -fn nextest_list(o: &CiOptions, args: &[&str]) -> Result { +fn nextest_list(o: &CiOptions, args: &[&str], record: bool) -> Result { let mut c = cargo(); c.args(["nextest", "list", "--profile", "ci", "--message-format", "json"]).args(test_build_args(&o.exclude)).args(args); - let what = shown(&c); - eprintln!("$ {what}"); - let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("{what}: failed to spawn: {e}"))?; - if !out.status.success() { - return Err(format!("{what}: exited with {}", out.status)); + if record && cache_units::file().is_some() { + c.args(["--cargo-message-format", "json-render-diagnostics"]); } - serde_json::from_slice(&out.stdout).map_err(|e| format!("{what}: bad JSON: {e}")) + let what = shown(&c); + let out = if record { + cache_units::capture(c, &what)? + } else { + eprintln!("$ {what}"); + let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("{what}: failed to spawn: {e}"))?; + if !out.status.success() { + return Err(format!("{what}: exited with {}", out.status)); + } + out.stdout + }; + serde_json::from_slice(&out).map_err(|e| format!("{what}: bad JSON: {e}")) } /// The gate's build job with per-shard archives: builds the tests, lists them, plans which binaries @@ -550,7 +558,7 @@ fn build_shard_archives(o: &CiOptions, dir: &Path, name: &str, shards: usize, gp }); let times = shards::Times::parse(&text, os)?; // The build itself, and every binary it made. - let built = nextest_list(o, &["--list-type", "binaries-only"])?; + let built = nextest_list(o, &["--list-type", "binaries-only"], true)?; let ids: Vec = built.get("rust-binaries").and_then(serde_json::Value::as_object).ok_or("nextest list: no rust-binaries")?.keys().cloned().collect(); // With a GPU shard every binary is listed against the gpu group; otherwise only the split ones. let filter = if gpu_shard { @@ -559,7 +567,7 @@ fn build_shard_archives(o: &CiOptions, dir: &Path, name: &str, shards: usize, gp let split: Vec = shards::binaries_to_list(&ids, ×, shards).iter().map(|b| format!("binary_id(={b})")).collect(); if split.is_empty() { "none()".to_string() } else { split.join(" | ") } }; - let listing = nextest_list(o, &["--run-ignored", "all", "-E", &filter])?; + let listing = nextest_list(o, &["--run-ignored", "all", "-E", &filter], false)?; let (binaries, target) = shards::parse_listing(&listing, gpu_shard)?; let plan = shards::plan(&binaries, ×, shards, gpu_shard)?; eprint!("{}", plan.summary()); From 5c34f6dbef59a2f63d6ea3837c801598e9d1db2b Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 02:41:56 +0100 Subject: [PATCH 2/6] Reject malformed Cargo messages while draining output --- xtask/src/cache_units.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/xtask/src/cache_units.rs b/xtask/src/cache_units.rs index 57b21f82ed..a034c25e62 100644 --- a/xtask/src/cache_units.rs +++ b/xtask/src/cache_units.rs @@ -63,11 +63,17 @@ pub fn record_xtask() -> Result<(), String> { /// 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(); + let mut malformed = false; 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")?; + if serde_json::from_slice::(&line).is_err() { + // Keep draining the child so it cannot block on a full stdout pipe. + malformed = true; + } else { + record.write_all(&line)?; + if !line.ends_with(b"\n") { + record.write_all(b"\n")?; + } } } else { out.write_all(&line)?; @@ -75,7 +81,8 @@ fn route(mut input: impl BufRead, record: &mut impl Write, out: &mut impl Write) line.clear(); } record.flush()?; - out.flush() + out.flush()?; + if malformed { Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "malformed Cargo JSON message")) } else { Ok(()) } } #[cfg(test)] @@ -100,5 +107,9 @@ mod tests { assert!(serde_json::from_slice::(&listing).is_ok()); listing.truncate(listing.len() - 3); assert!(serde_json::from_slice::(&listing).is_err()); + let (mut record, mut listing) = (Vec::new(), Vec::new()); + assert!(route(b"{\"reason\":\"compiler-artifact\"\n{\"rust-suites\":{}}\n".as_slice(), &mut record, &mut listing).is_err()); + assert!(record.is_empty()); + assert!(serde_json::from_slice::(&listing).is_ok()); } } From b61d81bb08a71029fbd31fdcf341e480b3157d1b Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 02:45:36 +0100 Subject: [PATCH 3/6] Keep unrecorded listing path unchanged and verify real output --- xtask/src/cache_units.rs | 61 ++++++++++++++++++++++++++-------------- xtask/src/main.rs | 7 +++-- 2 files changed, 44 insertions(+), 24 deletions(-) diff --git a/xtask/src/cache_units.rs b/xtask/src/cache_units.rs index a034c25e62..90b146cdfe 100644 --- a/xtask/src/cache_units.rs +++ b/xtask/src/cache_units.rs @@ -32,17 +32,13 @@ pub fn run(mut cmd: Command, what: &str) -> Result<(), String> { } /// Capture non-Cargo output while recording Cargo messages, for a command whose output is data. -pub fn capture(mut cmd: Command, what: &str) -> Result, String> { +pub fn capture_recorded(mut cmd: Command, what: &str, file: &std::path::Path) -> Result, String> { eprintln!("$ {what}"); - let mut record = file().map(|file| OpenOptions::new().create(true).append(true).open(&file).map_err(|e| format!("{}: {e}", file.display()))).transpose()?; + 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 stdout = child.stdout.take().expect("piped stdout"); let mut output = Vec::new(); - let routed = if let Some(record) = &mut record { - route(BufReader::new(stdout), record, &mut output) - } else { - std::io::copy(&mut BufReader::new(stdout), &mut output).map(|_| ()) - }; + let routed = route(BufReader::new(stdout), &mut record, &mut output); let status = child.wait().map_err(|e| format!("{what}: {e}"))?; routed.map_err(|e| format!("{what}: reading output: {e}"))?; if status.success() { Ok(output) } else { Err(format!("{what}: exited with {status}")) } @@ -63,17 +59,11 @@ pub fn record_xtask() -> Result<(), String> { /// 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(); - let mut malformed = false; while input.read_until(b'\n', &mut line)? != 0 { if line.starts_with(b"{\"reason\":") { - if serde_json::from_slice::(&line).is_err() { - // Keep draining the child so it cannot block on a full stdout pipe. - malformed = true; - } else { - record.write_all(&line)?; - if !line.ends_with(b"\n") { - record.write_all(b"\n")?; - } + record.write_all(&line)?; + if !line.ends_with(b"\n") { + record.write_all(b"\n")?; } } else { out.write_all(&line)?; @@ -81,8 +71,7 @@ fn route(mut input: impl BufRead, record: &mut impl Write, out: &mut impl Write) line.clear(); } record.flush()?; - out.flush()?; - if malformed { Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "malformed Cargo JSON message")) } else { Ok(()) } + out.flush() } #[cfg(test)] @@ -107,9 +96,39 @@ mod tests { assert!(serde_json::from_slice::(&listing).is_ok()); listing.truncate(listing.len() - 3); assert!(serde_json::from_slice::(&listing).is_err()); + } + + #[test] + fn real_nextest_list_records_build_without_rebuilding() { + if !crate::nextest_available() { + eprintln!("cargo-nextest unavailable; skipping mixed-stream integration test"); + return; + } + let dir = std::env::temp_dir().join(format!("photocraft-cache-units-{}", std::process::id())); + 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").unwrap(); + std::fs::write(dir.join("src/lib.rs"), "#[test] fn one() {}\n").unwrap(); + let list = || { + let out = crate::cargo() + .current_dir(&dir) + .env("CARGO_TARGET_DIR", dir.join("target")) + .env("CARGO_BUILD_BUILD_DIR", dir.join("target")) + .env("CARGO_NET_OFFLINE", "true") + .args(["nextest", "list", "--message-format", "json", "--cargo-message-format", "json-render-diagnostics"]) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + out + }; + let first = list(); + assert!(String::from_utf8_lossy(&first.stderr).contains("Compiling")); let (mut record, mut listing) = (Vec::new(), Vec::new()); - assert!(route(b"{\"reason\":\"compiler-artifact\"\n{\"rust-suites\":{}}\n".as_slice(), &mut record, &mut listing).is_err()); - assert!(record.is_empty()); - assert!(serde_json::from_slice::(&listing).is_ok()); + route(first.stdout.as_slice(), &mut record, &mut listing).unwrap(); + assert!(String::from_utf8_lossy(&record).contains("compiler-artifact")); + let json: serde_json::Value = serde_json::from_slice(&listing).unwrap(); + assert_eq!(json["test-count"], 1); + let second = list(); + assert!(!String::from_utf8_lossy(&second.stderr).contains("Compiling")); + std::fs::remove_dir_all(dir).unwrap(); } } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index f3d403c3ea..73a9fc8f6d 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -529,12 +529,13 @@ fn build_tests(o: &CiOptions) -> Result<(), String> { fn nextest_list(o: &CiOptions, args: &[&str], record: bool) -> Result { let mut c = cargo(); c.args(["nextest", "list", "--profile", "ci", "--message-format", "json"]).args(test_build_args(&o.exclude)).args(args); - if record && cache_units::file().is_some() { + let record = record.then(cache_units::file).flatten(); + if record.is_some() { c.args(["--cargo-message-format", "json-render-diagnostics"]); } let what = shown(&c); - let out = if record { - cache_units::capture(c, &what)? + let out = if let Some(file) = record { + cache_units::capture_recorded(c, &what, &file)? } else { eprintln!("$ {what}"); let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("{what}: failed to spawn: {e}"))?; From 38826a67de43654842d785a250531b0c219dae20 Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 02:47:22 +0100 Subject: [PATCH 4/6] Exercise the binaries-only listing used for planning --- xtask/src/cache_units.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xtask/src/cache_units.rs b/xtask/src/cache_units.rs index 90b146cdfe..859ad18c91 100644 --- a/xtask/src/cache_units.rs +++ b/xtask/src/cache_units.rs @@ -114,7 +114,7 @@ mod tests { .env("CARGO_TARGET_DIR", dir.join("target")) .env("CARGO_BUILD_BUILD_DIR", dir.join("target")) .env("CARGO_NET_OFFLINE", "true") - .args(["nextest", "list", "--message-format", "json", "--cargo-message-format", "json-render-diagnostics"]) + .args(["nextest", "list", "--list-type", "binaries-only", "--message-format", "json", "--cargo-message-format", "json-render-diagnostics"]) .output() .unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); @@ -126,7 +126,7 @@ mod tests { route(first.stdout.as_slice(), &mut record, &mut listing).unwrap(); assert!(String::from_utf8_lossy(&record).contains("compiler-artifact")); let json: serde_json::Value = serde_json::from_slice(&listing).unwrap(); - assert_eq!(json["test-count"], 1); + assert_eq!(json["rust-binaries"].as_object().unwrap().len(), 1); let second = list(); assert!(!String::from_utf8_lossy(&second.stderr).contains("Compiling")); std::fs::remove_dir_all(dir).unwrap(); From fc17b2d5fae67fc3ee2bcc78022a75f49c4195b5 Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 03:03:06 +0100 Subject: [PATCH 5/6] Select fixture profile under nextest CI --- xtask/src/cache_units.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/xtask/src/cache_units.rs b/xtask/src/cache_units.rs index 859ad18c91..59df9abed2 100644 --- a/xtask/src/cache_units.rs +++ b/xtask/src/cache_units.rs @@ -114,7 +114,19 @@ mod tests { .env("CARGO_TARGET_DIR", dir.join("target")) .env("CARGO_BUILD_BUILD_DIR", dir.join("target")) .env("CARGO_NET_OFFLINE", "true") - .args(["nextest", "list", "--list-type", "binaries-only", "--message-format", "json", "--cargo-message-format", "json-render-diagnostics"]) + .env("NEXTEST_PROFILE", "ci") + .args([ + "nextest", + "list", + "--profile", + "default", + "--list-type", + "binaries-only", + "--message-format", + "json", + "--cargo-message-format", + "json-render-diagnostics", + ]) .output() .unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); From 4dc260d9e838bf938775ea0035db71a470fe1337 Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 04:51:55 +0100 Subject: [PATCH 6/6] Check Cargo artifact freshness in fixture --- xtask/src/cache_units.rs | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/xtask/src/cache_units.rs b/xtask/src/cache_units.rs index 59df9abed2..5c48c92844 100644 --- a/xtask/src/cache_units.rs +++ b/xtask/src/cache_units.rs @@ -132,15 +132,21 @@ mod tests { assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); out }; - let first = list(); - assert!(String::from_utf8_lossy(&first.stderr).contains("Compiling")); - let (mut record, mut listing) = (Vec::new(), Vec::new()); - route(first.stdout.as_slice(), &mut record, &mut listing).unwrap(); - assert!(String::from_utf8_lossy(&record).contains("compiler-artifact")); - let json: serde_json::Value = serde_json::from_slice(&listing).unwrap(); - assert_eq!(json["rust-binaries"].as_object().unwrap().len(), 1); - let second = list(); - assert!(!String::from_utf8_lossy(&second.stderr).contains("Compiling")); + for expected_fresh in [false, true] { + let output = list(); + let (mut record, mut listing) = (Vec::new(), Vec::new()); + route(output.stdout.as_slice(), &mut record, &mut listing).unwrap(); + let artifacts: Vec = record + .split(|&b| b == b'\n') + .filter(|line| !line.is_empty()) + .map(|line| serde_json::from_slice(line).unwrap()) + .filter(|message: &serde_json::Value| message["reason"] == "compiler-artifact") + .collect(); + assert!(!artifacts.is_empty()); + assert!(artifacts.iter().all(|message| message["fresh"].as_bool() == Some(expected_fresh))); + let json: serde_json::Value = serde_json::from_slice(&listing).unwrap(); + assert_eq!(json["rust-binaries"].as_object().unwrap().len(), 1); + } std::fs::remove_dir_all(dir).unwrap(); } }