mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge pull request #10909 from dotCooCoo/fix/ci-nextest-archive
CI: build the tests once and run every shard from a nextest archive
This commit is contained in:
8 files changed
+364
-388
No files matched your search
@@ -33,37 +33,37 @@
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / cache warm (ubuntu-24.04)",
|
||||
"name": "gate / build (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 1/6 (ubuntu-24.04)",
|
||||
"name": "gate / lint (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 2/6 (ubuntu-24.04)",
|
||||
"name": "gate / test 1/5 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 3/6 (ubuntu-24.04)",
|
||||
"name": "gate / test 2/5 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 4/6 (ubuntu-24.04)",
|
||||
"name": "gate / test 3/5 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 5/6 (ubuntu-24.04)",
|
||||
"name": "gate / test 4/5 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 6/6 (ubuntu-24.04)",
|
||||
"name": "gate / test 5/5 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
|
||||
+27
-29
@@ -31,9 +31,9 @@ jobs:
|
||||
with:
|
||||
# Same craft-fonts commit as release.yml.
|
||||
craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
# A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change)
|
||||
# took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with
|
||||
# those steps and the save it needs about two hours.
|
||||
# A cold build of every shard's tests (the nightly run, or any run after a toolchain or
|
||||
# lockfile change) took 90 minutes to reach its last three steps on 2026-11-27 and was
|
||||
# canceled there; with those steps and the save it needs about two hours.
|
||||
timeout-minutes: 150
|
||||
# The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0,
|
||||
# CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line
|
||||
@@ -43,19 +43,24 @@ jobs:
|
||||
dev-strip: true
|
||||
# The workspace crates also build without line tables. A panic still names its file and line.
|
||||
dev-debug: "0"
|
||||
# Six legs instead of one: shards 1 and 2 each build vectorcraft-ui-egui's tests and run
|
||||
# half of them, shards 3 to 5 each build and run the tests of their own crates, and shard 6
|
||||
# runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)` passes only
|
||||
# when all six did. On pushes to main, a `cache warm` leg builds what every shard builds and
|
||||
# saves the dependency cache.
|
||||
test-shards: 6
|
||||
# The `build (<os>)` job builds the tests once and writes one nextest archive per shard with
|
||||
# that shard's test binaries (`cargo xtask ci archive`), then runs the doctests. Five test
|
||||
# legs download their own archive and run it without building: shards 1 and 2 each run half
|
||||
# of vectorcraft-ui-egui's tests, and shards 3 to 5 the tests of their own crates
|
||||
# (xtask/src/shards.rs). The `lint (<os>)` leg runs the other `cargo xtask ci` steps beside
|
||||
# them, with a dependency cache of its own. `gate (<os>)` passes when the build and every
|
||||
# test leg that ran passed; `lint (<os>)` is a check of its own.
|
||||
test-shards: 5
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
archive-command: cargo xtask ci archive
|
||||
shard-archives: true
|
||||
after-archive-command: cargo xtask ci doctests
|
||||
lint-command: cargo xtask ci checks
|
||||
# A pull request runs only the test shards whose crates its changes reach: the crates that
|
||||
# own a changed file or declare a read of it (`[package.metadata.craft] reads`), and every
|
||||
# crate that depends on them. Shard 6 runs on every event. The `select legs` log lists the
|
||||
# shards left out and why; pushes to main, the nightly run and the `full-ci` label run all
|
||||
# six. `shard-members` names each shard's crates, as xtask/src/shards.rs › GROUPS does.
|
||||
# crate that depends on them. The `select legs` log lists the shards left out and why; pushes
|
||||
# to main, the nightly run and the `full-ci` label run all five. `shard-members` names each
|
||||
# shard's crates, as xtask/src/shards.rs › GROUPS does.
|
||||
select-tests: true
|
||||
shard-members: |
|
||||
vectorcraft-ui-egui
|
||||
@@ -63,14 +68,10 @@ jobs:
|
||||
vectorcraft-engine
|
||||
vectorcraft vectorcraft-web vectorcraft-cli vectorcraft-mcp xtask
|
||||
(rest)
|
||||
(always)
|
||||
# The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what
|
||||
# its shard builds), and `cache warm` puts their files into the one entry it saves.
|
||||
warm-split: true
|
||||
# The dependency cache also keeps the compiled workspace crates and their library and binary
|
||||
# test executables (not the integration tests' executables), so a
|
||||
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
|
||||
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
|
||||
# test executables (not the integration tests' executables), so a pull request's build
|
||||
# rebuilds only the crates its changes reach. Each main run's `build` job saves a rolling
|
||||
# entry of its own, every build restores the newest one, and
|
||||
# cache-prune.yml deletes the one it replaced after each attempt. The nightly run restores
|
||||
# nothing and builds everything from source.
|
||||
cache-workspace-crates: true
|
||||
@@ -83,15 +84,12 @@ jobs:
|
||||
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
|
||||
# while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the
|
||||
# 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes
|
||||
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a
|
||||
# free runner, and with `warm-split` after every `cache warm <k>/6` leg. The script suspends its
|
||||
# start deadline while any split leg is queued or running, then allows 180 minutes from the last
|
||||
# split completion for the saving leg to start. Without split legs, it allows 180 minutes from
|
||||
# the script's start. A failed split leg fails this job too. The script then waits up to 160
|
||||
# minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the
|
||||
# script's deadlines expire when split builds or runner waits take too long.
|
||||
# the old entries when the `build` job starts saving (scripts/ci-clear-rolling-cache.py). When
|
||||
# the job fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run build. The build starts after `gate / select legs`
|
||||
# and a free runner. The script allows 180 minutes from its start for the build to start, then
|
||||
# waits up to 160 minutes from the build's start. GitHub's 360-minute job limit can end this job
|
||||
# before the script's deadlines expire when runner waits take too long.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
|
||||
@@ -81,9 +81,10 @@ Read on 2026-11-24; re-read anything that may have moved before `nightly-signer`
|
||||
| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135806`), 9 jobs | Workflow list API; jobs that succeeded on recent main push runs |
|
||||
| `candidate_policy.sonar` | `storytold` / `storytold_vectorcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on main commits |
|
||||
|
||||
The signer reads the policy from `nightly-signer`, so a candidate whose CI ran six test shards
|
||||
(`test 1/6` to `test 6/6`) is admitted only after `nightly-signer` advances to a main commit with
|
||||
this policy. Candidates whose CI ran five shards should be signed before that advance.
|
||||
The signer reads the policy from `nightly-signer`, so a candidate whose CI built the tests once
|
||||
(`build`, `lint` and `test 1/5` to `test 5/5`) is admitted only after `nightly-signer` advances to
|
||||
a main commit with this policy. Candidates whose CI ran six shards (`cache warm` and `test 1/6` to
|
||||
`test 6/6`) should be signed before that advance.
|
||||
|
||||
## Ownership and interface
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ _spec = importlib.util.spec_from_file_location("clear", Path(__file__).with_name
|
||||
clear = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(clear)
|
||||
|
||||
WARM = "gate / cache warm (ubuntu-24.04)"
|
||||
WARM = "gate / build (ubuntu-24.04)"
|
||||
ME = [{"name": "cold cache clear", "status": "in_progress"}]
|
||||
|
||||
|
||||
@@ -166,8 +166,10 @@ class Workflow(unittest.TestCase):
|
||||
|
||||
class Jobs(unittest.TestCase):
|
||||
def test_only_the_warm_leg_counts(self):
|
||||
jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"}, {"name": WARM}]
|
||||
self.assertEqual(clear.warm_job(jobs), jobs[2])
|
||||
jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"},
|
||||
{"name": "gate / cache warm (ubuntu-24.04)"}, {"name": WARM}]
|
||||
self.assertEqual(clear.warm_job(jobs), jobs[3])
|
||||
self.assertIsNone(clear.warm_job(jobs[:3]))
|
||||
|
||||
def test_a_rerun_of_failed_jobs_skips_a_leg_that_succeeded(self):
|
||||
grace = clear.RERUN_GRACE_SECONDS
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
The cold run (ci.yml, `cold-build`) never restores the rolling entry, so the old one only adds to
|
||||
the cache while the new one is saved: two entries of about 4.6 GB each, beside the others, go over
|
||||
the repository's 10 GB limit and GitHub evicts the corpus, SonarCloud and Windows ARM64 entries. The
|
||||
gate's `cache warm` leg saves in its `Post Setup` step; this deletes the old entries when that step
|
||||
gate's `build` leg saves in its `Post Setup` step; this deletes the old entries when that step
|
||||
starts, then waits for the step to finish. Pull requests and pushes that start in the minutes
|
||||
between restore nothing from the deleted entry and build cold once. Deleting is the only write; the
|
||||
entry the cold run saves does not exist yet when this runs. Only entries created before this run
|
||||
@@ -35,7 +35,9 @@ import sys
|
||||
import time
|
||||
|
||||
REF = 'refs/heads/main'
|
||||
WARM_JOB = re.compile(r'^gate / cache warm \(')
|
||||
# The leg that saves the rolling entry: the gate's `build` job (ci.yml's `archive-command`). While
|
||||
# the job is skipped, GitHub lists it as `gate / build (${{ matrix.os }})`.
|
||||
WARM_JOB = re.compile(r'^gate / build \((?!\$\{\{)')
|
||||
SPLIT_WARM_JOB = re.compile(r'^gate / cache warm \d+/\d+ \(')
|
||||
# The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of
|
||||
# them fails or is canceled, the legs are skipped and no warm leg is listed. With `warm-split` the
|
||||
@@ -64,8 +66,8 @@ START_SECONDS = 180 * 60
|
||||
STOPPED = ('failure', 'cancelled', 'timed_out')
|
||||
# Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml.
|
||||
TOLERATED_FAILURES = ('Trim the cache entry to this build',)
|
||||
NO_SAVE = 'the cache warm leg failed or was canceled and saves no entry; nothing deleted. Re-running the failed jobs runs this job again with the leg'
|
||||
SAVE_LOST = 'the cache warm leg did not finish its save after the old rolling entries were deleted; the next run starts cold'
|
||||
NO_SAVE = 'the build leg failed or was canceled and saves no entry; nothing deleted. Re-running the failed jobs runs this job again with the leg'
|
||||
SAVE_LOST = 'the build leg did not finish its save after the old rolling entries were deleted; the next run starts cold'
|
||||
|
||||
|
||||
def save_step(job):
|
||||
@@ -194,7 +196,7 @@ def main():
|
||||
job = warm_job(jobs.get('jobs', []))
|
||||
ready = start_wait_began(jobs.get('jobs', []), began)
|
||||
if started_late(job, ready):
|
||||
print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
print(f'::error::the build leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
return 1
|
||||
if job and saving(job):
|
||||
break
|
||||
@@ -206,7 +208,7 @@ def main():
|
||||
if warm_job(earlier_jobs[earlier]) is not None:
|
||||
break
|
||||
if not_in_attempt(jobs.get('jobs', []), earlier_jobs, (datetime.now(timezone.utc) - began).total_seconds()):
|
||||
print('the cache warm leg is not part of this attempt (it succeeded in an earlier one); nothing deleted')
|
||||
print('the build leg is not part of this attempt (it succeeded in an earlier one); nothing deleted')
|
||||
return
|
||||
if legs_stopped(jobs.get('jobs', [])):
|
||||
print('::error::the gate stopped before its cache warm leg started; nothing deleted')
|
||||
@@ -216,14 +218,14 @@ def main():
|
||||
if job.get('conclusion') in STOPPED or job.get('conclusion') == 'skipped' and legs_stopped(jobs.get('jobs', [])):
|
||||
print(f'::error::{NO_SAVE}')
|
||||
return 1
|
||||
print('the cache warm leg finished without a save step; nothing deleted')
|
||||
print('the build leg finished without a save step; nothing deleted')
|
||||
return
|
||||
now = datetime.now(timezone.utc)
|
||||
if start_overdue(job, now, ready):
|
||||
print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
print(f'::error::the build leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
return 1
|
||||
if gave_up(job, now):
|
||||
print('::error::the cache warm leg never reached its save; nothing deleted')
|
||||
print('::error::the build leg never reached its save; nothing deleted')
|
||||
return 1
|
||||
time.sleep(POLL_SECONDS)
|
||||
if saves_nothing(job):
|
||||
@@ -249,7 +251,7 @@ def main():
|
||||
if saves_nothing(job):
|
||||
print(f'::error::{SAVE_LOST}')
|
||||
return 1
|
||||
print('the cache warm leg saved its entry')
|
||||
print('the build leg saved its entry')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! 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 warm` append those
|
||||
//! 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.
|
||||
|
||||
|
||||
+263
-174
@@ -50,11 +50,14 @@ commands:
|
||||
wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates, the web app and its plug-in worker
|
||||
test the workspace tests (cargo nextest when installed, else cargo test), then the doctests
|
||||
ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, grant-sites, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure)
|
||||
ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs
|
||||
the tests and doctests of its crates, the last shard the other steps
|
||||
ci warm build what every shard builds, without running it (fills the gate's cache); with
|
||||
GATE_SHARD of GATE_SHARDS set, only what that shard builds; with
|
||||
CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for each build to that file
|
||||
ci shard shard $GATE_SHARD of $GATE_SHARDS of ci's tests (xtask/src/shards.rs): from the
|
||||
nextest archive in $NEXTEST_ARCHIVE_FILE when set, otherwise it builds them and
|
||||
also runs the doctests of its crates
|
||||
ci archive build every shard's tests once and write shard k's nextest archive to
|
||||
$NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME for k from 1 to $GATE_SHARDS; with
|
||||
CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for the build to that file
|
||||
ci doctests the doctests of each shard's crates, one cargo command per shard
|
||||
ci checks the ci steps other than the tests, the doctests and the i18n report
|
||||
shards list the crates each shard tests; fails when a member is in no shard or in two,
|
||||
or builds with other features in its shard than in the whole workspace
|
||||
corpus [--download | --affinity | --scripts]
|
||||
@@ -95,7 +98,9 @@ fn main() -> ExitCode {
|
||||
Some("wasm") => cmd_wasm(),
|
||||
Some("test") => cmd_test().and_then(|()| cmd_doctests()),
|
||||
Some("ci") if rest.first() == Some(&"shard") => cmd_ci_shard(),
|
||||
Some("ci") if rest.first() == Some(&"warm") => cmd_ci_warm(),
|
||||
Some("ci") if rest.first() == Some(&"archive") => cmd_ci_archive(),
|
||||
Some("ci") if rest.first() == Some(&"doctests") => cmd_ci_doctests(),
|
||||
Some("ci") if rest.first() == Some(&"checks") => cmd_ci_checks(),
|
||||
Some("ci") => cmd_ci(),
|
||||
Some("shards") => shards::run().map(drop),
|
||||
Some("corpus") => cmd_corpus_args(&rest),
|
||||
@@ -288,46 +293,62 @@ fn cmd_test() -> Result<(), String> {
|
||||
/// which needs nextest. A part runs its counted share, then its pinned tests, each with
|
||||
/// nextest's default thread count. Every run finishes before the first error is returned.
|
||||
fn test_packages(select: &[String], shown: &str, targets: shards::Targets, part: Option<shards::Part>) -> Result<(), String> {
|
||||
let (listed, targets) = (targets.shown(), targets.args());
|
||||
if let Some(part) = part {
|
||||
if !has_nextest() {
|
||||
return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests needs cargo-nextest"));
|
||||
}
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(targets);
|
||||
let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("cargo nextest list {shown}: exited with {}", out.status));
|
||||
}
|
||||
let missing = part.missing_pins(&String::from_utf8_lossy(&out.stdout)).map_err(|e| format!("cargo nextest list {shown}: {e}"))?;
|
||||
if !missing.is_empty() {
|
||||
return Err(format!(
|
||||
"cargo nextest list {shown}: no test has the full name of pinned test(s) {} (update `pinned` in xtask/src/shards.rs)",
|
||||
missing.join(", ")
|
||||
));
|
||||
}
|
||||
let command = |args: Vec<String>| {
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", "run"]).args(select).args(targets).args(&args);
|
||||
let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::<Vec<_>>().join(" ");
|
||||
(c, format!("cargo nextest run {shown} {listed} {quoted}"))
|
||||
};
|
||||
let mut result = Ok(());
|
||||
for args in part.runs() {
|
||||
let (c, what) = command(args);
|
||||
result = result.and(run(c, &what));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
let mut c = cargo();
|
||||
if has_nextest() {
|
||||
c.args(["nextest", "run"]).args(select).args(targets);
|
||||
run(c, &format!("cargo nextest run {shown} {listed}"))
|
||||
} else {
|
||||
let (listed, args) = (targets.shown(), targets.args());
|
||||
if part.is_none() && !has_nextest() {
|
||||
eprintln!("note: cargo-nextest is not installed; running cargo test (cargo install cargo-nextest for faster runs)");
|
||||
c.arg("test").args(select).args(targets);
|
||||
run(c, &format!("cargo test {shown} {listed}"))
|
||||
let mut c = cargo();
|
||||
c.arg("test").args(select).args(args);
|
||||
return run(c, &format!("cargo test {shown} {listed}"));
|
||||
}
|
||||
let nextest = |sub: &str| {
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", sub]).args(select).args(args);
|
||||
c
|
||||
};
|
||||
nextest_tests(&nextest, &format!("{shown} {listed}"), part)
|
||||
}
|
||||
|
||||
/// The tests of the nextest archive `file`, which `cargo xtask ci archive` wrote for one shard;
|
||||
/// with `part`, that part's share of them, as [`test_packages`] runs it.
|
||||
fn archive_tests(file: &Path, part: Option<shards::Part>) -> Result<(), String> {
|
||||
let nextest = |sub: &str| {
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", sub, "--archive-file"]).arg(file).arg("--workspace-remap").arg(root());
|
||||
c
|
||||
};
|
||||
nextest_tests(&nextest, &format!("--archive-file {}", file.display()), part)
|
||||
}
|
||||
|
||||
/// The tests `nextest(sub)` selects for `cargo nextest <sub>`, shown after the subcommand as
|
||||
/// `shown`; with `part`, only that part's share of them (see [`test_packages`]).
|
||||
fn nextest_tests(nextest: &dyn Fn(&str) -> Command, shown: &str, part: Option<shards::Part>) -> Result<(), String> {
|
||||
if !has_nextest() {
|
||||
return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests, or runs an archive, needs cargo-nextest"));
|
||||
}
|
||||
let Some(part) = part else {
|
||||
return run(nextest("run"), &format!("cargo nextest run {shown}"));
|
||||
};
|
||||
let mut c = nextest("list");
|
||||
c.args(["--color", "never", "--message-format", "json"]);
|
||||
let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("cargo nextest list {shown}: exited with {}", out.status));
|
||||
}
|
||||
let missing = part.missing_pins(&String::from_utf8_lossy(&out.stdout)).map_err(|e| format!("cargo nextest list {shown}: {e}"))?;
|
||||
if !missing.is_empty() {
|
||||
return Err(format!(
|
||||
"cargo nextest list {shown}: no test has the full name of pinned test(s) {} (update `pinned` in xtask/src/shards.rs)",
|
||||
missing.join(", ")
|
||||
));
|
||||
}
|
||||
let mut result = Ok(());
|
||||
for args in part.runs() {
|
||||
let mut c = nextest("run");
|
||||
c.args(&args);
|
||||
let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::<Vec<_>>().join(" ");
|
||||
result = result.and(run(c, &format!("cargo nextest run {shown} {quoted}")));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The doctests, which nextest doesn't run.
|
||||
@@ -350,7 +371,8 @@ fn doctest_packages(crates: &[shards::Member]) -> Result<(), String> {
|
||||
/// One `cargo xtask ci` step: its name and what it runs.
|
||||
type Step = (&'static str, Box<dyn Fn() -> Result<(), String>>);
|
||||
|
||||
/// The `ci` steps that build and run tests of the whole workspace; `ci shard` runs them per shard.
|
||||
/// The `ci` steps that build and run tests of the whole workspace; `ci shard` runs them per shard,
|
||||
/// and `ci checks` runs the other steps.
|
||||
const TEST_STEPS: [&str; 3] = ["test", "doctests", "i18n-report"];
|
||||
|
||||
/// `cargo xtask ci`: each step in turn, stopping at the first that fails; the summary names the
|
||||
@@ -359,152 +381,180 @@ fn cmd_ci() -> Result<(), String> {
|
||||
run_steps(&ci_steps())
|
||||
}
|
||||
|
||||
/// `cargo xtask ci shard`: shard `GATE_SHARD` of `GATE_SHARDS` (1-based, as the shared gate
|
||||
/// workflow sets them). A test shard runs the shard checks, then the tests and doctests of its
|
||||
/// crates, and the i18n report where it tests vectorcraft-ui-egui; a part of a split runs its
|
||||
/// share of the tests, and only part 1 the doctests and the report. The checks shard runs every
|
||||
/// other `ci` step and the shard checks.
|
||||
fn cmd_ci_shard() -> Result<(), String> {
|
||||
let number = |key: &str| -> Result<usize, String> {
|
||||
let value = std::env::var(key).map_err(|_| format!("ci shard: {key} is not set (the gate workflow sets it)"))?;
|
||||
value.trim().parse().map_err(|_| format!("ci shard: {key} is `{value}`, not a number"))
|
||||
};
|
||||
let (shard, count) = (number("GATE_SHARD")?, number("GATE_SHARDS")?);
|
||||
/// `GATE_SHARDS`, the shard count the shared gate workflow sets, for `ci <what>`; it must equal
|
||||
/// the number of shards in xtask/src/shards.rs.
|
||||
fn gate_shards(what: &str) -> Result<usize, String> {
|
||||
let count = gate_number(what, "GATE_SHARDS")?;
|
||||
if count != shards::GROUPS.len() {
|
||||
return Err(format!(
|
||||
"ci shard: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)",
|
||||
"ci {what}: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)",
|
||||
shards::GROUPS.len()
|
||||
));
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// The number in the environment variable `key`, which the shared gate workflow sets.
|
||||
fn gate_number(what: &str, key: &str) -> Result<usize, String> {
|
||||
let value = std::env::var(key).map_err(|_| format!("ci {what}: {key} is not set (the gate workflow sets it)"))?;
|
||||
value.trim().parse().map_err(|_| format!("ci {what}: {key} is `{value}`, not a number"))
|
||||
}
|
||||
|
||||
/// `cargo xtask ci shard`: shard `GATE_SHARD` of `GATE_SHARDS` (1-based, as the shared gate
|
||||
/// workflow sets them). A shard runs the tests of its crates, and the i18n report where it tests
|
||||
/// vectorcraft-ui-egui; a part of a split runs its share of the tests, and only part 1 the report.
|
||||
///
|
||||
/// With `NEXTEST_ARCHIVE_FILE` set (the gate's shard legs), it runs the tests of that archive,
|
||||
/// which `ci archive` built for this shard after the shard checks, and leaves the doctests to
|
||||
/// `ci doctests`. Otherwise it runs the shard checks, builds the tests, and runs the doctests of
|
||||
/// its crates on part 1 too.
|
||||
fn cmd_ci_shard() -> Result<(), String> {
|
||||
let count = gate_shards("shard")?;
|
||||
let shard = gate_number("shard", "GATE_SHARD")?;
|
||||
if !(1..=count).contains(&shard) {
|
||||
return Err(format!("ci shard: GATE_SHARD is {shard}, not 1 to {count}"));
|
||||
}
|
||||
let checked = shards::run()?;
|
||||
let archive = std::env::var_os("NEXTEST_ARCHIVE_FILE").filter(|f| !f.is_empty()).map(PathBuf::from);
|
||||
let shards::Shard { runs, part } = if archive.is_some() { shards::assigned()? } else { shards::run()? }.swap_remove(shard - 1);
|
||||
let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default();
|
||||
eprintln!("ci shard {shard}/{count}: the tests of {}{share}", shards::describe(&runs));
|
||||
let first = part.is_none_or(|p| p.is_first());
|
||||
let report =
|
||||
runs.iter().find(|r| r.targets == shards::Targets::All && r.crates.iter().any(|m| m.name == "vectorcraft-ui-egui")).filter(|_| first);
|
||||
let mut steps: Vec<Step> = Vec::new();
|
||||
match &checked[shard - 1] {
|
||||
shards::Shard::Tests(runs, part) => {
|
||||
let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default();
|
||||
eprintln!("ci shard {shard}/{count}: the tests of {}{share}", shards::describe(runs));
|
||||
let shown = |crates: &[shards::Member]| crates.iter().map(|m| format!("-p {}", m.name)).collect::<Vec<_>>().join(" ");
|
||||
let part = *part;
|
||||
let tests: Vec<(Vec<String>, String, shards::Targets)> =
|
||||
runs.iter().map(|r| (shards::select(&r.crates), shown(&r.crates), r.targets)).collect();
|
||||
// Each run finishes before the first error is returned.
|
||||
steps.push((
|
||||
"test",
|
||||
Box::new(move || {
|
||||
let mut result = Ok(());
|
||||
for (s, w, t) in &tests {
|
||||
result = result.and(test_packages(s, w, *t, part));
|
||||
}
|
||||
result
|
||||
}),
|
||||
));
|
||||
// The doctests and the i18n report run once, on a split's first part.
|
||||
let first = part.is_none_or(|p| p.is_first());
|
||||
if first {
|
||||
let c = shards::unit_crates(runs);
|
||||
steps.push(("doctests", Box::new(move || doctest_packages(&c))));
|
||||
}
|
||||
let all = runs.iter().find(|r| r.targets == shards::Targets::All && r.crates.iter().any(|m| m.name == "vectorcraft-ui-egui"));
|
||||
if let Some(r) = all.filter(|_| first) {
|
||||
let (select, shown) = (shards::select(&r.crates), shown(&r.crates));
|
||||
steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown))));
|
||||
}
|
||||
}
|
||||
shards::Shard::Checks => {
|
||||
eprintln!("ci shard {shard}/{count}: the ci steps other than the tests");
|
||||
steps.extend(ci_steps().into_iter().filter(|(name, _)| !TEST_STEPS.contains(name)));
|
||||
if let Some(file) = archive {
|
||||
let tests = file.clone();
|
||||
steps.push(("test", Box::new(move || archive_tests(&tests, part))));
|
||||
if report.is_some() {
|
||||
steps.push(("i18n-report", Box::new(move || i18n_report_archive(&file))));
|
||||
}
|
||||
return run_steps(&steps);
|
||||
}
|
||||
let shown = |crates: &[shards::Member]| crates.iter().map(|m| format!("-p {}", m.name)).collect::<Vec<_>>().join(" ");
|
||||
let report = report.map(|r| (shards::select(&r.crates), shown(&r.crates)));
|
||||
let tests: Vec<(Vec<String>, String, shards::Targets)> = runs.iter().map(|r| (shards::select(&r.crates), shown(&r.crates), r.targets)).collect();
|
||||
// Each run finishes before the first error is returned.
|
||||
steps.push((
|
||||
"test",
|
||||
Box::new(move || {
|
||||
let mut result = Ok(());
|
||||
for (s, w, t) in &tests {
|
||||
result = result.and(test_packages(s, w, *t, part));
|
||||
}
|
||||
result
|
||||
}),
|
||||
));
|
||||
// The doctests and the i18n report run once, on a split's first part.
|
||||
if first {
|
||||
let c = shards::unit_crates(&runs);
|
||||
steps.push(("doctests", Box::new(move || doctest_packages(&c))));
|
||||
}
|
||||
if let Some((select, shown)) = report {
|
||||
steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown))));
|
||||
}
|
||||
run_steps(&steps)
|
||||
}
|
||||
|
||||
/// `cargo xtask ci warm`: for each test shard, builds the library and binary tests of the crates
|
||||
/// it tests without running them, then builds what the checks shard builds, so one
|
||||
/// dependency-cache entry holds the dependencies of every shard with the features that shard builds
|
||||
/// them with (cargo resolves features over the packages each command selects). It does not build
|
||||
/// the integration tests ([`warm_runs`], [`warm_tests`]), which take the same dependencies and
|
||||
/// dev-dependencies as the library tests. Cargo warns `unused dependency vectorcraft-testkit` for
|
||||
/// vectorcraft-cli, whose integration tests are the only ones that use it.
|
||||
/// `cargo xtask ci archive`: the shared gate's `build` job (`archive-command` with
|
||||
/// `shard-archives`). After the shard checks it builds the tests of each shard's run, one cargo
|
||||
/// command per run ([`archive_builds`]), then writes the tests of shard k's run (1-based,
|
||||
/// [`archived_runs`]) to the nextest archive `$NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME` for
|
||||
/// every k up to `GATE_SHARDS`, with the run's package and target selection, so the archive's own
|
||||
/// build finds them built. A split's later parts run the same binaries as part 1, so their archive
|
||||
/// is a copy of part 1's.
|
||||
///
|
||||
/// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that
|
||||
/// shard builds: a test shard's tests, or the checks shard's builds. A split's later parts build
|
||||
/// nothing in either case, since part 1 builds the same tests.
|
||||
///
|
||||
/// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS`
|
||||
/// (xtask/src/cache_units.rs), xtask's own build included.
|
||||
fn cmd_ci_warm() -> Result<(), String> {
|
||||
let var = |key: &str| match std::env::var(key) {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(std::env::VarError::NotPresent) => Ok(None),
|
||||
Err(std::env::VarError::NotUnicode(_)) => Err(format!("ci warm: {key} is not valid Unicode")),
|
||||
/// In a leg that saves the cache, the library and binary tests' builds record their units in
|
||||
/// `CRAFT_CACHE_UNITS` (xtask/src/cache_units.rs), xtask's own build included, and the
|
||||
/// integration tests' builds do not, so the saved entry holds every dependency and
|
||||
/// dev-dependency the tests build with and none of the integration tests' executables.
|
||||
fn cmd_ci_archive() -> Result<(), String> {
|
||||
let var = |key: &str| {
|
||||
std::env::var(key).ok().filter(|v| !v.is_empty()).ok_or_else(|| format!("ci archive: {key} is not set (the gate workflow sets it)"))
|
||||
};
|
||||
let (shard, count) = (var("GATE_SHARD")?, var("GATE_SHARDS")?);
|
||||
let only = shards::warm_only(shard.as_deref(), count.as_deref())?;
|
||||
let (dir, name) = (PathBuf::from(var("NEXTEST_ARCHIVE_DIR")?), var("NEXTEST_ARCHIVE_NAME")?);
|
||||
gate_shards("archive")?;
|
||||
if !has_nextest() {
|
||||
return Err("ci archive: cargo-nextest is not installed".into());
|
||||
}
|
||||
cache_units::record_xtask()?;
|
||||
let checked = shards::run()?;
|
||||
let (tests, checks) = shards::warm_plan(&checked, only);
|
||||
let mut steps: Vec<Step> = Vec::new();
|
||||
for i in tests {
|
||||
if let shards::Shard::Tests(runs, _) = checked[i].clone() {
|
||||
for r in warm_runs(runs) {
|
||||
steps.push((
|
||||
"build tests",
|
||||
Box::new(move || {
|
||||
let (c, what) = warm_tests(&r);
|
||||
cache_units::run(c, &what)
|
||||
}),
|
||||
));
|
||||
}
|
||||
let archived = archived_runs(&checked)?;
|
||||
for (units, r) in archive_builds(&checked) {
|
||||
let (c, what) = test_build(&r, units);
|
||||
if units { cache_units::run(c, &what)? } else { run(c, &what)? }
|
||||
}
|
||||
for (i, (shard, r)) in checked.iter().zip(archived).enumerate() {
|
||||
let file = dir.join((i + 1).to_string()).join(&name);
|
||||
let parent = file.parent().unwrap_or(&dir);
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("ci archive: {}: {e}", parent.display()))?;
|
||||
if let Some(p) = shard.part.filter(|p| !p.is_first()) {
|
||||
let first = dir.join((i + 2 - p.index).to_string()).join(&name);
|
||||
std::fs::hard_link(&first, &file)
|
||||
.or_else(|_| std::fs::copy(&first, &file).map(drop))
|
||||
.map_err(|e| format!("ci archive: copy {} to {}: {e}", first.display(), file.display()))?;
|
||||
eprintln!("ci archive: shard {} runs part {} of shard {}'s archive", i + 1, p.index, i + 2 - p.index);
|
||||
continue;
|
||||
}
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", "archive"]).args(shards::select(&r.crates)).args(r.targets.args()).arg("--archive-file").arg(&file);
|
||||
let what = format!("cargo nextest archive {} ({}) --archive-file {}", r.targets.shown(), shards::names(&r.crates), file.display());
|
||||
run(c, &what)?;
|
||||
}
|
||||
if checks {
|
||||
push_warm_checks(&mut steps);
|
||||
}
|
||||
run_steps(&steps)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The builds of the checks shard that [`cmd_ci_warm`] runs.
|
||||
fn push_warm_checks(steps: &mut Vec<Step>) {
|
||||
steps.push((
|
||||
"clippy",
|
||||
Box::new(|| {
|
||||
let mut c = cargo();
|
||||
c.args(["clippy", "--workspace", "--all-targets", "--keep-going"]);
|
||||
cache_units::run(c, "cargo clippy --workspace --all-targets --keep-going")
|
||||
}),
|
||||
));
|
||||
steps.push((
|
||||
"no-bundled-fonts",
|
||||
Box::new(|| {
|
||||
let mut c = cargo();
|
||||
c.args(["test", "-p", "vectorcraft-text", "--no-default-features", "--test", "without_bundled_fonts", "--no-run"]);
|
||||
cache_units::run(c, "cargo test -p vectorcraft-text --no-default-features --test without_bundled_fonts --no-run")?;
|
||||
let mut c = cargo();
|
||||
c.args(["clippy", "-p", "vectorcraft-ui-egui", "--no-default-features", "--all-targets"]);
|
||||
cache_units::run(c, "cargo clippy -p vectorcraft-ui-egui --no-default-features --all-targets")?;
|
||||
let mut c = cargo();
|
||||
c.args(["test", "-p", "vectorcraft-ui-egui", "--no-default-features", "--test", "install_fonts", "--no-run"]);
|
||||
cache_units::run(c, "cargo test -p vectorcraft-ui-egui --no-default-features --test install_fonts --no-run")
|
||||
}),
|
||||
));
|
||||
steps.push(("wasm", Box::new(cmd_wasm)));
|
||||
/// The run of each shard, whose tests `ci archive` writes to the shard's archive with one cargo
|
||||
/// selection. A shard that makes more than one run is an error.
|
||||
fn archived_runs(shards: &[shards::Shard]) -> Result<Vec<&shards::Run>, String> {
|
||||
shards
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, s)| match s.runs.as_slice() {
|
||||
[r] => Ok(r),
|
||||
runs => Err(format!(
|
||||
"ci archive: shard {} makes {} runs, and its archive holds the tests of one (xtask/src/shards.rs › GROUPS)",
|
||||
i + 1,
|
||||
runs.len()
|
||||
)),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The runs of a test shard that `ci warm` builds: every run except an integration-test run, whose
|
||||
/// crate has its library tests in a run on another shard.
|
||||
fn warm_runs(runs: Vec<shards::Run>) -> impl Iterator<Item = shards::Run> {
|
||||
runs.into_iter().filter(|r| r.targets != shards::Targets::Integration)
|
||||
/// The builds `ci archive` runs before it writes the archives, in order: `(true, run)` builds the
|
||||
/// library and binary tests of a run of the first part of each shard (none for a run of
|
||||
/// integration tests alone, whose crate has its library tests in a run on another shard), then
|
||||
/// `(false, run)` builds each such run's integration tests.
|
||||
fn archive_builds(shards: &[shards::Shard]) -> Vec<(bool, shards::Run)> {
|
||||
let runs: Vec<&shards::Run> = shards.iter().filter(|s| s.part.is_none_or(|p| p.is_first())).flat_map(|s| &s.runs).collect();
|
||||
let units = runs.iter().filter(|r| r.targets != shards::Targets::Integration).map(|r| (true, (*r).clone()));
|
||||
let integration = runs.iter().filter(|r| r.targets != shards::Targets::Units).map(|r| (false, (*r).clone()));
|
||||
units.chain(integration).collect()
|
||||
}
|
||||
|
||||
/// The command `ci warm` builds the library and binary tests of one run of a test shard with, and
|
||||
/// its description.
|
||||
fn warm_tests(r: &shards::Run) -> (Command, String) {
|
||||
let units = shards::Targets::Units;
|
||||
/// The `cargo test --no-run` command that builds a run's library and binary tests (`units`) or its
|
||||
/// integration tests, and its description.
|
||||
fn test_build(r: &shards::Run, units: bool) -> (Command, String) {
|
||||
let targets = if units { shards::Targets::Units } else { shards::Targets::Integration };
|
||||
let mut c = cargo();
|
||||
c.arg("test").args(shards::select(&r.crates)).args(units.args()).arg("--no-run");
|
||||
(c, format!("cargo test {} --no-run ({})", units.shown(), shards::names(&r.crates)))
|
||||
c.arg("test").args(shards::select(&r.crates)).args(targets.args()).arg("--no-run");
|
||||
(c, format!("cargo test {} --no-run ({})", targets.shown(), shards::names(&r.crates)))
|
||||
}
|
||||
|
||||
/// `cargo xtask ci doctests`: the doctests of each shard's crates, one cargo command per shard
|
||||
/// with the crates `ci shard` runs them for, after `ci archive` (the shared gate's
|
||||
/// `after-archive-command`). Every command runs before the first error is returned.
|
||||
fn cmd_ci_doctests() -> Result<(), String> {
|
||||
let mut result = Ok(());
|
||||
for s in shards::assigned()?.iter().filter(|s| s.part.is_none_or(|p| p.is_first())) {
|
||||
result = result.and(doctest_packages(&shards::unit_crates(&s.runs)));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// `cargo xtask ci checks`: every `ci` step other than [`TEST_STEPS`], for the shared gate's
|
||||
/// `lint` leg.
|
||||
fn cmd_ci_checks() -> Result<(), String> {
|
||||
run_steps(&ci_steps().into_iter().filter(|(name, _)| !TEST_STEPS.contains(name)).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// Runs `steps` in turn, stopping at the first that fails; the summary names the steps that passed
|
||||
@@ -651,22 +701,61 @@ fn i18n_report_packages(select: &[String], shown: &str) -> Result<(), String> {
|
||||
run(c, &format!("cargo test {shown} --lib --bins --tests -- i18n::tests::untranslated_report --exact --nocapture"))
|
||||
}
|
||||
|
||||
/// [`cmd_ci_i18n_report`] from the nextest archive `file` of a `ci shard` that tests
|
||||
/// vectorcraft-ui-egui.
|
||||
fn i18n_report_archive(file: &Path) -> Result<(), String> {
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", "run", "--archive-file"]).arg(file).arg("--workspace-remap").arg(root());
|
||||
c.args(["--no-capture", "-E", "test(=i18n::tests::untranslated_report)"]);
|
||||
run(c, &format!("cargo nextest run --archive-file {} --no-capture -E 'test(=i18n::tests::untranslated_report)'", file.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use shards::{Group, Split, Targets};
|
||||
|
||||
#[test]
|
||||
fn warm_builds_library_and_binary_tests_without_integration_tests() {
|
||||
fn the_archive_builds_each_run_once_library_tests_first() {
|
||||
let m =
|
||||
|name: &str| shards::Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true };
|
||||
let args = |r: &shards::Run| warm_tests(r).0.get_args().map(|a| a.to_string_lossy().into_owned()).collect::<Vec<String>>();
|
||||
let all = shards::Run::all(vec![m("a")]);
|
||||
assert_eq!(args(&all), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--no-run"]);
|
||||
assert_eq!(warm_tests(&all).1, "cargo test --lib --bins --no-run (a)");
|
||||
let units = shards::Run { targets: shards::Targets::Units, crates: vec![m("b")] };
|
||||
assert_eq!(args(&units), ["test", "-p", "path+file:///w/b#0.1.0", "--lib", "--bins", "--no-run"]);
|
||||
let integration = shards::Run { targets: shards::Targets::Integration, crates: vec![m("b")] };
|
||||
let built: Vec<shards::Run> = warm_runs(vec![all.clone(), integration, units.clone()]).collect();
|
||||
assert_eq!(built, [all, units]);
|
||||
static SPLIT: Split = Split { crates: &["a"], pinned: &[&[], &[]] };
|
||||
let groups = [
|
||||
Group::Part(&SPLIT, 1),
|
||||
Group::Part(&SPLIT, 2),
|
||||
Group::Targets(&[(Targets::Units, &["b"])]),
|
||||
Group::Targets(&[(Targets::All, &["c"]), (Targets::Integration, &["b"])]),
|
||||
Group::Rest,
|
||||
];
|
||||
let shards = shards::assign(&groups, &[m("a"), m("b"), m("c"), m("d")]).unwrap();
|
||||
let builds: Vec<(Vec<String>, String)> = archive_builds(&shards)
|
||||
.iter()
|
||||
.map(|(units, r)| {
|
||||
let (c, what) = test_build(r, *units);
|
||||
(c.get_args().map(|a| a.to_string_lossy().into_owned()).collect(), what)
|
||||
})
|
||||
.collect();
|
||||
let shown: Vec<&str> = builds.iter().map(|(_, what)| what.as_str()).collect();
|
||||
assert_eq!(
|
||||
shown,
|
||||
[
|
||||
"cargo test --lib --bins --no-run (a)",
|
||||
"cargo test --lib --bins --no-run (b)",
|
||||
"cargo test --lib --bins --no-run (c)",
|
||||
"cargo test --lib --bins --no-run (d)",
|
||||
"cargo test --test '*' --no-run (a)",
|
||||
"cargo test --test '*' --no-run (c)",
|
||||
"cargo test --test '*' --no-run (b)",
|
||||
"cargo test --test '*' --no-run (d)",
|
||||
]
|
||||
);
|
||||
assert_eq!(builds[1].0, ["test", "-p", "path+file:///w/b#0.1.0", "--lib", "--bins", "--no-run"]);
|
||||
assert_eq!(builds[6].0, ["test", "-p", "path+file:///w/b#0.1.0", "--test", "*", "--no-run"]);
|
||||
let two = archived_runs(&shards).unwrap_err();
|
||||
assert!(two.contains("shard 4 makes 2 runs"), "{two}");
|
||||
let real = shards::assigned().unwrap();
|
||||
let archived = archived_runs(&real).unwrap();
|
||||
assert_eq!(archived.len(), shards::GROUPS.len());
|
||||
assert!(archived.iter().zip(&real).all(|(r, s)| s.runs == [(*r).clone()]));
|
||||
}
|
||||
}
|
||||
+45
-161
@@ -2,10 +2,12 @@
|
||||
//! gate workflow): which workspace crates each shard tests, and the checks that keep the split
|
||||
//! complete.
|
||||
//!
|
||||
//! Each test shard builds and runs the tests of its own crates and what they depend on. The last
|
||||
//! shard runs the `cargo xtask ci` steps that are not tests. [`GROUPS`] names the crates of the
|
||||
//! first shards; every other workspace member goes to the [`Group::Rest`] shard, so a new crate is
|
||||
//! tested without a change here. [`check`] fails when a named crate is not a workspace member or
|
||||
//! In CI the gate's `build` job builds every shard's tests once and writes one nextest archive per
|
||||
//! shard (`cargo xtask ci archive`), and each shard runs its tests from its archive. Without an archive a shard builds and runs the tests of its own crates and what they
|
||||
//! depend on. The `cargo xtask ci` steps that are not tests run in the gate's `lint` leg
|
||||
//! (`cargo xtask ci checks`). [`GROUPS`] names the crates of the first shards; every other
|
||||
//! workspace member goes to the [`Group::Rest`] shard, so a new crate is tested without a change
|
||||
//! here. [`check`] fails when a named crate is not a workspace member or
|
||||
//! is named twice, when a group is empty, and when a crate's features in its shard differ from
|
||||
//! its features in `cargo test --workspace`. Cargo resolves features over the packages a command
|
||||
//! selects, so a feature that only another crate's dev-dependencies turn on is off in a shard
|
||||
@@ -37,8 +39,6 @@ pub enum Group {
|
||||
Targets(&'static [(Targets, &'static [&'static str])]),
|
||||
/// The tests of every workspace member no other group names.
|
||||
Rest,
|
||||
/// The `cargo xtask ci` steps that are not tests.
|
||||
Checks,
|
||||
}
|
||||
|
||||
/// The test targets a shard builds and runs for a crate.
|
||||
@@ -109,18 +109,14 @@ pub static UI_EGUI: Split = Split {
|
||||
};
|
||||
|
||||
/// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length, and its
|
||||
/// `shard-members` names each shard's crates. vectorcraft-engine's integration tests run on
|
||||
/// shard 4, which already builds the engine library for the app crates.
|
||||
/// `shard-members` names each shard's crates. Each shard makes one run: `cargo xtask ci archive`
|
||||
/// writes a shard's archive with the run's package and target selection.
|
||||
pub const GROUPS: &[Group] = &[
|
||||
Group::Part(&UI_EGUI, 1),
|
||||
Group::Part(&UI_EGUI, 2),
|
||||
Group::Targets(&[(Targets::Units, &["vectorcraft-engine"])]),
|
||||
Group::Targets(&[
|
||||
(Targets::All, &["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]),
|
||||
(Targets::Integration, &["vectorcraft-engine"]),
|
||||
]),
|
||||
Group::Targets(&[(Targets::All, &["vectorcraft-engine"])]),
|
||||
Group::Targets(&[(Targets::All, &["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"])]),
|
||||
Group::Rest,
|
||||
Group::Checks,
|
||||
];
|
||||
|
||||
/// A workspace member, as `cargo metadata` gives it.
|
||||
@@ -139,9 +135,9 @@ pub struct Member {
|
||||
|
||||
/// What one shard runs, with its crates resolved; a shard of a [`Split`] carries its part.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Shard {
|
||||
Tests(Vec<Run>, Option<Part>),
|
||||
Checks,
|
||||
pub struct Shard {
|
||||
pub runs: Vec<Run>,
|
||||
pub part: Option<Part>,
|
||||
}
|
||||
|
||||
/// One test run of a shard: the given targets of these crates.
|
||||
@@ -286,7 +282,7 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result<Vec<Shard>, String
|
||||
}
|
||||
vec![(Targets::All, split.crates)]
|
||||
}
|
||||
Group::Rest | Group::Checks => continue,
|
||||
Group::Rest => continue,
|
||||
};
|
||||
if lists.iter().all(|(_, names)| names.is_empty()) {
|
||||
return Err(format!("shard {} names no crates ({WHERE})", i + 1));
|
||||
@@ -326,25 +322,24 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result<Vec<Shard>, String
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, g)| match g {
|
||||
Group::Targets(lists) => Ok(Shard::Tests(
|
||||
lists
|
||||
Group::Targets(lists) => Ok(Shard {
|
||||
runs: lists
|
||||
.iter()
|
||||
.filter(|(_, names)| !names.is_empty())
|
||||
.map(|(targets, names)| Run { targets: *targets, crates: pick(&|m| names.contains(&m.name.as_str())) })
|
||||
.collect(),
|
||||
None,
|
||||
)),
|
||||
part: None,
|
||||
}),
|
||||
Group::Part(split, index) => {
|
||||
Ok(Shard::Tests(vec![Run::all(pick(&|m| split.crates.contains(&m.name.as_str())))], Some(Part { split, index: *index })))
|
||||
Ok(Shard { runs: vec![Run::all(pick(&|m| split.crates.contains(&m.name.as_str())))], part: Some(Part { split, index: *index }) })
|
||||
}
|
||||
Group::Rest => {
|
||||
let rest = pick(&|m| !named.contains_key(m.name.as_str()));
|
||||
if rest.is_empty() {
|
||||
return Err(format!("shard {} takes the remaining crates, and there are none ({WHERE})", i + 1));
|
||||
}
|
||||
Ok(Shard::Tests(vec![Run::all(rest)], None))
|
||||
Ok(Shard { runs: vec![Run::all(rest)], part: None })
|
||||
}
|
||||
Group::Checks => Ok(Shard::Checks),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -424,6 +419,13 @@ pub fn describe(runs: &[Run]) -> String {
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// The shards of this workspace after the checks in [`assign`] alone. A shard that runs its tests
|
||||
/// from an archive uses it: the archive's build already ran [`check`], and `cargo tree` would
|
||||
/// first download every dependency.
|
||||
pub fn assigned() -> Result<Vec<Shard>, String> {
|
||||
assign(GROUPS, &members(&crate::metadata()?)?)
|
||||
}
|
||||
|
||||
/// The shards of this workspace, after the checks in [`assign`] and [`feature_differences`].
|
||||
pub fn check() -> Result<Vec<Shard>, String> {
|
||||
// The shared gate runs only the shards that test a crate a pull request reaches, by these
|
||||
@@ -435,11 +437,9 @@ pub fn check() -> Result<Vec<Shard>, String> {
|
||||
let mut differences = Vec::new();
|
||||
for (i, shard) in shards.iter().enumerate() {
|
||||
// Each run is its own cargo command, so cargo resolves features over that run's crates.
|
||||
if let Shard::Tests(runs, _) = shard {
|
||||
for r in runs {
|
||||
let alone = tree_features(&tree(&select(&r.crates))?, &members);
|
||||
differences.extend(feature_differences(i + 1, &r.crates, &workspace, &alone));
|
||||
}
|
||||
for r in &shard.runs {
|
||||
let alone = tree_features(&tree(&select(&r.crates))?, &members);
|
||||
differences.extend(feature_differences(i + 1, &r.crates, &workspace, &alone));
|
||||
}
|
||||
}
|
||||
if !differences.is_empty() {
|
||||
@@ -475,7 +475,6 @@ fn workflow_members(workflow: &str) -> Result<(), String> {
|
||||
lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
Group::Rest => "(rest)".to_owned(),
|
||||
Group::Checks => "(always)".to_owned(),
|
||||
})
|
||||
.collect();
|
||||
let found = shard_members(workflow);
|
||||
@@ -491,119 +490,17 @@ fn workflow_members(workflow: &str) -> Result<(), String> {
|
||||
pub fn run() -> Result<Vec<Shard>, String> {
|
||||
let shards = check()?;
|
||||
for (i, shard) in shards.iter().enumerate() {
|
||||
match shard {
|
||||
Shard::Tests(runs, part) => {
|
||||
let share = part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default();
|
||||
println!("shard {}/{}: tests of {}{share}", i + 1, shards.len(), describe(runs))
|
||||
}
|
||||
Shard::Checks => println!("shard {}/{}: the other ci steps", i + 1, shards.len()),
|
||||
}
|
||||
let share = shard.part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default();
|
||||
println!("shard {}/{}: tests of {}{share}", i + 1, shards.len(), describe(&shard.runs))
|
||||
}
|
||||
println!("OK: every workspace member is tested on one shard, with the features `cargo test --workspace` gives it.");
|
||||
Ok(shards)
|
||||
}
|
||||
|
||||
/// The shard `cargo xtask ci warm` builds alone, as an index into [`GROUPS`], from the gate's
|
||||
/// `GATE_SHARD` and `GATE_SHARDS`: `None` (every shard) when neither is set. Setting only one,
|
||||
/// a value that is not a number, a count other than the number of shards, or a shard out of range
|
||||
/// is an error.
|
||||
pub fn warm_only(shard: Option<&str>, count: Option<&str>) -> Result<Option<usize>, String> {
|
||||
let (shard, count) = match (shard, count) {
|
||||
(None, None) => return Ok(None),
|
||||
(Some(shard), Some(count)) => (shard, count),
|
||||
_ => return Err("ci warm: GATE_SHARD and GATE_SHARDS are set together or not at all".into()),
|
||||
};
|
||||
let number =
|
||||
|key: &str, value: &str| -> Result<usize, String> { value.trim().parse().map_err(|_| format!("ci warm: {key} is `{value}`, not a number")) };
|
||||
let (shard, count) = (number("GATE_SHARD", shard)?, number("GATE_SHARDS", count)?);
|
||||
if count != GROUPS.len() {
|
||||
return Err(format!(
|
||||
"ci warm: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)",
|
||||
GROUPS.len()
|
||||
));
|
||||
}
|
||||
if !(1..=count).contains(&shard) {
|
||||
return Err(format!("ci warm: GATE_SHARD is {shard}, not 1 to {count}"));
|
||||
}
|
||||
Ok(Some(shard - 1))
|
||||
}
|
||||
|
||||
/// What `cargo xtask ci warm` builds of `shards`: the indices of the test shards whose tests it
|
||||
/// builds, and whether it runs the checks shard's builds. With `only` (from [`warm_only`]) it
|
||||
/// builds that shard alone, and without it every shard. A split's later parts build nothing: they
|
||||
/// build the same tests as part 1, whose leg puts them in the cache.
|
||||
pub fn warm_plan(shards: &[Shard], only: Option<usize>) -> (Vec<usize>, bool) {
|
||||
let mut tests = Vec::new();
|
||||
let mut checks = false;
|
||||
for (i, shard) in shards.iter().enumerate() {
|
||||
if only.is_some_and(|k| k != i) {
|
||||
continue;
|
||||
}
|
||||
match shard {
|
||||
Shard::Checks => checks = true,
|
||||
Shard::Tests(_, part) if part.is_some_and(|p| !p.is_first()) => {}
|
||||
Shard::Tests(..) => tests.push(i),
|
||||
}
|
||||
}
|
||||
(tests, checks)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn warm_builds_every_shard_unless_the_gate_names_one() {
|
||||
let n = GROUPS.len().to_string();
|
||||
assert_eq!(warm_only(None, None), Ok(None));
|
||||
assert_eq!(warm_only(Some("1"), Some(&n)), Ok(Some(0)));
|
||||
assert_eq!(warm_only(Some(&n), Some(&n)), Ok(Some(GROUPS.len() - 1)));
|
||||
for (shard, count) in [(Some("1"), None), (None, Some(n.as_str())), (Some("0"), Some(n.as_str())), (Some("x"), Some(n.as_str()))] {
|
||||
assert!(warm_only(shard, count).is_err(), "{shard:?} of {count:?}");
|
||||
}
|
||||
let past = (GROUPS.len() + 1).to_string();
|
||||
assert!(warm_only(Some(&past), Some(&n)).is_err());
|
||||
assert!(warm_only(Some("1"), Some(&past)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_builds_each_shard_of_the_plan() {
|
||||
let ws = [m("a"), m("b")];
|
||||
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(warm_plan(&shards, None), (vec![0, 2], true));
|
||||
assert_eq!(warm_plan(&shards, Some(0)), (vec![0], false));
|
||||
assert_eq!(warm_plan(&shards, Some(1)), (vec![], false));
|
||||
assert_eq!(warm_plan(&shards, Some(2)), (vec![2], false));
|
||||
assert_eq!(warm_plan(&shards, Some(3)), (vec![], true));
|
||||
// The real plan: every leg the gate names builds its own shard (a split's later part
|
||||
// builds nothing), and the legs together, like a full warm, build every crate's tests
|
||||
// once and the checks.
|
||||
let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap();
|
||||
let mut owned: Vec<&str> = real.iter().flat_map(owners).map(|(name, _)| name).collect();
|
||||
owned.sort_unstable();
|
||||
let (mut legs, mut leg_checks) = (Vec::new(), 0);
|
||||
for i in 0..GROUPS.len() {
|
||||
let n = GROUPS.len().to_string();
|
||||
let only = warm_only(Some(&(i + 1).to_string()), Some(&n)).unwrap();
|
||||
let (tests, checks) = warm_plan(&real, only);
|
||||
let want = match &real[i] {
|
||||
Shard::Checks => (vec![], true),
|
||||
Shard::Tests(_, Some(p)) if !p.is_first() => (vec![], false),
|
||||
Shard::Tests(..) => (vec![i], false),
|
||||
};
|
||||
assert_eq!((tests.clone(), checks), want, "shard {}", i + 1);
|
||||
legs.extend(tests);
|
||||
leg_checks += usize::from(checks);
|
||||
}
|
||||
let (tests, checks) = warm_plan(&real, None);
|
||||
assert!(checks);
|
||||
assert_eq!(leg_checks, 1);
|
||||
assert_eq!(tests, legs);
|
||||
let mut built: Vec<&str> = tests.iter().flat_map(|&i| crates(&real[i])).collect();
|
||||
built.sort_unstable();
|
||||
assert_eq!(built, owned);
|
||||
}
|
||||
|
||||
fn m(name: &str) -> Member {
|
||||
Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true }
|
||||
}
|
||||
@@ -626,20 +523,16 @@ mod tests {
|
||||
}
|
||||
|
||||
fn crates(shard: &Shard) -> Vec<&str> {
|
||||
match shard {
|
||||
Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| m.name.as_str())).collect(),
|
||||
Shard::Checks => Vec::new(),
|
||||
}
|
||||
shard.runs.iter().flat_map(|r| r.crates.iter().map(|m| m.name.as_str())).collect()
|
||||
}
|
||||
|
||||
/// Each crate a shard tests from the start, with the targets it runs: a part after the first
|
||||
/// runs a share of the same tests, so it is counted with part 1.
|
||||
fn owners(shard: &Shard) -> Vec<(&str, Targets)> {
|
||||
match shard {
|
||||
Shard::Tests(_, Some(p)) if !p.is_first() => Vec::new(),
|
||||
Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| (m.name.as_str(), r.targets))).collect(),
|
||||
Shard::Checks => Vec::new(),
|
||||
if shard.part.is_some_and(|p| !p.is_first()) {
|
||||
return Vec::new();
|
||||
}
|
||||
shard.runs.iter().flat_map(|r| r.crates.iter().map(|m| (m.name.as_str(), r.targets))).collect()
|
||||
}
|
||||
|
||||
/// The tests (binary ids and full names, in the order nextest lists them) that one `cargo nextest run` with
|
||||
@@ -685,9 +578,9 @@ mod tests {
|
||||
#[test]
|
||||
fn a_split_runs_on_its_parts_in_a_row() {
|
||||
let ws = [m("a"), m("b")];
|
||||
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["a"], vec!["a"], vec!["b"], vec![]]);
|
||||
assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("a")])], Some(Part { split: &SPLIT, index: 2 })));
|
||||
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap();
|
||||
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["a"], vec!["a"], vec!["b"]]);
|
||||
assert_eq!(shards[1], Shard { runs: vec![Run::all(vec![m("a")])], part: Some(Part { split: &SPLIT, index: 2 }) });
|
||||
let apart = assign(&[Group::Part(&SPLIT, 1), Group::Rest, Group::Part(&SPLIT, 2)], &ws).unwrap_err();
|
||||
assert!(apart.contains("not shards 1 to 2 in a row"), "{apart}");
|
||||
let missing = assign(&[Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap_err();
|
||||
@@ -755,9 +648,8 @@ mod tests {
|
||||
#[test]
|
||||
fn the_rest_shard_takes_every_crate_no_group_names() {
|
||||
let ws = [m("a"), m("b"), m("c"), m("d")];
|
||||
let shards = assign(&[Group::Targets(&[(Targets::All, &["c"])]), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["c"], vec!["a", "b", "d"], vec![]]);
|
||||
assert_eq!(shards[2], Shard::Checks);
|
||||
let shards = assign(&[Group::Targets(&[(Targets::All, &["c"])]), Group::Rest], &ws).unwrap();
|
||||
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["c"], vec!["a", "b", "d"]]);
|
||||
}
|
||||
|
||||
/// Every test target of `a`.
|
||||
@@ -768,18 +660,11 @@ mod tests {
|
||||
#[test]
|
||||
fn a_crate_s_units_and_integration_tests_run_on_two_shards() {
|
||||
let ws = [m("a"), m("b"), m("c")];
|
||||
let shards =
|
||||
assign(&[Group::Targets(&[UNITS]), Group::Targets(&[(Targets::All, &["b"]), INTEGRATION]), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(shards[0], Shard::Tests(vec![Run { targets: Targets::Units, crates: vec![m("a")] }], None));
|
||||
assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("b")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], None));
|
||||
let shards = assign(&[Group::Targets(&[UNITS]), Group::Targets(&[(Targets::All, &["b"]), INTEGRATION]), Group::Rest], &ws).unwrap();
|
||||
assert_eq!(shards[0], Shard { runs: vec![Run { targets: Targets::Units, crates: vec![m("a")] }], part: None });
|
||||
assert_eq!(shards[1], Shard { runs: vec![Run::all(vec![m("b")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], part: None });
|
||||
assert_eq!(crates(&shards[2]), ["c"]);
|
||||
assert_eq!(
|
||||
unit_crates(match &shards[1] {
|
||||
Shard::Tests(r, _) => r,
|
||||
Shard::Checks => panic!("shard 2 is a test shard"),
|
||||
}),
|
||||
[m("b")]
|
||||
);
|
||||
assert_eq!(unit_crates(&shards[1].runs), [m("b")]);
|
||||
let half = assign(&[Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err();
|
||||
assert!(half.contains("no shard runs its integration tests"), "{half}");
|
||||
let other_half = assign(&[Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err();
|
||||
@@ -833,7 +718,6 @@ mod tests {
|
||||
"`{name}` runs {targets:?}, not each test target once"
|
||||
);
|
||||
}
|
||||
assert_eq!(shards.iter().filter(|s| **s == Shard::Checks).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user