Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,7 @@ cargo xtask web --serve # the same app in the br
cargo run --release -p lightcraft-cli -- render photo.jpg -o out.jpg --set light.exposure=0.5
cargo xtask ci # fmt, clippy, HEIF, tests, parity, layers, assets, WASM
cargo xtask ci --quick # only what your branch's changes can break (minutes)
cargo xtask test -p lightcraft-raw --keep-going # tests only, with ci's caps; runs every binary, names each that failed
```

`cargo xtask ci --quick` compares with the merge base of `origin/main` (`--base REF` for another)
Expand All @@ -427,6 +428,16 @@ unchanged. Explicit `CARGO_PROFILE_DEV_DEBUG`, `CARGO_BUILD_JOBS`, `RUST_TEST_TH
`cargo test`; `LIGHTCRAFT_NEXTEST=1` runs them under [cargo-nextest](https://nexte.st) instead (one
process per test, slower here because each regenerates the demo scenes). Ordinary development commands keep their own settings.

To run tests without the rest of `ci`, use `cargo xtask test` rather than `cargo test --workspace`,
which runs one test per CPU in every test binary (on a 16-core machine the UI tests alone run out of
memory) and takes no CI slot. It has `ci`'s caps and waits for its slot, builds every test target
once (the same build as `ci`'s, so neither rebuilds the other) and runs each test binary, or those
of the `-p PKG` packages, with whatever follows `--` (`cargo xtask test -p lightcraft-ui-egui --
i18n::`). It stops at the first failing binary; `--keep-going` runs them all and names each that
failed, as `ci`'s test step does. `--doc` adds the doctests; `LIGHTCRAFT_NEXTEST=1` applies here too, where
`--test-threads N` and `--nocapture` become nextest's own options and only filters, `--exact`,
`--skip`, `--ignored` and `--include-ignored` may follow `--`.

**Release builds on memory-constrained machines:** [#1196](https://github.com/storytold/lightcraft/issues/1196)
reports Arch/AUR release-link OOM kills on a 16 GB machine when the desktop and CLI build concurrently
with full debug information, thin LTO and one codegen unit. The CI defaults above do not apply to
Expand Down
9 changes: 9 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,14 @@ module per file (`cargo test -p <crate> --test it <module>::`); a test that chan
whole process (a global allocator, closing the GPU) keeps a binary of its own in `tests/`. The WASM
build is one `cargo check --target wasm32-unknown-unknown --keep-going` over the wasm-safe crates.

`ci`'s resource caps (build jobs by available RAM, at most 4 test threads, line-table debuginfo) and
its one-run-per-machine slot (`xtask/src/ci_lock.rs`) also cover `cargo xtask test [-p PKG]…
[--keep-going] [--doc] [-- ARGS]` (`xtask/src/test.rs`), the way to run the tests alone: subcommands
opt into the caps with `use_ci_caps`. It builds every workspace test target once, as `ci` does, and
runs each test binary, or the `-p` packages' binaries, itself (`test::run_binary`, which `ci --quick`
uses too); `--keep-going` runs every binary and names each that failed instead of stopping at the
first.

`ci` also probes the machine: OS, CPUs, RAM, the GPU adapters of each backend (from the ignored
`gpu_probe` test of `lightcraft-gpu`, run after the workspace tests so it reuses their build; xtask
has no wgpu), the corpus and `CRAFT_FONTS_DIR`. Tests
Expand All @@ -87,6 +95,7 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT

| Date | Change | Summary |
|---|---|---|
| 2026-10-26 | minor | Quality gates: `cargo xtask test` runs the tests with `ci`'s caps and slot, and can keep going past a failing binary |
| 2026-10-23 | minor | Quality gates: one integration-test binary per crate, doctests apart, nextest on request, one WASM check |
| 2026-10-11 | minor | Quality gates: the CI machine probe, visible skips (`testkit`) and `target/ci/report.json` |
| 2026-10-10 | major | Created from the code (crate sizes, layers, data model, rendering, control, gates) |
79 changes: 20 additions & 59 deletions xtask/src/ci.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::layers::cmd_layers;
use super::raw_samples::RAW_SAMPLES;
use super::wasm::{cmd_wasm, cmd_wasm_for};
use super::{Command, Path, PathBuf, USAGE, assets, cargo, ci_lock, ci_quick, ci_report, metadata, parity, root, roots, run};
use super::{Command, PathBuf, USAGE, assets, cargo, ci_lock, ci_quick, ci_report, metadata, parity, root, roots, run, test, use_ci_caps};

/// CI build jobs: one per 1.5 GB of RAM available when CI starts, at most one per CPU, 4 when it
/// is unknown. With line-table debuginfo, 4 jobs measured about 3 GB of RAM in use and 2 jobs
Expand Down Expand Up @@ -63,7 +63,7 @@ pub(crate) fn total_ram_gb() -> Option<u64> {
const TEST_TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"];

/// `args` followed by [`TEST_TARGETS`].
fn with_test_targets<'a>(args: &[&'a str]) -> Vec<&'a str> {
pub(crate) fn with_test_targets<'a>(args: &[&'a str]) -> Vec<&'a str> {
args.iter().copied().chain(TEST_TARGETS).collect()
}

Expand All @@ -72,7 +72,7 @@ fn with_test_targets<'a>(args: &[&'a str]) -> Vec<&'a str> {
/// are cached per process: libtest runs a binary's tests in one process and generates each scene
/// once, while nextest's process per test regenerates them (measured: the ui-egui tests take about
/// 30 min under nextest, under 5 min under cargo test).
fn nextest() -> bool {
pub(crate) fn nextest() -> bool {
static FOUND: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*FOUND.get_or_init(|| {
if std::env::var_os("LIGHTCRAFT_NEXTEST").is_none_or(|v| v != "1") {
Expand Down Expand Up @@ -108,60 +108,6 @@ fn doctests() -> (Command, String) {
(c, "cargo test --no-fail-fast --workspace --doc".to_owned())
}

/// `ci --quick`'s tests: build every workspace test target, then run only the test binaries of
/// `packages`. Building with `-p` instead would resolve features per selection: different
/// artifacts from `ci`'s workspace build, so it would recompile ~130 crates. Doc tests are left to
/// the full `ci`.
fn test_selected(root: &Path, packages: &std::collections::BTreeSet<String>, skip_log: &Path) -> Result<(), String> {
let manifests: std::collections::BTreeMap<String, String> = metadata()?["packages"]
.as_array()
.into_iter()
.flatten()
.filter_map(|p| Some((p["manifest_path"].as_str()?.to_owned(), p["name"].as_str()?.to_owned())))
.filter(|(_, name)| packages.contains(name))
.collect();
let what = "cargo test --workspace --no-run --lib --bins --tests";
eprintln!("$ {what} (then the test binaries of {})", packages.iter().map(String::as_str).collect::<Vec<_>>().join(", "));
let out = cargo()
.args(with_test_targets(&["test", "--workspace", "--no-run", "--message-format=json-render-diagnostics"]))
.stderr(std::process::Stdio::inherit())
.output()
.map_err(|e| format!("{what}: failed to spawn: {e}"))?;
if !out.status.success() {
return Err(format!("{what}: exited with {}", out.status));
}
let mut binaries = Vec::new();
for line in String::from_utf8_lossy(&out.stdout).lines() {
let Ok(msg) = serde_json::from_str::<serde_json::Value>(line) else { continue };
if msg["reason"] != "compiler-artifact" || msg["profile"]["test"] != true {
continue;
}
let (Some(exe), Some(manifest)) = (msg["executable"].as_str(), msg["manifest_path"].as_str()) else { continue };
if let Some(name) = manifests.get(manifest) {
binaries.push((name.clone(), manifest.to_owned(), exe.to_owned()));
}
}
if binaries.is_empty() {
println!("no test binaries in {}", packages.iter().map(String::as_str).collect::<Vec<_>>().join(", "));
return Ok(());
}
let mut failed = Vec::new();
for (name, manifest, exe) in &binaries {
let dir = Path::new(manifest).parent().unwrap_or(root);
let mut c = Command::new(exe);
c.current_dir(dir).env("CARGO_MANIFEST_DIR", dir).env("CARGO_PKG_NAME", name).env(ci_report::SKIP_LOG_ENV, skip_log);
if std::env::var_os("RUST_TEST_THREADS").is_none() {
// as the cargo runs of ci (`cargo()`): more threads make the frame-budget tests flaky
c.env("RUST_TEST_THREADS", std::thread::available_parallelism().map_or(4, |n| n.get()).min(4).to_string());
}
let file = Path::new(exe).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
if run(c, &format!("{name}: {file}")).is_err() {
failed.push(format!("{name} ({file})"));
}
}
if failed.is_empty() { Ok(()) } else { Err(format!("tests failed in {}", failed.join(", "))) }
}

/// The test that prints the messages each language lacks (shown in English); it always passes.
const TRANSLATION_GAPS_TEST: &str = "i18n::tests::translation_gaps_report";

Expand Down Expand Up @@ -214,7 +160,8 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> {
let root = root();
let command = std::iter::once("cargo xtask ci").chain(args.iter().copied()).collect::<Vec<_>>().join(" ");
// held until ci returns: one run at a time per machine (ci_lock.rs)
let _slot = ci_lock::acquire(&root, &command)?;
let slot = ci_lock::acquire(&root, &command)?;
use_ci_caps(&slot);
let plan = if quick {
let (base, files) = ci_quick::changed_files(&root, base)?;
let plan = ci_quick::plan(&files, &ci_quick::packages(&root, &metadata()?), base);
Expand Down Expand Up @@ -294,7 +241,7 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> {
(
"test",
Box::new(|| match &plan {
Some(p) if !p.workspace_wide => test_selected(&root, &p.packages, &ci_report::skip_log(&root, "test")),
Some(p) if !p.workspace_wide => test::selected(&root, &p.packages, &ci_report::skip_log(&root, "test")),
_ => test(tests(&with_test_targets(&["--workspace"])), "test").and_then(|()| test(doctests(), "test")),
}),
),
Expand Down Expand Up @@ -458,4 +405,18 @@ mod ci_jobs_tests {
assert_eq!(ci_jobs(None, 32), 4, "unknown RAM keeps the old default");
assert_eq!(ci_jobs(None, 2), 2);
}

#[test]
fn caps_cover_build_and_test_threads_and_yield_to_explicit_settings() {
let caps = crate::ci_caps();
let keys: Vec<&str> = caps.iter().map(|(k, _)| *k).collect();
assert_eq!(keys, ["CARGO_PROFILE_DEV_DEBUG", "CARGO_BUILD_JOBS", "RUST_TEST_THREADS", "NEXTEST_TEST_THREADS"]);
for (key, value) in caps.iter().filter(|(k, _)| k.ends_with("TEST_THREADS")) {
let n: usize = value.parse().unwrap();
assert!((1..=4).contains(&n), "{key}={value}");
}
let set = crate::caps_to_set(caps, |key| key == "RUST_TEST_THREADS");
assert_eq!(set.iter().map(|(k, _)| *k).collect::<Vec<_>>(), ["CARGO_PROFILE_DEV_DEBUG", "CARGO_BUILD_JOBS", "NEXTEST_TEST_THREADS"]);
assert!(crate::caps_to_set(caps, |_| true).is_empty());
}
}
84 changes: 61 additions & 23 deletions xtask/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ mod layers;
mod parity;
mod roots;
mod stats;
mod test;
mod version;
mod web;

Expand Down Expand Up @@ -63,6 +64,15 @@ commands:
break: clippy, the changed packages' tests, and heif / parity / wasm when they apply.
One ci runs at a time per machine; others wait (LIGHTCRAFT_CI_SLOTS=N for N at once,
LIGHTCRAFT_CI_LOCK=off to skip the lock)
test [-p PKG]... [--keep-going] [--doc] [-- ARGS]
the workspace's tests (or PKG's) with ci's caps (build jobs by free RAM, at most 4 test
threads, line-table debuginfo; a CARGO_BUILD_JOBS or RUST_TEST_THREADS you set wins)
in ci's machine-wide slot, instead of `cargo test`:
builds every test target once, then runs each test binary with ARGS (a filter,
--exact, --skip, --nocapture); stops at the first failing binary unless --keep-going
(alias --no-fail-fast), which runs them all and names each that failed; --doc runs the
doctests after them. LIGHTCRAFT_NEXTEST=1 runs the tests under cargo nextest
(--test-threads N and --nocapture become its options; ARGS are its filters)
corpus [--download]
show where test corpora live; --download fetches PngSuite and CC0 raw samples (raw.pixls.us) into corpus/ and checks their sha256
stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`)
Expand All @@ -87,6 +97,7 @@ fn main() -> ExitCode {
Some("wasm") => cmd_wasm(),
Some("web") => web::run(&rest),
Some("ci") => cmd_ci(&rest),
Some("test") => test::run(&rest),
Some("corpus") => cmd_corpus(rest.contains(&"--download")),
Some("stats") => stats::run(&root(), rest.contains(&"--exact")),
Some("raw-frame") => cmd_raw_frame(&rest),
Expand Down Expand Up @@ -139,32 +150,59 @@ fn workspace_root(runtime_manifest_dir: Option<PathBuf>, compile_time_manifest_d
pub fn cargo() -> Command {
let mut c = Command::new(std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()));
c.current_dir(root());
// Full Windows debuginfo plus one linker per CPU can exhaust RAM before any
// tests run. Scope these overridable defaults to CI, including parity/WASM
// subprocesses, without changing ordinary developer builds or GPU coverage.
if std::env::args().nth(1).as_deref() == Some("ci") {
static JOBS: std::sync::OnceLock<(String, String)> = std::sync::OnceLock::new();
let (build, threads) = JOBS.get_or_init(|| {
let ram_mb = available_ram_mb().or_else(|| total_ram_gb().map(|gb| gb.saturating_mul(1024) / 2));
let jobs = ci_jobs(ram_mb, std::thread::available_parallelism().map_or(4, |n| n.get()));
// More test threads barely shorten CI (a few heavy tests dominate) but make the
// wall-clock frame-budget tests flaky on a loaded machine.
(jobs.to_string(), jobs.min(4).to_string())
});
for (key, value) in [
("CARGO_PROFILE_DEV_DEBUG", "line-tables-only"),
("CARGO_BUILD_JOBS", build.as_str()),
("RUST_TEST_THREADS", threads.as_str()),
("NEXTEST_TEST_THREADS", threads.as_str()),
] {
if std::env::var_os(key).is_none() {
c.env(key, value);
}
}
}
apply_ci_caps(&mut c);
c
}

/// Whether this run gives the cargo and test processes it starts CI's resource caps
/// ([`apply_ci_caps`]). Off until a subcommand opts in with [`use_ci_caps`].
static CI_CAPS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Opt this run into CI's resource caps: the subcommands that build and run the test suite (`ci`,
/// `test`) call it once they hold the CI slot, so every cargo and test binary they start, including
/// parity and WASM subprocesses, gets them. Ordinary developer builds keep their own settings.
///
/// It takes the slot so it can't run before the slot is held: the first capped command takes the
/// RAM snapshot behind [`ci_caps`], and a snapshot taken while another run still holds the slot
/// counts that run's memory as used, shrinking this run's jobs and threads for its whole length.
fn use_ci_caps(_slot: &Option<ci_lock::Held>) {
CI_CAPS.store(true, std::sync::atomic::Ordering::Relaxed);
}

/// The environment defaults of a capped run, worked out once: line-table debuginfo, build jobs by
/// available RAM ([`ci_jobs`]) and test threads at most 4.
fn ci_caps() -> &'static [(&'static str, String); 4] {
static CAPS: std::sync::OnceLock<[(&'static str, String); 4]> = std::sync::OnceLock::new();
CAPS.get_or_init(|| {
let ram_mb = available_ram_mb().or_else(|| total_ram_gb().map(|gb| gb.saturating_mul(1024) / 2));
let jobs = ci_jobs(ram_mb, std::thread::available_parallelism().map_or(4, |n| n.get()));
// More test threads barely shorten CI (a few heavy tests dominate) but make the
// wall-clock frame-budget tests flaky on a loaded machine.
let threads = jobs.min(4).to_string();
[
("CARGO_PROFILE_DEV_DEBUG", "line-tables-only".to_owned()),
("CARGO_BUILD_JOBS", jobs.to_string()),
("RUST_TEST_THREADS", threads.clone()),
("NEXTEST_TEST_THREADS", threads),
]
})
}

/// The caps `c` gets: each of `caps` the environment doesn't set itself (`is_set`), so an explicit
/// setting always wins.
fn caps_to_set<'a>(caps: &'a [(&'static str, String)], is_set: impl Fn(&str) -> bool) -> Vec<(&'static str, &'a str)> {
caps.iter().filter(|(key, _)| !is_set(key)).map(|(key, value)| (*key, value.as_str())).collect()
}

/// Give `c` CI's resource caps when this run opted in ([`use_ci_caps`]). Full Windows debuginfo
/// plus one linker per CPU can exhaust RAM before any tests run, and one test thread per CPU
/// can exhaust it while they run (#3057).
fn apply_ci_caps(c: &mut Command) {
if CI_CAPS.load(std::sync::atomic::Ordering::Relaxed) {
c.envs(caps_to_set(ci_caps(), |key| std::env::var_os(key).is_some()));
}
}

pub fn run(mut cmd: Command, what: &str) -> Result<(), String> {
eprintln!("$ {what}");
let status = cmd.status().map_err(|e| format!("{what}: failed to spawn: {e}"))?;
Expand Down
Loading
Loading