From 78c9db2626eecbab4736dbd7bfa1d9a68fb035f5 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 16:18:39 +0900 Subject: [PATCH 1/3] test(vtest): run shared cases through an optimized executor Add an opt-in shared executor with runtime corpus loading while preserving existing libtest registrations and nextest scheduling. Avoid Rust rebuilds for vtest body edits and retain the embedded in-process path. Change-Id: I782a196b4d4b952a7c5122984f2f9785cc61d153 --- CONTRIBUTING.md | 35 ++++++ Cargo.lock | 1 + Cargo.toml | 6 ++ crates/celox-test-suite/Cargo.toml | 5 + crates/celox-test-suite/build.rs | 5 +- crates/celox-test-suite/src/lib.rs | 2 + crates/celox-test-suite/src/runtime_cases.rs | 101 ++++++++++++++++++ crates/celox-test-suite/src/sv/mod.rs | 11 +- crates/celox-test-suite/src/veryl/mod.rs | 9 +- crates/celox/Cargo.toml | 4 + crates/celox/examples/vtest-exec.rs | 42 ++++++++ .../tests/frontends/systemverilog/suite.rs | 5 +- crates/celox/tests/systemverilog.rs | 3 + crates/celox/tests/test_utils/mod.rs | 1 + crates/celox/tests/test_utils/suite.rs | 3 + crates/celox/tests/test_utils/vtest_exec.rs | 22 ++++ scripts/run-vtest.mjs | 55 ++++++++++ scripts/run-vtest.test.mjs | 42 ++++++++ 18 files changed, 347 insertions(+), 5 deletions(-) create mode 100644 crates/celox-test-suite/src/runtime_cases.rs create mode 100644 crates/celox/examples/vtest-exec.rs create mode 100644 crates/celox/tests/test_utils/vtest_exec.rs create mode 100644 scripts/run-vtest.mjs create mode 100644 scripts/run-vtest.test.mjs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2c6b6912b76..2a4e01a30a6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,6 +40,41 @@ Use the actual affected case or group as the filter. For SystemVerilog cases, use the `verify-sv-verilator` and `verify-sv-icarus` binaries. Missing tools, empty selections, compilation failures, and simulator errors are not passes. +For repeated local vtest runs, use the optimized shared executor: + +```sh +node scripts/run-vtest.mjs --test counter +node scripts/run-vtest.mjs --test systemverilog -E 'test(operators::)' +``` + +This builds `vtest-exec` with the `vtest` Cargo profile (`opt-level = 1`, +development assertions and overflow checks enabled), then runs the existing +Celox test registrations with nextest. Both builds enable `systemverilog` and +`celox-test-suite/runtime-cases`. Cases execute in the shared binary, while +Rust API tests execute normally. Existing test names, filters, backend omissions, +ignored cases and nextest's parallel scheduling/timeouts are preserved. Additional +arguments are passed to `cargo nextest run`; use `--run-ignored all` to include +ignored registrations deliberately. + +With `runtime-cases`, `.vtest` bodies are read from disk instead of embedded in +Rust binaries, so edits to an existing case do not require recompilation. Adding +a test registration or changing Rust still requires a build. The first run builds +both the optimized executor and ordinary test binaries; the executor profile has +its own Cargo cache. Ordinary Cargo test commands retain the embedded, in-process +path, and CI continues to use that path. + +For debugging a single case after building, the executor also accepts +` ` directly, for example: + +```sh +target/vtest/examples/vtest-exec veryl counter::test_counter_n4_basic native +``` + +Direct invocations do not apply registration-level ignores. `CELOX_VTEST_ROOT` +can point to an alternative corpus root containing `veryl/cases` and `sv/cases`; +otherwise the executor uses the suite's source directory from its build checkout. +The script sets that root and `CELOX_VTEST_RUNNER` for its test invocation only. + External results are reused locally by default, including between worktrees, when the case, verifier and tool fingerprints match. New/changed cases and prior failures run again; `--fresh` forces execution. A Celox implementation diff --git a/Cargo.lock b/Cargo.lock index a7bb33ff72b..248419dde03 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -799,6 +799,7 @@ dependencies = [ "num-traits", "serde_json", "sha2 0.11.1", + "tempfile", "veryl-analyzer", "veryl-emitter", "veryl-metadata", diff --git a/Cargo.toml b/Cargo.toml index 76c0db9690d..8c770d54d64 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -166,6 +166,12 @@ incremental = true [profile.bench] debug = true +# Optimize the shared vtest executor while keeping development checks enabled. +# External dependencies retain the dev profile's package-specific optimization. +[profile.vtest] +inherits = "dev" +opt-level = 1 + # Profile for wasm-pack builds. LTO is disabled to avoid a known issue # where proc-macro dependencies (syn) get incorrectly compiled for the # wasm32 target under full LTO. diff --git a/crates/celox-test-suite/Cargo.toml b/crates/celox-test-suite/Cargo.toml index 7f5b893d5e0..989f9adf23b 100644 --- a/crates/celox-test-suite/Cargo.toml +++ b/crates/celox-test-suite/Cargo.toml @@ -12,6 +12,8 @@ readme = "README.md" [features] default = [] +# Load the corpus from disk so editing a case does not rebuild Rust runners. +runtime-cases = [] # Emit the Veryl cases to SystemVerilog. emit = ["dep:veryl-analyzer", "dep:veryl-emitter", "dep:veryl-parser", "dep:veryl-metadata"] # The external-simulator runners shared by both suites. Port shapes of the @@ -62,5 +64,8 @@ veryl-std.workspace = true serde_json = { workspace = true, optional = true } sha2 = { version = "0.11", optional = true } +[dev-dependencies] +tempfile.workspace = true + [lints] workspace = true diff --git a/crates/celox-test-suite/build.rs b/crates/celox-test-suite/build.rs index 6ac733d981f..3d94cad2b64 100644 --- a/crates/celox-test-suite/build.rs +++ b/crates/celox-test-suite/build.rs @@ -1,7 +1,10 @@ // Fingerprint the compiled verifier independently of the embedded case corpus. // Hashing the executable itself would invalidate every case after adding one. #[cfg(not(feature = "external"))] -fn main() {} +fn main() { + // Do not let Cargo's default package-wide scan track runtime-only cases. + println!("cargo:rerun-if-changed=build.rs"); +} #[cfg(feature = "external")] fn main() { diff --git a/crates/celox-test-suite/src/lib.rs b/crates/celox-test-suite/src/lib.rs index bd2186df8fb..186da9925d9 100644 --- a/crates/celox-test-suite/src/lib.rs +++ b/crates/celox-test-suite/src/lib.rs @@ -2,6 +2,8 @@ #![forbid(unsafe_code)] mod backend; +#[cfg(feature = "runtime-cases")] +mod runtime_cases; mod scalar; pub mod script; pub mod sv; diff --git a/crates/celox-test-suite/src/runtime_cases.rs b/crates/celox-test-suite/src/runtime_cases.rs new file mode 100644 index 00000000000..e619f52e2a1 --- /dev/null +++ b/crates/celox-test-suite/src/runtime_cases.rs @@ -0,0 +1,101 @@ +//! Runtime corpus loading for the development executor. + +use crate::{StdResolver, TestCase}; +use std::path::Path; + +#[allow( + clippy::disallowed_methods, + reason = "test corpus configuration boundary" +)] +pub(crate) fn load(language: &str, resolver: StdResolver) -> Vec<&'static TestCase> { + let root = std::env::var_os("CELOX_VTEST_ROOT") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("src")); + load_directory(&root.join(language).join("cases"), resolver) +} + +fn load_directory(directory: &Path, resolver: StdResolver) -> Vec<&'static TestCase> { + let mut paths = std::fs::read_dir(directory) + .unwrap_or_else(|error| panic!("read {}: {error}", directory.display())) + .map(|entry| entry.expect("read corpus entry").path()) + .filter(|path| { + path.extension() + .is_some_and(|extension| extension == "vtest") + }) + .collect::>(); + paths.sort(); + assert!( + !paths.is_empty(), + "no .vtest files in {}", + directory.display() + ); + let mut names = std::collections::BTreeSet::new(); + paths + .into_iter() + .flat_map(|path| { + let text = std::fs::read_to_string(&path) + .unwrap_or_else(|error| panic!("read {}: {error}", path.display())); + crate::load_group(&path.to_string_lossy(), &text, resolver) + }) + .inspect(|case| { + assert!( + names.insert(case.name), + "duplicate vtest case: {}", + case.name + ); + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn case(group: &str, source: &str) -> String { + format!( + "(group {group} (category operators)) (case t (source \"top.sv\" \"{source}\") (top Top))" + ) + } + + #[test] + fn discovers_files_in_order_and_reads_edited_sources() { + let directory = tempfile::tempdir().unwrap(); + std::fs::write(directory.path().join("b.vtest"), case("b", "before")).unwrap(); + std::fs::write(directory.path().join("a.vtest"), case("a", "a")).unwrap(); + std::fs::write(directory.path().join("ignored.txt"), "not a vtest").unwrap(); + let cases = load_directory(directory.path(), crate::no_std_library); + assert_eq!( + cases.iter().map(|case| case.name).collect::>(), + ["a::t", "b::t"] + ); + assert_eq!(cases[1].design().sources[0].text, "before"); + std::fs::write(directory.path().join("b.vtest"), case("b", "after")).unwrap(); + let cases = load_directory(directory.path(), crate::no_std_library); + assert_eq!(cases[1].design().sources[0].text, "after"); + } + + #[test] + #[should_panic(expected = "duplicate vtest case: a::t")] + fn duplicate_names_are_errors() { + let directory = tempfile::tempdir().unwrap(); + for file in ["a.vtest", "b.vtest"] { + std::fs::write(directory.path().join(file), case("a", "")).unwrap(); + } + load_directory(directory.path(), crate::no_std_library); + } + + #[test] + #[should_panic(expected = "no .vtest files")] + fn empty_corpus_is_an_error() { + let directory = tempfile::tempdir().unwrap(); + load_directory(directory.path(), crate::no_std_library); + } + + #[test] + #[should_panic(expected = "broken.vtest:")] + fn malformed_cases_report_the_file() { + let directory = tempfile::tempdir().unwrap(); + std::fs::write(directory.path().join("broken.vtest"), "(case").unwrap(); + load_directory(directory.path(), crate::no_std_library); + } +} diff --git a/crates/celox-test-suite/src/sv/mod.rs b/crates/celox-test-suite/src/sv/mod.rs index e2284608bf4..49b6e80302b 100644 --- a/crates/celox-test-suite/src/sv/mod.rs +++ b/crates/celox-test-suite/src/sv/mod.rs @@ -1,5 +1,6 @@ //! The SystemVerilog suite: cases whose designs are SystemVerilog source. +#[cfg(not(feature = "runtime-cases"))] mod cases; #[cfg(feature = "external")] @@ -7,12 +8,18 @@ pub mod verification; use crate::TestCase; -/// All cases in deterministic declaration order. A case's design is -/// SystemVerilog source; build it with your SystemVerilog frontend. +/// All cases in deterministic order (file-name order with `runtime-cases`, +/// otherwise catalogue declaration order). A case's design is SystemVerilog +/// source; build it with your SystemVerilog frontend. pub fn cases() -> impl Iterator { static CASES: std::sync::OnceLock> = std::sync::OnceLock::new(); CASES .get_or_init(|| { + #[cfg(feature = "runtime-cases")] + { + crate::runtime_cases::load("sv", crate::no_std_library) + } + #[cfg(not(feature = "runtime-cases"))] cases::GROUPS .iter() .flat_map(|group| crate::load_group(group.file, group.text, crate::no_std_library)) diff --git a/crates/celox-test-suite/src/veryl/mod.rs b/crates/celox-test-suite/src/veryl/mod.rs index e10decffab0..1b933014da7 100644 --- a/crates/celox-test-suite/src/veryl/mod.rs +++ b/crates/celox-test-suite/src/veryl/mod.rs @@ -1,5 +1,6 @@ //! The Veryl suite: cases whose designs are Veryl source. +#[cfg(not(feature = "runtime-cases"))] mod cases; #[cfg(feature = "emit")] @@ -69,12 +70,18 @@ fn std_source(path: &str) -> String { .unwrap_or_else(|err| panic!("failed to read {}: {err}", src.src.display())) } -/// All cases in deterministic declaration order. Filter by category or name in the +/// All cases in deterministic order (file-name order with `runtime-cases`, +/// otherwise catalogue declaration order). Filter by category or name in the /// host test runner; nothing is silently skipped by the suite itself. pub fn cases() -> impl Iterator { static CASES: std::sync::OnceLock> = std::sync::OnceLock::new(); CASES .get_or_init(|| { + #[cfg(feature = "runtime-cases")] + { + crate::runtime_cases::load("veryl", std_source) + } + #[cfg(not(feature = "runtime-cases"))] cases::GROUPS .iter() .flat_map(|group| crate::load_group(group.file, group.text, std_source)) diff --git a/crates/celox/Cargo.toml b/crates/celox/Cargo.toml index c854d2ed803..6ba5486a1b6 100644 --- a/crates/celox/Cargo.toml +++ b/crates/celox/Cargo.toml @@ -146,5 +146,9 @@ name = "frontend_binary" path = "examples/frontend_binary.rs" required-features = ["host-runtime"] +[[example]] +name = "vtest-exec" +required-features = ["host-runtime"] + [lints] workspace = true diff --git a/crates/celox/examples/vtest-exec.rs b/crates/celox/examples/vtest-exec.rs new file mode 100644 index 00000000000..66e69731bc6 --- /dev/null +++ b/crates/celox/examples/vtest-exec.rs @@ -0,0 +1,42 @@ +//! One case per process; libtest/nextest owns selection, ignores and scheduling. + +use clap::{Parser, ValueEnum}; + +#[path = "../tests/test_utils/suite.rs"] +mod suite; +#[path = "../tests/test_utils/veryl_sim.rs"] +mod veryl_sim; +#[path = "../tests/test_utils/veryl_sv.rs"] +mod veryl_sv; +#[path = "../tests/test_utils/vtest_exec.rs"] +mod vtest_exec; + +#[cfg(feature = "systemverilog")] +#[allow(dead_code)] +#[path = "../tests/frontends/systemverilog/suite.rs"] +mod sv_suite; + +#[derive(Clone, ValueEnum)] +enum Language { + Veryl, + #[cfg(feature = "systemverilog")] + Sv, +} + +#[derive(Parser)] +#[command(about = "Execute a runtime vtest case using the shared test adapters")] +struct Args { + #[arg(value_enum)] + language: Language, + case: String, + backend: String, +} + +fn main() { + let args = Args::parse(); + match args.language { + Language::Veryl => suite::run_case(&args.case, &args.backend), + #[cfg(feature = "systemverilog")] + Language::Sv => sv_suite::run_case(&args.case, &args.backend), + } +} diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index d3f41052704..f10ac99fc15 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -363,7 +363,10 @@ fn build(design: &Design, backend: &str) -> Result> { /// Run the suite case `name` on `backend`. The SV frontend is recursive, so /// the case runs on a thread with room on its stack. -pub fn run_case(name: &'static str, backend: &'static str) { +pub fn run_case(name: &str, backend: &str) { + if super::vtest_exec::dispatch("sv", name, backend) { + return; + } std::thread::scope(|scope| { std::thread::Builder::new() .stack_size(8 * 1024 * 1024) diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 52af4da8702..e0331b436d1 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -3,6 +3,9 @@ use std::path::Path; use celox::Simulator; use num_bigint::BigUint; +#[path = "test_utils/vtest_exec.rs"] +mod vtest_exec; + // Each entry is either a suite case, `@case "group::name";`, or a test written // against the Celox API with `@setup` and `@build`. Either runs on every backend. macro_rules! sv_backends { diff --git a/crates/celox/tests/test_utils/mod.rs b/crates/celox/tests/test_utils/mod.rs index dda3390ee2d..141a34687f5 100644 --- a/crates/celox/tests/test_utils/mod.rs +++ b/crates/celox/tests/test_utils/mod.rs @@ -1,6 +1,7 @@ pub mod suite; pub mod veryl_sim; pub mod veryl_sv; +pub mod vtest_exec; #[path = "../fixtures/veryl_std.rs"] #[allow(dead_code)] diff --git a/crates/celox/tests/test_utils/suite.rs b/crates/celox/tests/test_utils/suite.rs index 95aa93d426c..a152d50d399 100644 --- a/crates/celox/tests/test_utils/suite.rs +++ b/crates/celox/tests/test_utils/suite.rs @@ -221,6 +221,9 @@ fn build_sv(design: &Design, sources: &[(&str, &std::path::Path)]) -> Result bool { + let Some(executable) = std::env::var_os("CELOX_VTEST_RUNNER") else { + return false; + }; + let status = std::process::Command::new(&executable) + .args([language, name, backend]) + // The executor shares these adapters. Do not dispatch recursively. + .env_remove("CELOX_VTEST_RUNNER") + .status() + .unwrap_or_else(|error| panic!("start vtest executor {executable:?}: {error}")); + assert!( + status.success(), + "vtest {language}/{name}/{backend}: {status}" + ); + true +} diff --git a/scripts/run-vtest.mjs b/scripts/run-vtest.mjs new file mode 100644 index 00000000000..dd656fa444b --- /dev/null +++ b/scripts/run-vtest.mjs @@ -0,0 +1,55 @@ +import { spawnSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { resolve } from "node:path"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const features = "systemverilog,celox-test-suite/runtime-cases"; + +export function executorPath(output) { + const paths = output.split("\n").filter(Boolean).map((line) => JSON.parse(line)) + .filter((message) => message.reason === "compiler-artifact" + && message.target.name === "vtest-exec" + && message.target.kind.includes("example") && message.executable) + .map((message) => message.executable); + if (paths.length !== 1) throw new Error("Cargo did not report one vtest executor"); + return paths[0]; +} + +// Keep the registrations in libtest: nextest still owns filters, ignores, +// process isolation, timeouts and parallel scheduling, including Rust API tests. +export function run(args, spawn = spawnSync, env = process.env) { + const build = spawn("cargo", [ + "build", "--locked", "-p", "celox", "--example", "vtest-exec", + "--profile", "vtest", "--features", features, "--message-format=json-render-diagnostics", + ], { cwd: root, env, encoding: "utf8", stdio: ["inherit", "pipe", "inherit"], maxBuffer: 64 * 1024 * 1024 }); + if (build.error) throw build.error; + if (build.status !== 0) return build.status ?? 1; + const executable = executorPath(build.stdout); + const tests = spawn("cargo", [ + "nextest", "run", "--locked", "-p", "celox", "--features", features, ...args, + ], { + cwd: root, + env: { ...env, CELOX_VTEST_RUNNER: executable, CELOX_VTEST_ROOT: resolve(root, "crates/celox-test-suite/src") }, + stdio: "inherit", + }); + if (tests.error) throw tests.error; + return tests.status ?? 1; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + if (process.argv.includes("--help")) { + console.log(`Usage: node scripts/run-vtest.mjs [cargo nextest run options] + +Build the shared vtest executor with opt-level=1, then run Celox tests through +nextest. Case bodies are read from disk; Rust API tests run in their test binary. +Examples: + node scripts/run-vtest.mjs --test counter + node scripts/run-vtest.mjs --test operators -E 'test(::native$)' + node scripts/run-vtest.mjs --test systemverilog -E 'test(operators::)' + +The runner and registrations both enable systemverilog and runtime-cases. +Use ordinary cargo nextest run for the existing in-process test path.`); + } else { + process.exitCode = run(process.argv.slice(2)); + } +} diff --git a/scripts/run-vtest.test.mjs b/scripts/run-vtest.test.mjs new file mode 100644 index 00000000000..96c0e511018 --- /dev/null +++ b/scripts/run-vtest.test.mjs @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { executorPath, run } from "./run-vtest.mjs"; + +const artifact = JSON.stringify({ + reason: "compiler-artifact", target: { name: "vtest-exec", kind: ["example"] }, + executable: "/managed target/vtest/examples/vtest-exec", +}); + +test("builds the optimized executor and preserves nextest selection and environment", () => { + const calls = []; + const status = run(["--test", "counter", "-E", "test(::native$)", "--run-ignored", "all"], + (...call) => { + calls.push(call); + return calls.length === 1 ? { status: 0, stdout: `${artifact}\n` } : { status: 7 }; + }, { PATH: "/tools", CELOX_VTEST_ROOT: "/stale", CELOX_VTEST_RUNNER: "/stale" }); + assert.equal(status, 7); + assert.equal(calls.length, 2); + const [[, build, options], [, tests, testOptions]] = calls; + assert.equal(build[build.indexOf("--profile") + 1], "vtest"); + assert.equal(build[build.indexOf("--features") + 1], tests[tests.indexOf("--features") + 1]); + assert.deepEqual(tests.slice(-6), ["--test", "counter", "-E", "test(::native$)", "--run-ignored", "all"]); + assert.equal(testOptions.cwd, options.cwd); + assert.equal(testOptions.env.PATH, "/tools"); + assert.equal(testOptions.env.CELOX_VTEST_RUNNER, "/managed target/vtest/examples/vtest-exec"); + assert.ok(testOptions.env.CELOX_VTEST_ROOT.endsWith("/crates/celox-test-suite/src")); +}); + +test("failed or interrupted builds never launch tests", () => { + for (const status of [1, null]) { + let calls = 0; + assert.equal(run([], () => { calls++; return { status }; }), 1); + assert.equal(calls, 1); + } + assert.throws(() => run([], () => ({ error: new Error("no cargo") })), /no cargo/); +}); + +test("missing or ambiguous executors fail closed", () => { + assert.throws(() => executorPath('{"reason":"build-finished"}\n'), /one vtest executor/); + assert.throws(() => executorPath(`${artifact}\n${artifact}`), /one vtest executor/); + assert.equal(executorPath(`{"reason":"build-finished"}\n${artifact}\n`), "/managed target/vtest/examples/vtest-exec"); +}); From 3530b564efa13514556d7e34a19a59f8f1b4da63 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 16:36:48 +0900 Subject: [PATCH 2/3] ci(vtest): use the optimized executor for Rust test jobs Prepare the shared executor once for full and scoped Celox runs, fail when setup is missing, and warm both Cargo profiles under a matching cache key. Change-Id: I3bc134b06e3bf4fce8f1ed2e8a36ce7e0a6f629b --- .github/workflows/ci.yml | 7 +++++- .github/workflows/rust-cache.yml | 8 +++++- CONTRIBUTING.md | 5 +++- scripts/ci-workflow.test.mjs | 25 +++++++++++++++++-- scripts/run-ci-rust-scope.mjs | 9 ++++++- scripts/run-ci-rust-scope.test.mjs | 20 +++++++++++++++ scripts/run-vtest.mjs | 39 +++++++++++++++++++++++++----- scripts/run-vtest.test.mjs | 30 ++++++++++++++++++++++- 8 files changed, 130 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9b1fde462a1..7240c48d8ff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -220,6 +220,7 @@ jobs: - uses: Swatinem/rust-cache@v2 with: + key: vtest-v1 save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} - uses: actions/setup-python@v7 @@ -236,6 +237,10 @@ jobs: with: tool: cargo-nextest@0.9.144 + - name: Build the optimized vtest executor + if: needs.changes.outputs.rust_full != 'false' || contains(format(' {0} ', needs.changes.outputs.rust_packages), ' celox ') + run: node scripts/run-vtest.mjs --prepare-ci + # Enable the frontend and suite features together so common integration # tests run once, rather than once per Cargo feature combination. # nextest schedules tests from all binaries on one pool; `cargo test` @@ -247,7 +252,7 @@ jobs: if: needs.changes.outputs.rust_full != 'false' run: >- cargo nextest run --locked --workspace --exclude 'lydite*' --profile ci - --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus + --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/runtime-cases - name: Run the tests this pull request can affect if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_packages != '' diff --git a/.github/workflows/rust-cache.yml b/.github/workflows/rust-cache.yml index a5d8b9f0de3..b7113223635 100644 --- a/.github/workflows/rust-cache.yml +++ b/.github/workflows/rust-cache.yml @@ -13,6 +13,7 @@ on: - ".github/actions/setup-rust/**" - ".github/workflows/rust-cache.yml" - ".github/workflows/ci.yml" + - "scripts/run-vtest.mjs" workflow_dispatch: permissions: @@ -39,14 +40,19 @@ jobs: - uses: ./.github/actions/setup-rust - uses: Swatinem/rust-cache@v2 id: cache + with: + key: vtest-v1 - name: Install cargo-nextest if: steps.cache.outputs.cache-hit != 'true' uses: taiki-e/install-action@v2 with: tool: cargo-nextest@0.9.144 + - name: Build the optimized vtest executor to populate dependencies + if: steps.cache.outputs.cache-hit != 'true' + run: node scripts/run-vtest.mjs --prepare-ci - name: Build test targets to populate dependencies if: steps.cache.outputs.cache-hit != 'true' run: >- cargo nextest list --locked --workspace --message-format json - --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus + --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/runtime-cases > /dev/null diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2a4e01a30a6..4266b5a98ee 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -61,7 +61,10 @@ Rust binaries, so edits to an existing case do not require recompilation. Adding a test registration or changing Rust still requires a build. The first run builds both the optimized executor and ordinary test binaries; the executor profile has its own Cargo cache. Ordinary Cargo test commands retain the embedded, in-process -path, and CI continues to use that path. +path. CI's Rust Tests job prepares the executor once and uses it for both full +workspace runs and scoped runs that include Celox. Scopes without Celox skip that +build. The default-branch cache warmer builds both executor and test dependencies +under the same cache key; vtest preparation failures fail the test job. For debugging a single case after building, the executor also accepts ` ` directly, for example: diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 45069ab5bf4..4371d744539 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -381,6 +381,12 @@ test("cache warming shares the Rust Tests key and builds without running tests", /pull_request:|cargo nextest run|cargo test|shared-key:/, ); assert.match(warm, /steps.cache.outputs.cache-hit != 'true'/); + for (const text of [warm, job("rust-tests")]) { + assert.match(text, /key: vtest-v1/); + assert.match(text, /run: node scripts\/run-vtest.mjs --prepare-ci/); + } + assert.match(warm, /name: Build the optimized vtest executor to populate dependencies\n if: steps.cache.outputs.cache-hit != 'true'/); + assert.match(warm, /"scripts\/run-vtest.mjs"/); assert.match( warm, /cargo nextest list --locked --workspace --message-format json/, @@ -408,7 +414,7 @@ function cargoArguments(jobName, stepName, env) { features: (env.FEATURES ?? "").split(",").filter(Boolean), }]); const result = spawnSync("bash", ["-e", "-c", script], { - env: { ...process.env, ...env, BUILDS: builds, PATH: `${directory}:${process.env.PATH}` }, encoding: "utf8", + env: { ...process.env, CELOX_VTEST_RUNNER: "/ci/vtest-exec", ...env, BUILDS: builds, PATH: `${directory}:${process.env.PATH}` }, encoding: "utf8", }); assert.ifError(result.error); assert.equal(result.status, 0, result.stderr); @@ -425,7 +431,7 @@ test("scoped Cargo commands build only the selected integration targets", () => }; assert.deepEqual(cargoArguments("rust-tests", "Run the tests this pull request can affect", env), [ "nextest", "run", "--locked", "--profile", "ci", "--no-tests=pass", - "-p", "celox", "--features", "celox/systemverilog", + "-p", "celox", "--features", "celox/systemverilog,celox-test-suite/runtime-cases", "--test", "flip_flop", "--test", "systemverilog", "-E", env.FILTER, ]); assert.deepEqual(cargoArguments("lint", "Lint the crates this pull request can affect", env), [ @@ -440,6 +446,21 @@ test("scoped Cargo commands build only the selected integration targets", () => }), ["doc", "--locked", "--no-deps", "-p", "celox-runtime", "-p", "celox"]); }); +test("CI prepares one executor for full runs and scopes containing Celox", () => { + const rust = job("rust-tests"); + const step = rust.split(" - name: Build the optimized vtest executor\n")[1] + .split("\n #")[0]; + assert.match(step, /if: needs.changes.outputs.rust_full != 'false' \|\| contains\(format\(' \{0\} ', needs.changes.outputs.rust_packages\), ' celox '\)/); + assert.match(step, /run: node scripts\/run-vtest.mjs --prepare-ci/); + assert.ok(rust.indexOf("Build the optimized vtest executor") < rust.indexOf("Run workspace tests")); + assert.match(rust, /cargo nextest run[^\n]*\n[^\n]*celox-test-suite\/runtime-cases/); + assert.deepEqual(cargoArguments("rust-tests", "Run the tests this pull request can affect", { + PACKAGES: "celox-heap", FEATURES: "", TARGETS: "", FILTER: "package(celox-heap)", + CELOX_VTEST_RUNNER: "", + }), ["nextest", "run", "--locked", "--profile", "ci", "--no-tests=pass", + "-p", "celox-heap", "-E", "package(celox-heap)"]); +}); + test("scoped checks preserve full-run fallbacks and use their own package scopes", () => { const lint = job("lint"); assert.match(lint, /name: cargo clippy\n if: .*outputs\.rust_full != 'false'/); diff --git a/scripts/run-ci-rust-scope.mjs b/scripts/run-ci-rust-scope.mjs index 1904120f991..b604ee32a0f 100644 --- a/scripts/run-ci-rust-scope.mjs +++ b/scripts/run-ci-rust-scope.mjs @@ -1,5 +1,6 @@ import { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; +import { runtimeCasesFeature } from "./run-vtest.mjs"; // Keep target flags local to their packages. Cargo applies --test to every -p. export function cargoCommands(mode, builds, filter) { @@ -17,7 +18,9 @@ export function cargoCommands(mode, builds, filter) { ? ["nextest", "run", "--locked", "--profile", "ci", "--no-tests=pass"] : ["clippy", "--locked"]; for (const name of packages) args.push("-p", name); - if (features.length) args.push("--features", features.join(",")); + const enabled = mode === "test" && packages.includes("celox") + ? [...new Set([...features, runtimeCasesFeature])] : features; + if (enabled.length) args.push("--features", enabled.join(",")); for (const target of targets) args.push("--test", target); if (mode === "lint") { if (!targets.length) args.push("--all-targets"); @@ -31,6 +34,10 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) for (const args of cargoCommands( process.argv[2], JSON.parse(process.env.BUILDS), process.env.FILTER, )) { + if (process.argv[2] === "test" + && args.some((arg, index) => arg === "celox" && args[index - 1] === "-p") + && !process.env.CELOX_VTEST_RUNNER) + throw new Error("Celox CI tests require the prepared vtest executor"); console.log("cargo", ...args); const result = spawnSync("cargo", args, { stdio: "inherit" }); if (result.error) throw result.error; diff --git a/scripts/run-ci-rust-scope.test.mjs b/scripts/run-ci-rust-scope.test.mjs index 7d83ce37198..0058198d5cf 100644 --- a/scripts/run-ci-rust-scope.test.mjs +++ b/scripts/run-ci-rust-scope.test.mjs @@ -35,6 +35,26 @@ test("empty or invalid plans cannot silently pass CI", () => { assert.throws(() => cargoCommands("test", builds, "")); }); +test("runtime loading is enabled only for Celox test builds, without changing scope", () => { + const original = structuredClone(builds); + const tests = cargoCommands("test", builds, filter); + const lint = cargoCommands("lint", builds, filter); + assert.equal(tests[0][tests[0].indexOf("--features") + 1], "celox-test-suite/icarus"); + assert.equal(tests[1][tests[1].indexOf("--features") + 1], + "celox/systemverilog,celox-test-suite/runtime-cases"); + assert.equal(lint[1][lint[1].indexOf("--features") + 1], "celox/systemverilog"); + assert.deepEqual(builds, original); +}); + +test("Celox CI tests reject missing executor setup before launching Cargo", () => { + const result = spawnSync(process.execPath, ["scripts/run-ci-rust-scope.mjs", "test"], { + env: { ...process.env, BUILDS: JSON.stringify([builds[1]]), FILTER: filter, + CELOX_VTEST_RUNNER: "" }, encoding: "utf8", + }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /require the prepared vtest executor/); +}); + test("the runner stops and propagates a failed scoped Cargo invocation", () => { const directory = mkdtempSync(join(tmpdir(), "celox-cargo-failure-")); try { diff --git a/scripts/run-vtest.mjs b/scripts/run-vtest.mjs index dd656fa444b..c16a4ae606c 100644 --- a/scripts/run-vtest.mjs +++ b/scripts/run-vtest.mjs @@ -1,9 +1,11 @@ import { spawnSync } from "node:child_process"; import { fileURLToPath, pathToFileURL } from "node:url"; import { resolve } from "node:path"; +import { appendFileSync } from "node:fs"; const root = fileURLToPath(new URL("../", import.meta.url)); -const features = "systemverilog,celox-test-suite/runtime-cases"; +export const runtimeCasesFeature = "celox-test-suite/runtime-cases"; +const features = `celox/systemverilog,${runtimeCasesFeature}`; export function executorPath(output) { const paths = output.split("\n").filter(Boolean).map((line) => JSON.parse(line)) @@ -15,21 +17,43 @@ export function executorPath(output) { return paths[0]; } -// Keep the registrations in libtest: nextest still owns filters, ignores, -// process isolation, timeouts and parallel scheduling, including Rust API tests. -export function run(args, spawn = spawnSync, env = process.env) { +export function buildExecutor(spawn = spawnSync, env = process.env) { const build = spawn("cargo", [ "build", "--locked", "-p", "celox", "--example", "vtest-exec", "--profile", "vtest", "--features", features, "--message-format=json-render-diagnostics", ], { cwd: root, env, encoding: "utf8", stdio: ["inherit", "pipe", "inherit"], maxBuffer: 64 * 1024 * 1024 }); if (build.error) throw build.error; - if (build.status !== 0) return build.status ?? 1; + if (build.status !== 0) return { status: build.status ?? 1 }; const executable = executorPath(build.stdout); + return { + status: 0, + environment: { CELOX_VTEST_RUNNER: executable, CELOX_VTEST_ROOT: resolve(root, "crates/celox-test-suite/src") }, + }; +} + +// Prepare once per CI job, even when scoped tests need several Cargo invocations. +export function prepareCi(spawn = spawnSync, env = process.env, append = appendFileSync) { + if (!env.GITHUB_ENV) throw new Error("--prepare-ci requires GITHUB_ENV"); + const result = buildExecutor(spawn, env); + if (result.status !== 0) return result.status; + const lines = Object.entries(result.environment).map(([name, value]) => { + if (/[\r\n]/.test(value)) throw new Error("Invalid executor environment path"); + return `${name}=${value}\n`; + }); + append(env.GITHUB_ENV, lines.join("")); + return 0; +} + +// Keep the registrations in libtest: nextest still owns filters, ignores, +// process isolation, timeouts and parallel scheduling, including Rust API tests. +export function run(args, spawn = spawnSync, env = process.env) { + const result = buildExecutor(spawn, env); + if (result.status !== 0) return result.status; const tests = spawn("cargo", [ "nextest", "run", "--locked", "-p", "celox", "--features", features, ...args, ], { cwd: root, - env: { ...env, CELOX_VTEST_RUNNER: executable, CELOX_VTEST_ROOT: resolve(root, "crates/celox-test-suite/src") }, + env: { ...env, ...result.environment }, stdio: "inherit", }); if (tests.error) throw tests.error; @@ -49,6 +73,9 @@ Examples: The runner and registrations both enable systemverilog and runtime-cases. Use ordinary cargo nextest run for the existing in-process test path.`); + } else if (process.argv[2] === "--prepare-ci") { + if (process.argv.length !== 3) throw new Error("--prepare-ci accepts no test arguments"); + process.exitCode = prepareCi(); } else { process.exitCode = run(process.argv.slice(2)); } diff --git a/scripts/run-vtest.test.mjs b/scripts/run-vtest.test.mjs index 96c0e511018..1bec1f1a200 100644 --- a/scripts/run-vtest.test.mjs +++ b/scripts/run-vtest.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { executorPath, run } from "./run-vtest.mjs"; +import { executorPath, prepareCi, run } from "./run-vtest.mjs"; const artifact = JSON.stringify({ reason: "compiler-artifact", target: { name: "vtest-exec", kind: ["example"] }, @@ -40,3 +40,31 @@ test("missing or ambiguous executors fail closed", () => { assert.throws(() => executorPath(`${artifact}\n${artifact}`), /one vtest executor/); assert.equal(executorPath(`{"reason":"build-finished"}\n${artifact}\n`), "/managed target/vtest/examples/vtest-exec"); }); + +test("CI preparation only builds and exports the executor for later test steps", () => { + const calls = []; + const writes = []; + assert.equal(prepareCi((...args) => { + calls.push(args); + return { status: 0, stdout: artifact }; + }, { GITHUB_ENV: "/job/environment" }, (...args) => writes.push(args)), 0); + assert.equal(calls.length, 1); + assert.equal(calls[0][1][0], "build"); + assert.ok(calls[0][1].includes("vtest")); + assert.equal(writes.length, 1); + assert.equal(writes[0][0], "/job/environment"); + assert.match(writes[0][1], /^CELOX_VTEST_RUNNER=\/managed target\/vtest\/examples\/vtest-exec\n/); + assert.match(writes[0][1], /\nCELOX_VTEST_ROOT=.*\/crates\/celox-test-suite\/src\n$/); +}); + +test("failed CI preparation cannot export a stale executor or silently skip setup", () => { + const unexpected = () => assert.fail("unexpected build or environment export"); + assert.throws(() => prepareCi(unexpected, {}, unexpected), /requires GITHUB_ENV/); + assert.equal(prepareCi(() => ({ status: 17 }), { GITHUB_ENV: "/job/env" }, unexpected), 17); + assert.throws(() => prepareCi(() => ({ status: 0, stdout: "" }), + { GITHUB_ENV: "/job/env" }, unexpected), /one vtest executor/); + const message = JSON.parse(artifact); + message.executable += "\nUNRELATED=value"; + assert.throws(() => prepareCi(() => ({ status: 0, stdout: JSON.stringify(message) }), + { GITHUB_ENV: "/job/env" }, unexpected), /Invalid executor environment/); +}); From ce7e0151953955a71c6662c82bbfac895c39750a Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 17:59:13 +0900 Subject: [PATCH 3/3] ci: report Rust test results to Mergify CI Insights Change-Id: I28a4e411f6de79c7e30511682cd78111ff7f9490 --- .config/nextest.toml | 4 +++ .github/workflows/ci.yml | 29 ++++++++++++++++++ CONTRIBUTING.md | 9 ++++++ scripts/ci-rust-reports.mjs | 40 +++++++++++++++++++++++++ scripts/ci-rust-reports.test.mjs | 51 ++++++++++++++++++++++++++++++++ scripts/ci-workflow.test.mjs | 26 ++++++++++++++-- scripts/run-ci-rust-scope.mjs | 5 ++++ 7 files changed, 162 insertions(+), 2 deletions(-) create mode 100644 scripts/ci-rust-reports.mjs create mode 100644 scripts/ci-rust-reports.test.mjs diff --git a/.config/nextest.toml b/.config/nextest.toml index 7251480628b..fa2e9835b73 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -11,6 +11,10 @@ fail-fast = false slow-timeout = { period = "60s", terminate-after = 10 } failure-output = "immediate-final" +[profile.ci.junit] +path = "junit.xml" +store-success-output = false + [[profile.ci.overrides]] # Deep per-bit graphs consume substantial compiler memory and CPU. Reserve the # pool so these regressions retain the same timeout without competing builds. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7240c48d8ff..a77cd3fe13a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -211,6 +211,9 @@ jobs: needs: changes if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') }} runs-on: ubuntu-latest + env: + CELOX_CI_REPORT_DIR: work/ci-reports/rust + HAS_MERGIFY_TOKEN: ${{ secrets.MERGIFY_TOKEN != '' }} steps: - uses: actions/checkout@v7 with: @@ -223,6 +226,9 @@ jobs: key: vtest-v1 save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} + - name: Initialize Rust test reports + run: node scripts/ci-rust-reports.mjs reset + - uses: actions/setup-python@v7 if: needs.changes.outputs.rust_vpi_e2e != 'false' with: @@ -249,12 +255,14 @@ jobs: # (scripts/ci-rust-scope.mjs); merge groups and the daily run keep the # Celox workspace. lydite-checks.yml owns Lydite tests at its own cadence. - name: Run workspace tests with CI features + id: workspace-tests if: needs.changes.outputs.rust_full != 'false' run: >- cargo nextest run --locked --workspace --exclude 'lydite*' --profile ci --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/runtime-cases - name: Run the tests this pull request can affect + id: scoped-tests if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_packages != '' env: BUILDS: ${{ needs.changes.outputs.rust_builds }} @@ -262,6 +270,27 @@ jobs: run: | node scripts/run-ci-rust-scope.mjs test + - name: Collect Rust test reports + if: success() || failure() + run: node scripts/ci-rust-reports.mjs collect + + - name: Retain Rust test reports + if: (success() || failure()) && hashFiles('work/ci-reports/rust/*.xml') != '' + uses: actions/upload-artifact@v7 + with: + name: rust-test-results + path: work/ci-reports/rust/*.xml + retention-days: 14 + + - name: Upload Rust test results to Mergify + if: (success() || failure()) && env.HAS_MERGIFY_TOKEN == 'true' && hashFiles('work/ci-reports/rust/*.xml') != '' + uses: mergifyio/gha-mergify-ci@392d123d84a27960993927aec1f2cbb059fb95c1 # v27 + with: + token: ${{ secrets.MERGIFY_TOKEN }} + report_path: work/ci-reports/rust/*.xml + job_name: rust-tests + test_step_outcome: ${{ steps.workspace-tests.outcome != 'skipped' && steps.workspace-tests.outcome || steps.scoped-tests.outcome }} + # nextest does not run documentation tests. - name: Run workspace documentation tests with CI features if: needs.changes.outputs.rust_full != 'false' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4266b5a98ee..1d2fa52bdfd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -66,6 +66,15 @@ workspace runs and scoped runs that include Celox. Scopes without Celox skip tha build. The default-branch cache warmer builds both executor and test dependencies under the same cache key; vtest preparation failures fail the test job. +The CI nextest profile also emits JUnit results. The Rust Tests job preserves +each scoped invocation separately under `work/ci-reports/rust/`, retains the XML +as the `rust-test-results` artifact for 14 days, and uploads it to Mergify CI +Insights when the repository's `MERGIFY_TOKEN` secret is available. The secret +must be a Mergify application key with `ci` scope, and CI Insights must be enabled +for the repository. Tests keep their normal failure status; reporting does not +enable retries or quarantine. Forks without the secret still run tests and retain +the artifact. `cargo test`/doctest invocations are not part of this nextest report. + For debugging a single case after building, the executor also accepts ` ` directly, for example: diff --git a/scripts/ci-rust-reports.mjs b/scripts/ci-rust-reports.mjs new file mode 100644 index 00000000000..ddfb851c8ee --- /dev/null +++ b/scripts/ci-rust-reports.mjs @@ -0,0 +1,40 @@ +import { copyFileSync, existsSync, mkdirSync, readdirSync, rmSync } from "node:fs"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; + +function currentReport(root) { + return resolve(root, "target/nextest/ci/junit.xml"); +} + +// Only remove nextest's report; never create target/ before Cargo/mbx runs. +export function clearCurrentReport(source = currentReport(process.cwd())) { + rmSync(source, { force: true }); +} + +export function resetReports(directory, source = currentReport(process.cwd())) { + clearCurrentReport(source); + if (!existsSync(directory)) return; + for (const name of readdirSync(directory)) { + if (/^nextest-(?:full|\d+)\.xml$/.test(name)) rmSync(resolve(directory, name)); + } +} + +export function saveCurrentReport(directory, name, source = currentReport(process.cwd())) { + if (!/^(?:full|\d+)$/.test(name)) throw new Error("Invalid Rust report name"); + // A build failure or an empty selection may produce no report. Keep the + // Cargo exit status and any earlier reports; never reuse a previous result. + if (!existsSync(source)) return; + mkdirSync(directory, { recursive: true }); + const destination = resolve(directory, `nextest-${name}.xml`); + copyFileSync(source, destination); + rmSync(source); + return destination; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const directory = process.env.CELOX_CI_REPORT_DIR; + if (!directory) throw new Error("CELOX_CI_REPORT_DIR is required"); + if (process.argv[2] === "reset") resetReports(directory); + else if (process.argv[2] === "collect") saveCurrentReport(directory, "full"); + else throw new Error("Expected reset or collect"); +} diff --git a/scripts/ci-rust-reports.test.mjs b/scripts/ci-rust-reports.test.mjs new file mode 100644 index 00000000000..e0ef8709eef --- /dev/null +++ b/scripts/ci-rust-reports.test.mjs @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import test from "node:test"; +import { clearCurrentReport, resetReports, saveCurrentReport } from "./ci-rust-reports.mjs"; + +function fixture(t) { + const root = mkdtempSync(join(tmpdir(), "celox-ci-reports-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + return { source: join(root, "junit.xml"), directory: join(root, "reports") }; +} + +test("each scoped run keeps its own report, including failures", (t) => { + const { source, directory } = fixture(t); + const passed = ''; + const failed = ''; + for (const [name, text] of [["0", passed], ["1", failed]]) { + writeFileSync(source, text); + const saved = saveCurrentReport(directory, name, source); + assert.equal(readFileSync(saved, "utf8"), text); + assert.ok(!existsSync(source)); + } + assert.deepEqual(readdirSync(directory).sort(), ["nextest-0.xml", "nextest-1.xml"]); + assert.equal(readFileSync(join(directory, "nextest-0.xml"), "utf8"), passed); + // A subsequent compilation failure must not relabel an earlier report. + clearCurrentReport(source); + assert.equal(saveCurrentReport(directory, "2", source), undefined); + assert.equal(readdirSync(directory).length, 2); +}); + +test("initialization removes only this job's stale reports and creates no target directory", (t) => { + const { source, directory } = fixture(t); + resetReports(directory, source); + assert.ok(!existsSync(directory)); + mkdirSync(directory); + for (const name of ["nextest-full.xml", "nextest-0.xml", "unrelated.xml"]) + writeFileSync(join(directory, name), "old"); + writeFileSync(source, "old"); + resetReports(directory, source); + assert.deepEqual(readdirSync(directory), ["unrelated.xml"]); + assert.ok(!existsSync(source)); +}); + +test("full runs use a stable report name and reject invalid paths", (t) => { + const { source, directory } = fixture(t); + writeFileSync(source, ""); + assert.throws(() => saveCurrentReport(directory, "../escape", source), /Invalid Rust report name/); + assert.ok(existsSync(source)); + assert.equal(saveCurrentReport(directory, "full", source), join(directory, "nextest-full.xml")); +}); diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 4371d744539..ed9ff3e9e7c 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -248,11 +248,11 @@ test("queue CI retains the whole workspace and ordinary PRs use scoped tests", ( // Anything but an explicit scope, including a failed detection, runs all. assert.match( rust, - /name: Run workspace tests with CI features\n if: needs\.changes\.outputs\.rust_full != 'false'\n/, + /name: Run workspace tests with CI features\n id: workspace-tests\n if: needs\.changes\.outputs\.rust_full != 'false'\n/, ); assert.match( rust, - /name: Run the tests this pull request can affect\n if: needs\.changes\.outputs\.rust_full == 'false' && /, + /name: Run the tests this pull request can affect\n id: scoped-tests\n if: needs\.changes\.outputs\.rust_full == 'false' && /, ); assert.match( job("changes"), @@ -461,6 +461,28 @@ test("CI prepares one executor for full runs and scopes containing Celox", () => "-p", "celox-heap", "-E", "package(celox-heap)"]); }); +test("CI reports each Rust run to Mergify without weakening test failures", () => { + const rust = job("rust-tests"); + assert.match(rust, /CELOX_CI_REPORT_DIR: work\/ci-reports\/rust/); + assert.match(rust, /HAS_MERGIFY_TOKEN: \$\{\{ secrets.MERGIFY_TOKEN != '' \}\}/); + assert.match(rust, /run: node scripts\/ci-rust-reports.mjs reset/); + assert.match(rust, /name: Collect Rust test reports\n if: success\(\) \|\| failure\(\)/); + assert.match(rust, /run: node scripts\/ci-rust-reports.mjs collect/); + assert.match(rust, /name: Run workspace tests with CI features\n id: workspace-tests/); + assert.match(rust, /name: Run the tests this pull request can affect\n id: scoped-tests/); + assert.doesNotMatch(rust, /continue-on-error/); + const upload = rust.split(" - name: Upload Rust test results to Mergify\n")[1] + .split("\n #")[0]; + assert.match(upload, /if: \(success\(\) \|\| failure\(\)\) && env.HAS_MERGIFY_TOKEN == 'true' && hashFiles\('work\/ci-reports\/rust\/\*.xml'\) != ''/); + assert.match(upload, /uses: mergifyio\/gha-mergify-ci@[0-9a-f]{40} # v27/); + assert.match(upload, /report_path: work\/ci-reports\/rust\/\*.xml/); + assert.match(upload, /job_name: rust-tests/); + assert.match(upload, /test_step_outcome: .*steps.workspace-tests.outcome.*steps.scoped-tests.outcome/); + assert.match(rust, /name: rust-test-results\n path: work\/ci-reports\/rust\/\*.xml\n retention-days: 14/); + const nextest = readFileSync(new URL("../.config/nextest.toml", import.meta.url), "utf8"); + assert.match(nextest, /\[profile.ci.junit\]\npath = "junit.xml"/); +}); + test("scoped checks preserve full-run fallbacks and use their own package scopes", () => { const lint = job("lint"); assert.match(lint, /name: cargo clippy\n if: .*outputs\.rust_full != 'false'/); diff --git a/scripts/run-ci-rust-scope.mjs b/scripts/run-ci-rust-scope.mjs index b604ee32a0f..80850239528 100644 --- a/scripts/run-ci-rust-scope.mjs +++ b/scripts/run-ci-rust-scope.mjs @@ -1,6 +1,7 @@ import { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; import { runtimeCasesFeature } from "./run-vtest.mjs"; +import { clearCurrentReport, saveCurrentReport } from "./ci-rust-reports.mjs"; // Keep target flags local to their packages. Cargo applies --test to every -p. export function cargoCommands(mode, builds, filter) { @@ -31,6 +32,8 @@ export function cargoCommands(mode, builds, filter) { } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const reportDirectory = process.argv[2] === "test" && process.env.CELOX_CI_REPORT_DIR; + let reportIndex = 0; for (const args of cargoCommands( process.argv[2], JSON.parse(process.env.BUILDS), process.env.FILTER, )) { @@ -39,7 +42,9 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) && !process.env.CELOX_VTEST_RUNNER) throw new Error("Celox CI tests require the prepared vtest executor"); console.log("cargo", ...args); + if (reportDirectory) clearCurrentReport(); const result = spawnSync("cargo", args, { stdio: "inherit" }); + if (reportDirectory) saveCurrentReport(reportDirectory, String(reportIndex++)); if (result.error) throw result.error; if (result.status !== 0) process.exit(result.status ?? 1); }