Skip to content

Commit 9afb870

Browse files
max-sixtyclaude
andcommitted
Fall back to all tests when selection can't be precise
`cargo affected run` is now a strict superset of `cargo nextest run`: when the framework can't compute a precise affected-test selection it emits a stderr notice and runs every test, rather than bailing or no-opping. Three branches in `src/run.rs` change behavior to match the existing fingerprint-mismatch fallback: - no coverage data at all (was: "run collect first" + return Ok(0)) - coverage data exists but `collect_sha` is missing (was: bail!) - `collect_sha` not reachable from HEAD / Diverged (was: bail!) Motivated by CI: when a PR job restores a cached DB whose `collect_sha` is no longer reachable from the merge-base (because main moved after the PR was opened), running every test with a notice is more useful than a hard error. Co-Authored-By: Claude <[email protected]>
1 parent 4e3ec4c commit 9afb870

4 files changed

Lines changed: 154 additions & 12 deletions

File tree

‎README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ cargo affected clean # wipe the coverage cache
3636
`collect` last ran. Recollect periodically — every committed change since
3737
the last collect adds to the diff and broadens selection.
3838

39+
When `run` can't compute a precise selection — no coverage yet, environment
40+
fingerprint changed, missing or unreachable `collect_sha` — it falls back to
41+
running every test with a stderr notice. `cargo affected run` is therefore a
42+
strict superset of `cargo nextest run`: always at least as safe.
43+
3944
## How it works
4045

4146
`collect`:

‎src/run.rs‎

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,17 @@
55
//! tests via `cargo nextest run`. Also lists tests via nextest to catch tests
66
//! added since the last `collect` — those have no coverage data, so they're
77
//! always selected. nextest is required — no `cargo test` fallback.
8+
//!
9+
//! When selection can't be computed precisely (no coverage yet, fingerprint
10+
//! changed, missing `collect_sha`, or `collect_sha` not reachable from HEAD),
11+
//! `run` falls back to running every test with an explanatory stderr notice.
12+
//! That makes `cargo affected run` a strict superset of `cargo nextest run` —
13+
//! always at least as safe.
814
915
use std::path::Path;
1016
use std::process::Command;
1117

12-
use anyhow::{bail, Context, Result};
18+
use anyhow::{Context, Result};
1319

1420
use crate::collect::{nextest_filter_expr, require_nextest};
1521
use crate::db::{warn_untracked_rs_files, Db, TestId};
@@ -20,6 +26,11 @@ use crate::project::{
2026
use crate::selection;
2127

2228
/// Entry point for `cargo affected run`. Returns the exit code to propagate.
29+
///
30+
/// Falls back to running all tests (with an explanatory stderr notice) in
31+
/// every case where a precise affected-test selection can't be computed —
32+
/// no coverage data, fingerprint mismatch, missing `collect_sha`, or
33+
/// `collect_sha` not reachable from HEAD.
2334
pub fn run(all: bool, verbose: bool, nextest_args: &[String]) -> Result<i32> {
2435
let project = find_project_root()?;
2536
let project_root = &project.workspace_root;
@@ -36,18 +47,26 @@ pub fn run(all: bool, verbose: bool, nextest_args: &[String]) -> Result<i32> {
3647
if db.test_count(&env_fingerprint)? == 0 {
3748
if db.has_any_coverage()? {
3849
eprintln!(
39-
"coverage database has no data for the current environment \
40-
(Cargo.lock, Cargo.toml, rustc version, or build flags changed) — running all tests"
50+
"note: no coverage data for the current environment \
51+
(Cargo.lock, Cargo.toml, rustc version, or build flags changed) — \
52+
running all tests; run `cargo affected collect` to refresh"
53+
);
54+
} else {
55+
eprintln!(
56+
"note: no coverage data yet — running all tests; \
57+
run `cargo affected collect` to enable selection"
4158
);
42-
return run_tests(project_root, None, nextest_args);
4359
}
44-
eprintln!("no coverage data yet — run `cargo affected collect` first");
45-
return Ok(0);
60+
return run_tests(project_root, None, nextest_args);
4661
}
4762

48-
let collect_sha = db
49-
.collect_sha(&env_fingerprint)?
50-
.context("coverage data exists but is missing collect_sha — run `cargo affected collect`")?;
63+
let Some(collect_sha) = db.collect_sha(&env_fingerprint)? else {
64+
eprintln!(
65+
"note: coverage data exists but is missing collect_sha — running all tests; \
66+
run `cargo affected collect` to re-anchor"
67+
);
68+
return run_tests(project_root, None, nextest_args);
69+
};
5170

5271
match relation_to_head(project_root, &collect_sha)? {
5372
ShaRelation::Equal => {}
@@ -59,11 +78,12 @@ pub fn run(all: bool, verbose: bool, nextest_args: &[String]) -> Result<i32> {
5978
);
6079
}
6180
ShaRelation::Diverged => {
62-
bail!(
63-
"collect_sha {collect_sha} is not reachable from HEAD \
64-
(rebased or branch switched) — \
81+
eprintln!(
82+
"note: collect_sha {collect_sha} not reachable from HEAD \
83+
(rebased or branch switched) — running all tests; \
6584
run `cargo affected collect` to re-anchor"
6685
);
86+
return run_tests(project_root, None, nextest_args);
6787
}
6888
}
6989

‎tests/functional/fallback.rs‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
//! Fallback-to-all-tests behavior for `cargo affected run`.
2+
//!
3+
//! `run` aims to be a strict superset of `cargo nextest run`: when the
4+
//! framework can't compute a precise affected-test selection, it falls back
5+
//! to running every test with a stderr notice rather than bailing or
6+
//! no-opping. This file pins the behavioral promise for the two cases that
7+
//! are easy to set up integration-style — no coverage data at all, and a
8+
//! `collect_sha` that's no longer reachable from HEAD (drift).
9+
//!
10+
//! `status` keeps the bail behavior for drift (see `drift.rs`); only `run`
11+
//! falls back, because `run`'s job is to actually produce CI signal.
12+
13+
use crate::{
14+
cargo_affected, git, git_head, init_git_with_initial_commit, write_two_module_project,
15+
};
16+
17+
#[test]
18+
fn run_falls_back_to_all_when_no_coverage_data() {
19+
let tmp = tempfile::tempdir().unwrap();
20+
let dir = tmp.path();
21+
write_two_module_project(dir, "sample_fallback_no_coverage");
22+
init_git_with_initial_commit(dir);
23+
24+
// No `cargo affected collect` — DB is empty (or absent). `run` must
25+
// still succeed by running every test, with a stderr notice explaining
26+
// why selection wasn't computed.
27+
let run = cargo_affected(dir, &["affected", "run"]);
28+
assert!(
29+
run.status.success(),
30+
"run with no coverage should succeed by running all: stderr=\n{}\nstdout=\n{}",
31+
String::from_utf8_lossy(&run.stderr),
32+
String::from_utf8_lossy(&run.stdout),
33+
);
34+
35+
let combined = format!(
36+
"{}{}",
37+
String::from_utf8_lossy(&run.stderr),
38+
String::from_utf8_lossy(&run.stdout)
39+
);
40+
41+
// The fallback notice — phrased as "note: ..." per the existing notice
42+
// style in run.rs. Match on the "no coverage data yet" key phrase.
43+
assert!(
44+
combined.contains("no coverage data yet") && combined.contains("running all tests"),
45+
"expected fallback notice, got:\n{combined}"
46+
);
47+
// nextest actually ran every test in the sample project (PASS lines for
48+
// each of test_add / test_multiply / test_greet). One PASS would be
49+
// ambiguous (could be the old narrow-selection path), so check all
50+
// three to confirm we really ran the full suite.
51+
for t in ["test_add", "test_multiply", "test_greet"] {
52+
assert!(
53+
combined.contains("PASS") && combined.contains(t),
54+
"expected nextest to PASS {t}, got:\n{combined}"
55+
);
56+
}
57+
}
58+
59+
#[test]
60+
fn run_falls_back_to_all_when_collect_sha_diverged() {
61+
let tmp = tempfile::tempdir().unwrap();
62+
let dir = tmp.path();
63+
write_two_module_project(dir, "sample_fallback_diverged");
64+
init_git_with_initial_commit(dir);
65+
let init_sha = git_head(dir);
66+
67+
// Add a second commit so we have something to collect against and a
68+
// commit to reset back from. `collect` runs at this second commit, so
69+
// its sha becomes the recorded `collect_sha`.
70+
std::fs::write(dir.join("src/extra.rs"), "pub fn extra() -> i32 { 1 }\n").unwrap();
71+
let lib_path = dir.join("src/lib.rs");
72+
let lib = std::fs::read_to_string(&lib_path).unwrap();
73+
std::fs::write(&lib_path, format!("{lib}pub mod extra;\n")).unwrap();
74+
git(dir, &["add", "."]);
75+
git(dir, &["commit", "-q", "-m", "add extra module"]);
76+
let collect_commit = git_head(dir);
77+
assert_ne!(init_sha, collect_commit);
78+
79+
let collect = cargo_affected(dir, &["affected", "collect"]);
80+
assert!(
81+
collect.status.success(),
82+
"collect failed: {}",
83+
String::from_utf8_lossy(&collect.stderr)
84+
);
85+
86+
// Reset HEAD back to the initial commit. The collect_sha is now an
87+
// orphan — present in the repo but not an ancestor of HEAD —
88+
// matching `ShaRelation::Diverged`.
89+
git(dir, &["reset", "--hard", "-q", &init_sha]);
90+
91+
let run = cargo_affected(dir, &["affected", "run"]);
92+
assert!(
93+
run.status.success(),
94+
"run on diverged collect_sha should succeed by running all: stderr=\n{}\nstdout=\n{}",
95+
String::from_utf8_lossy(&run.stderr),
96+
String::from_utf8_lossy(&run.stdout),
97+
);
98+
99+
let combined = format!(
100+
"{}{}",
101+
String::from_utf8_lossy(&run.stderr),
102+
String::from_utf8_lossy(&run.stdout)
103+
);
104+
105+
assert!(
106+
combined.contains("not reachable from HEAD") && combined.contains("running all tests"),
107+
"expected diverged-fallback notice, got:\n{combined}"
108+
);
109+
// The whole suite ran — same three-test check as the no-coverage case.
110+
for t in ["test_add", "test_multiply", "test_greet"] {
111+
assert!(
112+
combined.contains("PASS") && combined.contains(t),
113+
"expected nextest to PASS {t}, got:\n{combined}"
114+
);
115+
}
116+
}

‎tests/functional/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
2424
mod clean;
2525
mod drift;
26+
mod fallback;
2627
mod fingerprint;
2728
mod narrowing;
2829
mod new_test;

0 commit comments

Comments
 (0)