diff --git a/docs/coder-loop.md b/docs/coder-loop.md index c3e26ff32..c5d4c2995 100644 --- a/docs/coder-loop.md +++ b/docs/coder-loop.md @@ -130,7 +130,12 @@ The causes were in the loop, not only in prompt wording: Each new or changed test runs in the sandbox with and without the change (`habits_check`). A test the runner finds nothing in goes back to the - coder, and the coder quotes the run's output in its Evidence. End-to-end code + coder, and the coder quotes the run's output in its Evidence. + These runs install through CI's job for the test files. Without one, a + workspace member installs from the workspace root. They have a budget + of their own: a short step owes them to a fresh step, which runs them + before any other check. How many ran, and why the rest didn't, is + counted on the run and in the pull request (`incidents::tq_tests_run`). End-to-end code against another company's page uses only what a probe observed (#734). A proof fix round that answers a gap by looking (a query, a page, a check diff --git a/docs/incidents/tq_tests_run.md b/docs/incidents/tq_tests_run.md new file mode 100644 index 000000000..07aa55d9c --- /dev/null +++ b/docs/incidents/tq_tests_run.md @@ -0,0 +1,22 @@ +# tq. `tq_tests_run` + +**What happened:** Across the 53 most recent runs, 17 had new or changed tests to run with and without the change. Not one of them ran both ways: + +- **6 runs: the install failed in the sandbox.** All six were in one pnpm workspace. The test files sat in a workspace member (`apps/web`) whose lockfile is the workspace root's, and the sandbox installed the member on its own: `cd 'apps/web' && pnpm install --ignore-workspace --frozen-lockfile`. That folder has no lockfile, so pnpm stopped with `ERR_PNPM_NO_LOCKFILE` before any test ran, on every run. The run's CI install (cached per manifest blob) was never used for these runs, and the failure didn't say why. One of the runs also listed a Playwright spec as a unit test. +- **7 runs: no step had the time.** The check asked once for a step of its own. The fresh step ran every other check first (the proof, the link checks, the new-feature rules, the live probes, the scope ledger), so it reached the sandbox runs with less than their 760 seconds left, and its one request was already spent. One run resumed for the runs at 16:00:42 and only reached them at 16:05:42. +- **2 runs: CI's test command wasn't read.** A data pipeline's CI runs a `python "$t"` loop over its tests. Its fixture JSON files were also listed as tests, and one file without a command stopped every file from running. +- **2 runs: no test to run.** One change was only tests; the other changed no test file. + +**The guarantee:** +- **Install the way CI does.** The sandbox runs use CI's job for the changed files: its install lines in order, its Node and pnpm versions, through the cached environment. Without one, a workspace member installs from the workspace root, falling back to the member and what it depends on. A failed install says why, with its error lines. +- **Unit tests only.** An end-to-end spec and test data (fixtures, snapshots) are never run as unit tests. +- **A budget of their own.** When a step is short, the runs are owed to a fresh step. That step runs them first, before any other check, and records the result for the head. A run asks for such a step up to `MAX_PROOF_STEPS` times; only past that are the tests recorded as not run. +- **Read the test command.** Each file runs with CI's test step narrowed to it. One function narrows pytest, unittest, Vitest, Jest, `go test` and `cargo test`, and package scripts and make targets are read through to their runner. When CI's step can't be narrowed, the file's own package's test script runs it. A file with no command doesn't stop the others. +- **Counted.** Whether the tests ran, and why not, is recorded on the run's checks (`tests_ran`), written to its progress notes, and shown in the pull request. + +**Where it's enforced:** +- `common::e2e::test_package::workspace_member` and `install_cmd`; +- `common::test_env` (`narrow`, `resolve_scripts`, `package_test_command`, `INSTALL_FAILED`); +- `habits_check::bench_plan`, `install_failure`, `proof_time` and `run_owed`; +- the ledger's `proof_runs` and `proof_owed`; +- `habits_check::TestsRan`. diff --git a/services/common/src/e2e/test_package.rs b/services/common/src/e2e/test_package.rs index da3ffdb46..20edecc27 100644 --- a/services/common/src/e2e/test_package.rs +++ b/services/common/src/e2e/test_package.rs @@ -224,7 +224,9 @@ pub fn packages_outside( out.push(TestPackage { dir: dir.clone(), manager: lock.map(|(_, m)| *m).unwrap_or(Manager::Npm), - lockfile: lock.map(|(n, _)| n.to_string()), + // From the repository root, as `package_of` names it: a lockfile + // outside the package's folder is a workspace's. + lockfile: lock.map(|(n, _)| join(&dir, n)), has_tsconfig: tree.iter().any(|p| *p == join(&dir, "tsconfig.json")), lint: has_eslint(tree, &dir, &pj), runner: runner_of(&pj), @@ -316,14 +318,65 @@ pub fn ensure_manager(m: Manager) -> &'static str { } } -/// Installs the package's dependencies on their own, never the parent -/// workspace's, after making its manager available. +/// Whether the package is a member of a workspace whose lockfile sits at the +/// workspace's root (`lockfile` names a file outside the package's folder): +/// its dependencies install from that root, the way its CI installs them. +/// A package with its own lockfile, or none, installs on its own. +pub fn workspace_member(p: &TestPackage) -> bool { + let dir = p.dir.trim_end_matches('/'); + p.lockfile + .as_deref() + .is_some_and(|l| !dir.is_empty() && dir != "." && !l.starts_with(&format!("{dir}/"))) +} + +/// The folder the install runs in: the workspace's root for a member +/// ([`workspace_member`]), else the package's own. +pub fn install_dir(p: &TestPackage) -> String { + if workspace_member(p) { + p.lockfile + .as_deref() + .map(|l| parent(l).to_string()) + .filter(|d| !d.is_empty()) + .unwrap_or_else(|| ".".into()) + } else { + p.dir.clone() + } +} + +/// Installs the package's dependencies, after making its manager +/// available: a package on its own never reaches for the parent +/// workspace's; a workspace member installs the workspace from its root +/// lockfile (run in [`install_dir`]). A member's install that fails as a +/// whole falls back to the narrowest one that still runs its tests: the +/// member and what it depends on. +/// +/// Six pull requests' new tests never ran because a member of a pnpm +/// workspace was installed on its own (`cd apps/web && pnpm install +/// --ignore-workspace --frozen-lockfile`): its folder has no lockfile, so +/// pnpm stopped with `ERR_PNPM_NO_LOCKFILE` before any test. pub fn install_cmd(p: &TestPackage) -> String { format!("{}{}", ensure_manager(p.manager), install_only(p)) } fn install_only(p: &TestPackage) -> String { let frozen = p.lockfile.is_some(); + if workspace_member(p) { + let member = format!("./{}", p.dir.trim_start_matches("./")); + return match p.manager { + Manager::Npm => format!( + "(npm ci --no-audit --no-fund || npm ci --no-audit --no-fund --workspace {})", + q(&member).unwrap_or_else(|| "'.'".into()) + ), + Manager::Pnpm => match q(&format!("{member}...")) { + Some(f) => { + format!("(pnpm install --frozen-lockfile || pnpm install --frozen-lockfile --filter {f})") + } + None => "pnpm install --frozen-lockfile".into(), + }, + Manager::Yarn => "yarn install --ignore-engines --frozen-lockfile".into(), + Manager::Bun => "bun install --frozen-lockfile".into(), + }; + } match p.manager { Manager::Npm if frozen => "npm ci --no-audit --no-fund --workspaces=false".into(), Manager::Npm => "npm install --no-audit --no-fund --workspaces=false".into(), @@ -362,7 +415,7 @@ pub fn check_steps(p: &TestPackage) -> Option> { let dir = q(&p.dir)?; let mut steps = vec![Step { kind: "install", - cmd: format!("cd {dir} && {}", install_cmd(p)), + cmd: format!("cd {} && {}", q(&install_dir(p))?, install_cmd(p)), }]; if p.has_tsconfig { steps.push(Step { @@ -697,7 +750,7 @@ mod tests { let mut p = TestPackage { dir: "tests/e2e".into(), manager: Manager::Pnpm, - lockfile: Some("pnpm-lock.yaml".into()), + lockfile: Some("tests/e2e/pnpm-lock.yaml".into()), has_tsconfig: false, lint: false, runner: None, @@ -710,6 +763,7 @@ mod tests { ensure_manager(Manager::Pnpm) ) ); + assert_eq!(install_dir(&p), "tests/e2e"); p.manager = Manager::Yarn; assert!(install_cmd(&p).contains("--frozen-lockfile")); p.manager = Manager::Npm; @@ -722,6 +776,62 @@ mod tests { assert!(check_steps(&p).is_none()); } + /// A pnpm workspace's member (`apps/web`, lockfile at the root): it + /// installs the workspace from the root, never on its own, where pnpm + /// stops with `ERR_PNPM_NO_LOCKFILE`. + #[test] + fn a_workspace_member_installs_from_the_workspace_root() { + let t = tree(&[ + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "apps/web/package.json", + "apps/web/src/test/a.test.ts", + "e2e/package.json", + "e2e/pnpm-lock.yaml", + "e2e/tests/a.spec.ts", + ]); + let web = package_of(&t, "apps/web/src/test/a.test.ts", &|_| None).unwrap(); + assert_eq!(web.dir, "apps/web"); + assert_eq!(web.lockfile.as_deref(), Some("pnpm-lock.yaml")); + assert!(workspace_member(&web)); + assert_eq!(install_dir(&web), "."); + let steps = check_steps(&web).unwrap(); + assert!(steps[0].cmd.starts_with("cd '.' && "), "{}", steps[0].cmd); + assert!( + !steps[0].cmd.contains("--ignore-workspace"), + "{}", + steps[0].cmd + ); + assert!(steps[0].cmd.contains("pnpm install --frozen-lockfile")); + // The narrowest fallback: the member and what it depends on. + assert!(steps[0].cmd.contains("--filter './apps/web...'")); + // Type-check and lint still run in the member's folder. + assert!(steps + .iter() + .skip(1) + .all(|s| s.cmd.starts_with("cd 'apps/web'"))); + // A package with its own lockfile stays on its own. + let e2e = package_of(&t, "e2e/tests/a.spec.ts", &|_| None).unwrap(); + assert!(!workspace_member(&e2e)); + assert_eq!(install_dir(&e2e), "e2e"); + assert!(check_steps(&e2e).unwrap()[0] + .cmd + .contains("pnpm install --ignore-workspace --frozen-lockfile")); + // As `packages_outside` names it, the same. + let out = packages_outside(&t, &["e2e/tests/a.spec.ts".into()], &[], &|_| None); + assert_eq!(out[0].lockfile.as_deref(), Some("e2e/pnpm-lock.yaml")); + assert!(!workspace_member(&out[0])); + // The root package installs where it is. + let root = package_of( + &tree(&["package.json", "pnpm-lock.yaml", "a.test.ts"]), + "a.test.ts", + &|_| None, + ) + .unwrap(); + assert!(!workspace_member(&root)); + } + #[test] fn repeat_commands_use_the_runner_and_the_target() { let mut p = TestPackage { diff --git a/services/common/src/test_env.rs b/services/common/src/test_env.rs index 1271837c5..bbad89fc9 100644 --- a/services/common/src/test_env.rs +++ b/services/common/src/test_env.rs @@ -35,6 +35,9 @@ pub const ENV_ROOT: &str = "/tmp/coderhelm-env"; pub const RESTORED: &str = "===CODERHELM_ENV_RESTORED==="; pub const INSTALLED: &str = "===CODERHELM_ENV_INSTALLED==="; pub const SAVED: &str = "===CODERHELM_ENV_SAVED==="; +/// Printed with the install's exit code when CI's install failed: what +/// follows ran without it, so a test result after it says nothing. +pub const INSTALL_FAILED: &str = "===CODERHELM_ENV_INSTALL_FAILED==="; /// The language whose packages the install fills. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -57,6 +60,8 @@ pub struct TestEnv { pub kind: Kind, pub python: String, pub node: String, + /// The pnpm version CI's `pnpm/action-setup` pins ("" when none). + pub pnpm: String, /// Plain `NAME=value` settings of the job (never an expression). pub env: Vec<(String, String)>, pub install: Vec, @@ -277,6 +282,9 @@ pub fn from_workflows_for( if uses.starts_with("actions/setup-node") { env.node = s(step.get("with").and_then(|w| w.get("node-version"))); } + if uses.starts_with("pnpm/action-setup") { + env.pnpm = s(step.get("with").and_then(|w| w.get("version"))); + } let run = s(step.get("run")); if run.is_empty() || run.contains("${{") { continue; @@ -433,6 +441,307 @@ fn quote(s: &str) -> String { format!("'{}'", s.replace('\'', "'\\''")) } +/// Whether a path is safe to put on a command line as it is. +fn safe_path(p: &str) -> bool { + !p.is_empty() + && !p.starts_with('-') + && p.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '/')) + && !p.contains("..") +} + +/// A test command narrowed to one test file (`file`, relative to the folder +/// the command runs in), or `None` when its runner can't take one. The one +/// place CoderHelm narrows a runner: pytest and `python -m unittest` take +/// the path, Vitest and Jest take it as a filter (they print "no test files +/// found" when it matches nothing, never a pass), `go test` takes the +/// file's package, `cargo test` an integration test's target. A runner's +/// own flags after it are dropped with the rest of the line. +pub fn narrow(cmd: &str, file: &str) -> Option { + if !safe_path(file) { + return None; + } + let words: Vec<&str> = cmd.split_whitespace().collect(); + let low: Vec = words.iter().map(|w| w.to_ascii_lowercase()).collect(); + // Up to and including word `i`, never across a `&&`, `;` or `|`. + let prefix = |i: usize| -> String { + let start = words[..i] + .iter() + .rposition(|w| matches!(*w, "&&" | ";" | "||" | "|")) + .map_or(0, |p| p + 1); + words[start..=i].join(" ") + }; + for (i, w) in low.iter().enumerate() { + let w = w.trim_matches(['"', '\'']); + let base = w.rsplit('/').next().unwrap_or(w); + if base == "pytest" || (base == "unittest" && i > 0 && low[i - 1] == "-m") { + return Some(format!("{} {file}", prefix(i))); + } + if base == "vitest" { + let run = low.get(i + 1).is_some_and(|n| n == "run"); + let end = if run { i + 1 } else { i }; + let run = if run { "" } else { " run" }; + return Some(format!("{}{run} {file}", prefix(end))); + } + if base == "jest" { + return Some(format!("{} {file}", prefix(i))); + } + if w == "go" && low.get(i + 1).is_some_and(|n| n == "test") && file.ends_with("_test.go") { + let dir = file.rsplit_once('/').map_or(".", |(d, _)| d); + let pre = prefix(i + 1); + return Some(format!("{pre} ./{dir}/")); + } + if w == "cargo" && low.get(i + 1).is_some_and(|n| n == "test") { + // An integration test, `tests/.rs`, is a target of its own. + let name = file + .strip_prefix("tests/") + .and_then(|n| n.strip_suffix(".rs")) + .filter(|n| !n.contains('/'))?; + return Some(format!("{} --test {name}", prefix(i + 1))); + } + } + None +} + +/// What a package script or a make target runs, from the manifests: +/// `npm test`, `npm run `, `pnpm [--filter ] [run] `, `yarn +/// [workspace ] `, `bun run `, `make `, run in `dir`. +/// `(folder, command)` with the command the script or target holds, so a +/// runner in it can be narrowed. `read` gives a file's text; `tree` finds a +/// workspace package by name. `None` when it is no script call or the +/// script can't be read. +pub fn resolve_script( + line: &str, + dir: &str, + tree: &[String], + read: &dyn Fn(&str) -> Option, +) -> Option<(String, String)> { + resolve_depth(line, dir, tree, read, 0) +} + +fn package_dir_named( + tree: &[String], + read: &dyn Fn(&str) -> Option, + name: &str, +) -> Option { + let name = name.trim_matches(['"', '\'']); + if name.starts_with("./") || name.contains('/') && !name.starts_with('@') { + return Some( + name.trim_start_matches("./") + .trim_end_matches('/') + .to_string(), + ); + } + tree.iter() + .filter(|p| *p == "package.json" || p.ends_with("/package.json")) + .filter(|p| !p.contains("node_modules/")) + .find(|p| { + read(p) + .and_then(|t| serde_json::from_str::(&t).ok()) + .is_some_and(|v| v["name"].as_str() == Some(name)) + }) + .map(|p| { + p.trim_end_matches("package.json") + .trim_end_matches('/') + .to_string() + }) +} + +fn resolve_depth( + line: &str, + dir: &str, + tree: &[String], + read: &dyn Fn(&str) -> Option, + depth: u8, +) -> Option<(String, String)> { + if depth > 3 { + return None; + } + let words: Vec<&str> = line.split_whitespace().collect(); + let (tool, rest) = words.split_first()?; + let mut at = dir.to_string(); + let mut args: Vec<&str> = Vec::new(); + let mut i = 0; + while i < rest.len() { + let w = rest[i]; + match (*tool, w) { + ("pnpm", "--filter" | "-F") | ("npm", "--workspace" | "-w") => { + at = package_dir_named(tree, read, rest.get(i + 1)?)?; + i += 2; + continue; + } + ("pnpm" | "npm" | "yarn", "-C" | "--dir" | "--prefix" | "--cwd") | ("make", "-C") => { + let d = rest + .get(i + 1)? + .trim_matches(['"', '\'']) + .trim_end_matches('/'); + at = join(&at, d); + i += 2; + continue; + } + ("yarn", "workspace") => { + at = package_dir_named(tree, read, rest.get(i + 1)?)?; + i += 2; + continue; + } + _ if w.starts_with("--filter=") && *tool == "pnpm" => { + at = package_dir_named(tree, read, &w["--filter=".len()..])?; + } + _ if w.starts_with('-') => {} + _ => args.push(w), + } + i += 1; + } + let script = match (*tool, args.as_slice()) { + ("make", [target, ..]) => { + let mk = read(&join(&at, "Makefile"))?; + let recipe = make_recipe(&mk, target)?; + return resolve_depth(&recipe, &at, tree, read, depth + 1).or(Some((at, recipe))); + } + ("make", []) => return None, + ("npm" | "pnpm" | "yarn" | "bun", ["run" | "run-script", s, ..]) => s.to_string(), + ("npm" | "pnpm" | "yarn", ["test" | "t", ..]) => "test".to_string(), + ("pnpm" | "yarn", [s, ..]) + if !matches!(*s, "install" | "add" | "exec" | "dlx" | "i" | "ci" | "x") => + { + s.to_string() + } + _ => return None, + }; + let pj = read(&join(&at, "package.json"))?; + let v: serde_json::Value = serde_json::from_str(&pj).ok()?; + let body = v["scripts"][script.as_str()].as_str()?.trim().to_string(); + if body.is_empty() { + return None; + } + resolve_depth(&body, &at, tree, read, depth + 1).or(Some((at, body))) +} + +/// A script's command run from a shell: a Node runner a package script +/// finds in `node_modules/.bin` (`vitest`, `jest`) goes through `npx`. +fn via_bin(cmd: &str) -> String { + let first = cmd.split_whitespace().next().unwrap_or(""); + if matches!( + first, + "vitest" | "jest" | "mocha" | "ava" | "tsx" | "ts-node" + ) { + format!("npx --no-install {cmd}") + } else { + cmd.to_string() + } +} + +fn in_folder(at: &str, cmd: &str) -> String { + if at.is_empty() || at == "." { + cmd.to_string() + } else { + format!("(cd {at} && {cmd})") + } +} + +/// The first recipe line of `target` in a Makefile that runs a check, its +/// `@`/`-` prefix dropped. +fn make_recipe(makefile: &str, target: &str) -> Option { + let mut lines = makefile.lines(); + while let Some(l) = lines.next() { + let Some((name, _)) = l.split_once(':') else { + continue; + }; + if l.starts_with('\t') || name.split_whitespace().all(|n| n != target) { + continue; + } + for r in lines.by_ref() { + if !r.starts_with('\t') { + if r.trim().is_empty() { + continue; + } + break; + } + let r = r.trim().trim_start_matches(['@', '-']).trim(); + let says = matches!( + r.split_whitespace().next(), + Some("echo" | "printf" | "true") + ); + if !says && crate::ci_cover::is_check_command(r) { + return Some(r.to_string()); + } + } + return None; + } + None +} + +/// The files [`TestEnv::resolve_scripts`] and [`package_test_command`] may +/// read: the manifests and Makefiles of the folders the test steps run in, +/// the workspace's package manifests (a `--filter` names a package), and +/// each test file's nearest manifest. At most 40. +pub fn script_files(env: Option<&TestEnv>, tree: &[String], files: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + let mut add = |p: String| { + if tree.contains(&p) && !out.contains(&p) && out.len() < 40 { + out.push(p); + } + }; + if let Some(e) = env { + let mut dirs = vec![e.dir.clone()]; + dirs.extend(e.test.iter().map(|t| unwrap_cd(t).0)); + for d in dirs { + add(join(&d, "package.json")); + add(join(&d, "Makefile")); + } + } + for f in files { + if let Some(d) = crate::e2e::test_package::package_dir(tree, f) { + add(join(&d, "package.json")); + } + } + for p in tree + .iter() + .filter(|p| p.ends_with("/package.json") && !p.contains("node_modules/")) + { + add(p.clone()); + } + out +} + +/// The test file run by its own package's test script, narrowed to it: the +/// narrowest command that still runs it when CI's test step can't be +/// narrowed (a `turbo` or a root script running every package). `None` +/// when the package has no test script with a runner that takes a file. +pub fn package_test_command( + file: &str, + tree: &[String], + read: &dyn Fn(&str) -> Option, +) -> Option { + let dir = crate::e2e::test_package::package_dir(tree, file)?; + let pj = read(&join(&dir, "package.json"))?; + let v: serde_json::Value = serde_json::from_str(&pj).ok()?; + let rel = if dir.is_empty() { + file + } else { + file.strip_prefix(&format!("{dir}/"))? + }; + for script in ["test:unit", "test:run", "test"] { + let Some(body) = v["scripts"][script].as_str() else { + continue; + }; + let (at, body) = + resolve_depth(body, &dir, tree, read, 1).unwrap_or((dir.clone(), body.to_string())); + let rel = if at == dir { + rel.to_string() + } else { + match file.strip_prefix(&format!("{at}/")) { + Some(r) => r.to_string(), + None => continue, + } + }; + if let Some(c) = narrow(&via_bin(&body), &rel) { + return Some(in_folder(&at, &c)); + } + } + None +} + impl TestEnv { /// Whether this is another package's job for `focus` (the files a run /// changes): its tests run in a folder none of them is in. @@ -449,6 +758,29 @@ impl TestEnv { .any(|f| f.trim_start_matches("./").starts_with(&format!("{dir}/"))) } + /// Each test step that calls a package script or a make target + /// (`pnpm --filter web test`, `npm run test:unit`, `make test`) put as + /// the command the script holds, in its folder, so its runner can be + /// narrowed to one file ([`Self::file_command`]). `read` gives the + /// manifests' text ([`script_files`]). + pub fn resolve_scripts(&mut self, tree: &[String], read: &dyn Fn(&str) -> Option) { + for line in self.test.iter_mut() { + let (dir, cmd) = unwrap_cd(line); + let dir = if dir.is_empty() { + self.dir.clone() + } else { + dir + }; + if let Some((at, body)) = resolve_script(&cmd, &dir, tree, read) { + let at = at + .strip_prefix(&format!("{}/", self.dir)) + .map(str::to_string) + .unwrap_or(if at == self.dir { String::new() } else { at }); + *line = in_folder(&at, &via_bin(&body)); + } + } + } + /// The install's name: its steps, versions and the manifests' blob ids /// (`shas`: `(path, blob sha)` from the tree at the head). pub fn fingerprint(&self, shas: &[(String, String)]) -> String { @@ -456,6 +788,7 @@ impl TestEnv { h.update(self.dir.as_bytes()); h.update(self.python.as_bytes()); h.update(self.node.as_bytes()); + h.update(self.pnpm.as_bytes()); for l in &self.install { h.update(l.as_bytes()); h.update(b"\n"); @@ -509,6 +842,24 @@ impl TestEnv { quote(&self.node) )); } + // The package manager CI sets up with an action (no `run` + // line installs it), at the version it pins, before any + // install line calls it. + let all = format!("{} {}", self.install.join(" "), self.test.join(" ")); + for (tool, pinned) in [("pnpm", &self.pnpm), ("yarn", &String::new())] { + if !all.split_whitespace().any(|w| w == tool) { + continue; + } + let at = if pinned.is_empty() { + String::new() + } else { + format!("@{pinned}") + }; + out.push(format!( + "command -v {tool} >/dev/null 2>&1 || corepack enable {tool} >/dev/null 2>&1 || npm install -g {} >/dev/null 2>&1 || true; hash -r", + quote(&format!("{tool}{at}")) + )); + } } Kind::Other => {} } @@ -547,6 +898,7 @@ fi {activate} {cd}if [ -z "$RESTORED" ] || [ -z "{complete}" ]; then ( {install} ) >/tmp/coderhelm-install.log 2>&1; ICODE=$?; tail -5 /tmp/coderhelm-install.log + if [ $ICODE -ne 0 ]; then echo "{INSTALL_FAILED} $ICODE"; tail -c 1500 /tmp/coderhelm-install.log; fi if [ $ICODE -eq 0 ] && [ -z "$RESTORED" ]; then echo "{INSTALLED}" if [ -n "$ENV_CACHE_PUT_URL" ] && tar czf /tmp/coderhelm-env-out.tgz -C "$E" . && curl -fsS --retry 2 --noproxy "*" -T /tmp/coderhelm-env-out.tgz "$ENV_CACHE_PUT_URL"; then echo "{SAVED}"; fi @@ -584,16 +936,19 @@ bash -c {cmd}"#, let rel = file.strip_prefix(&format!("{}/", dir.trim_end_matches('/')))?; Some(format!("(cd {dir} && {})", cmd.replace(file, rel))) }; - // A runner that takes file paths. + // A runner that takes file paths (`narrow`). + // The wrapper runs the command from the repository root: a job's + // working directory and a step's folder are both cd'd into. + let job = self.dir.trim_end_matches('/'); for (dir, line) in &steps { - let low = line.to_ascii_lowercase(); - for runner in ["pytest", "-m unittest"] { - if let Some(i) = low.find(runner) { - let prefix = line[..i + runner.len()].trim(); - if let Some(c) = in_dir(dir, format!("{prefix} {file}")) { - return Some(c); - } - } + let at = join(job, dir); + let rel = if at.is_empty() { + Some(file) + } else { + file.strip_prefix(&format!("{}/", at.trim_end_matches('/'))) + }; + if let Some(c) = rel.and_then(|r| narrow(line, r)) { + return Some(in_folder(&at, &c)); } } // A loop over test files, its body running each one. @@ -837,6 +1192,129 @@ jobs: assert_eq!(e.file_command("tests/test_a.py"), None); } + #[test] + fn every_runner_is_narrowed_to_one_file_in_one_place() { + assert_eq!( + narrow("python -m pytest tests -q", "tests/test_a.py").as_deref(), + Some("python -m pytest tests/test_a.py") + ); + assert_eq!( + narrow("python -m unittest discover", "tests/test_a.py").as_deref(), + Some("python -m unittest tests/test_a.py") + ); + assert_eq!( + narrow("pnpm exec vitest run --coverage", "src/a.test.ts").as_deref(), + Some("pnpm exec vitest run src/a.test.ts") + ); + assert_eq!( + narrow("npx --no-install vitest", "src/a.test.ts").as_deref(), + Some("npx --no-install vitest run src/a.test.ts") + ); + assert_eq!( + narrow("npx jest --ci", "src/a.test.ts").as_deref(), + Some("npx jest src/a.test.ts") + ); + assert_eq!( + narrow("go test ./... -race", "pkg/cart/total_test.go").as_deref(), + Some("go test ./pkg/cart/") + ); + assert_eq!( + narrow("cargo test --workspace", "tests/cart.rs").as_deref(), + Some("cargo test --test cart") + ); + // Never across a chain, never a file it can't take. + assert_eq!( + narrow("tsc --noEmit && vitest run", "a.test.ts").as_deref(), + Some("vitest run a.test.ts") + ); + assert_eq!(narrow("cargo test", "src/lib.rs"), None); + assert_eq!(narrow("npm run build", "a.test.ts"), None); + assert_eq!(narrow("pytest", "a; rm -rf /"), None); + } + + #[test] + fn package_scripts_and_make_targets_are_read_to_their_runner() { + let tree: Vec = [ + "package.json", + "apps/web/package.json", + "apps/web/src/a.test.ts", + "Makefile", + "tests/test_a.py", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let read = |p: &str| -> Option { + match p { + "package.json" => { + Some(r#"{"name":"root","scripts":{"test":"turbo run test"}}"#.into()) + } + "apps/web/package.json" => Some( + r#"{"name":"web","scripts":{"test":"vitest","test:run":"vitest run"}}"#.into(), + ), + "Makefile" => Some( + "lint:\n\truff .\ntest: deps\n\t@echo testing\n\tpython -m pytest -q tests\n" + .into(), + ), + _ => None, + } + }; + assert_eq!( + resolve_script("pnpm --filter web test", "", &tree, &read), + Some(("apps/web".into(), "vitest".into())) + ); + assert_eq!( + resolve_script("pnpm -F web run test:run", "", &tree, &read), + Some(("apps/web".into(), "vitest run".into())) + ); + assert_eq!( + resolve_script("make test", "", &tree, &read), + Some((String::new(), "python -m pytest -q tests".into())) + ); + assert_eq!(resolve_script("pnpm install", "", &tree, &read), None); + // A CI step that calls a script is narrowed through it. + let mut e = TestEnv { + test: vec!["pnpm --filter web test".into(), "make test".into()], + ..Default::default() + }; + e.resolve_scripts(&tree, &read); + assert_eq!( + e.file_command("apps/web/src/a.test.ts").as_deref(), + Some("(cd apps/web && npx --no-install vitest run src/a.test.ts)") + ); + assert_eq!( + e.file_command("tests/test_a.py").as_deref(), + Some("python -m pytest tests/test_a.py") + ); + // CI runs every package through turbo: the file's own package's + // script runs it. + assert_eq!( + package_test_command("apps/web/src/a.test.ts", &tree, &read).as_deref(), + Some("(cd apps/web && npx --no-install vitest run src/a.test.ts)") + ); + let wanted = script_files(Some(&e), &tree, &["apps/web/src/a.test.ts".into()]); + assert!(wanted.contains(&"apps/web/package.json".to_string())); + assert!(wanted.contains(&"Makefile".to_string())); + } + + #[test] + fn a_failed_install_and_the_pinned_manager_are_in_the_script() { + let e = TestEnv { + kind: Kind::Node, + pnpm: "10.28.2".into(), + install: vec!["pnpm install --frozen-lockfile".into()], + test: vec!["pnpm test".into()], + ..Default::default() + }; + let w = e.wrap("true"); + assert!(w.contains(INSTALL_FAILED)); + assert!(w.contains("npm install -g 'pnpm@10.28.2'")); + assert!(w.find("corepack enable pnpm").unwrap() < w.find("pnpm install --frozen").unwrap()); + let wf = "jobs:\n t:\n steps:\n - uses: pnpm/action-setup@v4\n with:\n version: 10.28.2\n - run: pnpm install --frozen-lockfile\n - run: pnpm --filter web test\n"; + let e = from_workflows(&[("ci.yml".into(), wf.into())], &[]).unwrap(); + assert_eq!(e.pnpm, "10.28.2"); + } + /// The second round restores the first round's install instead of /// installing again. Runs the real script with bash, tar and curl (file /// URLs stand in for the presigned ones). diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index 8a4789a4d..3be1b3a85 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -19,12 +19,27 @@ //! ledger), goes back to be taken out, unless a `Scope change:` line //! cites an acceptance criterion or a person's comment. //! -//! The sandbox runs take up to its full wait, so the check asks for a step -//! of its own when this one has too little time left -//! ([`GateStop::NeedsTime`]), once; a run that still has none records the -//! tests as not run, with why. Like every check on the open pull request it -//! runs once on a head, keeps its rounds in the run's ledger, and what it -//! leaves goes under Open items. +//! The sandbox runs take up to its full wait. They have a budget of their +//! own, never the leftovers of the coding step: when this step has too +//! little time left the check asks for a step of its own +//! ([`GateStop::NeedsTime`]) and records the runs as owed; the next step +//! runs them first, before any other check ([`run_owed`]), and the check +//! reads their recorded result ([`RecordedRuns`]). A run asks at most +//! [`MAX_PROOF_STEPS`] times; only past that are the tests recorded as not +//! run, with why. Seven runs had recorded "no step of the run had the time" +//! for every changed test: the fresh step ran every other check first and +//! came to these runs short again, and the one request it had was spent. +//! +//! The runs install the way the repository's CI does: in the CI job that +//! runs the files' tests (`common::test_env`, cached per manifest blob), or, +//! when CI installs nothing CoderHelm can read, each test file's package +//! (a workspace member from the workspace's root). Each test file runs with +//! the command CI's test step runs, narrowed to it, else its own package's +//! test script (`common::test_env::narrow`). Why a test didn't run is kept +//! with it ([`NotRunWhy`]) and counted on the run ([`TestsRan`]). +//! +//! Like every check on the open pull request it runs once on a head, keeps +//! its rounds in the run's ledger, and what it leaves goes under Open items. use serde::{Deserialize, Serialize}; use tracing::{info, warn}; @@ -40,6 +55,9 @@ pub const MAX_TEST_FILES: usize = 8; /// What the two sandbox runs need of a step: the sandbox's longest wait and /// room to record the result. pub const SANDBOX_STEP_SECS: u64 = 760; +/// How many steps of its own the sandbox runs may ask for in a run: one per +/// head a fix round leaves, and room for a step that was cut short. +pub const MAX_PROOF_STEPS: u32 = 4; pub const START: &str = ""; pub const END: &str = ""; @@ -69,6 +87,127 @@ pub struct TestResult { /// The failure it printed without the change, or why it didn't run. #[serde(default)] pub detail: String, + /// Why it didn't run, as a kind to count (`None` when it ran). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub why: Option, +} + +/// Why a changed test wasn't run with and without the change. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NotRunWhy { + /// The dependencies' install failed in the sandbox. + InstallFailed, + /// No step had the time for the two sandbox runs. + NoTime, + /// No command CoderHelm can read runs the file on its own. + NoCommand, + /// An end-to-end spec: it runs against a preview, not in the sandbox. + EndToEnd, + /// The runner found no test in the file. + NoTestsFound, + /// More test files than are run on their own. + TooMany, + /// The sandbox gave no result, or something else stopped it. + Other, +} + +/// Why nothing ran: the install failed in the sandbox. +pub const INSTALL_FAILED: &str = "the package's install failed in the sandbox"; +/// Why nothing ran: past [`MAX_PROOF_STEPS`] steps, still no time. +pub const NO_TIME: &str = "no step of the run had the time for the two sandbox runs"; + +impl NotRunWhy { + /// The kind of a not-run detail line. + pub fn of(detail: &str) -> NotRunWhy { + let d = detail.to_ascii_lowercase(); + if d.contains("install") && d.contains("fail") { + NotRunWhy::InstallFailed + } else if d.contains("had the time") { + NotRunWhy::NoTime + } else if d.contains("end-to-end spec") { + NotRunWhy::EndToEnd + } else if d.contains("found no tests") { + NotRunWhy::NoTestsFound + } else if d.contains("only the first") { + NotRunWhy::TooMany + } else if d.contains("no unit test command") + || d.contains("can't be narrowed") + || d.contains("doesn't run `") + { + NotRunWhy::NoCommand + } else { + NotRunWhy::Other + } + } + + pub fn label(self) -> &'static str { + match self { + NotRunWhy::InstallFailed => "install failed", + NotRunWhy::NoTime => "no time", + NotRunWhy::NoCommand => "no test command", + NotRunWhy::EndToEnd => "end-to-end spec", + NotRunWhy::NoTestsFound => "no tests found", + NotRunWhy::TooMany => "past the file limit", + NotRunWhy::Other => "other", + } + } +} + +/// Whether the changed tests ran with and without the change, and why not: +/// the run's record of it (the ledger keeps the check's facts). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestsRan { + /// Changed test files. + pub files: usize, + /// Of them, run both ways. + pub ran: usize, + /// The rest, by why. + #[serde(default)] + pub not_run: Vec<(NotRunWhy, usize)>, +} + +impl TestsRan { + pub fn of(tests: &[TestResult]) -> TestsRan { + let mut not_run: Vec<(NotRunWhy, usize)> = Vec::new(); + for t in tests.iter().filter(|t| t.verdict == Verdict::NotRun) { + let why = t.why.unwrap_or_else(|| NotRunWhy::of(&t.detail)); + match not_run.iter_mut().find(|(w, _)| *w == why) { + Some((_, n)) => *n += 1, + None => not_run.push((why, 1)), + } + } + let n: usize = not_run.iter().map(|(_, n)| n).sum(); + TestsRan { + files: tests.len(), + ran: tests.len() - n, + not_run, + } + } + + /// One line: "Tests run with and without the change: 2 of 3 (not run: + /// 1 install failed)". Empty with no test files. + pub fn line(&self) -> String { + if self.files == 0 { + return String::new(); + } + let why = if self.not_run.is_empty() { + String::new() + } else { + format!( + " (not run: {})", + self.not_run + .iter() + .map(|(w, n)| format!("{n} {}", w.label())) + .collect::>() + .join(", ") + ) + }; + format!( + "Tests run with and without the change: {} of {}{why}", + self.ran, self.files + ) + } } /// A changed file that is no part of the plan. @@ -118,6 +257,9 @@ pub struct PrFacts { /// took it, files only reformatted. #[serde(default)] pub live: super::live_guard::LiveFacts, + /// Whether the changed tests ran both ways, and why not. + #[serde(default)] + pub tests_ran: TestsRan, } /// Why the check didn't give a result. @@ -130,14 +272,15 @@ pub enum GateStop { } /// One test file's run: its exit code and, when it failed, what it printed. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +/// No code: it didn't run, and the output says why when it is known. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct FileRun { pub code: Option, pub output: String, } /// Both runs of the changed test files, in the files' order. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Runs { pub with: Vec, pub without: Vec, @@ -207,6 +350,7 @@ fn excerpt(output: &str) -> String { /// What one file's two runs show. pub fn verdict(with: &FileRun, without: &FileRun) -> (Verdict, String) { match (with.code, without.code) { + (None, _) if !with.output.is_empty() => (Verdict::NotRun, with.output.clone()), (None, _) | (_, None) => ( Verdict::NotRun, "the sandbox gave no result for it".to_string(), @@ -244,9 +388,11 @@ pub fn scoped_cmd(base_cmd: &str, file: &str) -> Option { if low.contains("pytest") { return Some(format!("{base_cmd} {file}")); } - if low.trim_start().starts_with("go test") { - let dir = file.rsplit_once('/').map_or(".", |(d, _)| d); - return Some(format!("go test ./{dir}/")); + // Runners that take a path or a package: one place narrows them. + if !low.contains("vitest") && !low.contains("jest") { + if let Some(c) = common::test_env::narrow(base_cmd, file) { + return Some(c); + } } super::build_scoped_test_cmd(base_cmd, &[file.to_string()]) .map(|c| c.replace(" --passWithNoTests", "")) @@ -327,6 +473,50 @@ pub fn changed_tests(diff: &Diff) -> Vec { .collect() } +/// Test data, not a test: fixtures, snapshots, recorded responses. Two +/// runs listed a fixture's JSON as a test CoderHelm couldn't run. +fn is_test_data(path: &str) -> bool { + let p = path.to_ascii_lowercase(); + let data_dir = [ + "/fixtures/", + "/__fixtures__/", + "/testdata/", + "/test-data/", + "/__snapshots__/", + "/cassettes/", + ] + .iter() + .any(|d| format!("/{p}").contains(d)); + let ext = p.rsplit_once('.').map_or("", |(_, e)| e); + let data_ext = matches!( + ext, + "json" + | "yaml" + | "yml" + | "csv" + | "txt" + | "snap" + | "md" + | "html" + | "xml" + | "sql" + | "png" + | "jpg" + | "svg" + ); + data_dir || data_ext +} + +/// The changed test files a runner can run: not test data. +pub fn bench_files(diff: &Diff) -> Vec { + let mut tests: Vec = changed_tests(diff) + .into_iter() + .filter(|p| !is_test_data(p)) + .collect(); + tests.truncate(MAX_TEST_FILES); + tests +} + fn changes_code(diff: &Diff) -> bool { diff.iter().any(|(p, _, _)| !is_test_path(p)) } @@ -444,9 +634,14 @@ pub async fn check_once( not_updated: not_updated(&changed, plan, own_repo), ..Default::default() }; - let tests = changed_tests(diff); + let all = changed_tests(diff); + let tests: Vec = all.iter().filter(|p| !is_test_data(p)).cloned().collect(); if tests.is_empty() { - facts.no_tests = "the change adds or changes no test file".to_string(); + facts.no_tests = if all.is_empty() { + "the change adds or changes no test file".to_string() + } else { + "the change adds or changes only test data, no test file to run".to_string() + }; return facts; } if !changes_code(diff) { @@ -462,10 +657,12 @@ pub async fn check_once( runs.with.get(i).unwrap_or(&none), runs.without.get(i).unwrap_or(&none), ); + let why = (verdict == Verdict::NotRun).then(|| NotRunWhy::of(&detail)); facts.tests.push(TestResult { path: path.clone(), verdict, detail, + why, }); } } @@ -475,6 +672,7 @@ pub async fn check_once( path: path.clone(), verdict: Verdict::NotRun, detail: why.clone(), + why: Some(NotRunWhy::of(&why)), }); } } @@ -484,8 +682,10 @@ pub async fn check_once( path: path.clone(), verdict: Verdict::NotRun, detail: format!("only the first {MAX_TEST_FILES} test files are run on their own"), + why: Some(NotRunWhy::TooMany), }); } + facts.tests_ran = TestsRan::of(&facts.tests); facts } @@ -739,6 +939,11 @@ pub fn section(plan: &PlanResult, f: &PrFacts) -> String { out.push_str(&test_line(t)); out.push('\n'); } + // How many ran both ways, and why the rest didn't, counted. + let ran = TestsRan::of(&f.tests); + if ran.ran < ran.files { + out.push_str(&format!("{}.\n", ran.line())); + } // A bug fix no test was shown to fail on the base for says so, in // so many words: it is unverified, never quietly proven by CI. if f.bug && !f.tests.iter().any(|t| t.verdict == Verdict::Proven) { @@ -954,42 +1159,178 @@ pub struct SandboxBench<'a> { const KIND: &str = "unit"; +/// The end-to-end spec's line: it runs against a preview, never in the +/// unit sandbox (CI and the end-to-end proof run it there). +pub const E2E_SPEC: &str = "an end-to-end spec: it runs against a preview, not in the unit sandbox"; + +/// Whether `file` is an end-to-end spec: its package's runner drives a +/// browser, or it sits in the repository's end-to-end suite. +fn is_e2e_spec(tree: &[String], file: &str, texts: &dyn Fn(&str) -> Option) -> bool { + use test_package::Runner as R; + let runner = test_package::package_of(tree, file, texts).and_then(|p| p.runner); + matches!(runner, Some(R::Playwright | R::Cypress | R::Wdio)) + || common::preview::e2e_suite(tree) + .is_some_and(|s| file.starts_with(&format!("{}/", s.dir.trim_end_matches('/')))) +} + +/// How the sandbox runs the files: the installs (none when CI's test job +/// installs, through its environment), one command per file that has one, +/// and why the others don't run. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct BenchPlan { + pub install: Vec, + /// Per file, in order: its command, or why it doesn't run. + pub per_file: Vec>, +} + +/// The sandbox plan for `files`, from the CI test command CoderHelm reads +/// (`ci_cmd`), CI's test environment for these files (`env`, its package +/// scripts already resolved) and the tree's manifests (`texts`). A file +/// with no command is recorded as not run with why; the others still run. +pub fn bench_plan( + files: &[String], + tree: &[String], + ci_cmd: Option<&str>, + env: Option<&common::test_env::TestEnv>, + texts: &dyn Fn(&str) -> Option, +) -> BenchPlan { + let mut plan = BenchPlan::default(); + // CI's own install, in its order, at its versions, in its environment + // (cached per manifest blob); else each file's package's. + let ci_installs = env.is_some_and(|e| !e.install.is_empty()); + let mut installed: Vec = Vec::new(); + for f in files { + if is_e2e_spec(tree, f, texts) { + plan.per_file.push(Err(E2E_SPEC.to_string())); + continue; + } + let cmd = file_cmd(ci_cmd, env, f) + .or_else(|why| common::test_env::package_test_command(f, tree, texts).ok_or(why)); + if cmd.is_ok() && !ci_installs { + let steps = test_package::package_of(tree, f, texts) + .and_then(|p| test_package::check_steps(&p)) + .unwrap_or_default(); + for s in steps.into_iter().filter(|s| s.kind == "install") { + if !installed.contains(&s.cmd) { + installed.push(s.cmd.clone()); + plan.install.push(s); + } + } + } + plan.per_file.push(cmd); + } + plan +} + +/// The runs of the planned commands, per file: a file with no command did +/// not run, and says why. +fn spread(plan: &BenchPlan, runs: Vec) -> Vec { + let mut runs = runs.into_iter(); + plan.per_file + .iter() + .map(|c| match c { + Ok(_) => runs.next().unwrap_or_default(), + Err(why) => FileRun { + code: None, + output: why.clone(), + }, + }) + .collect() +} + +/// Why the install failed, from a sandbox script's output: CI's install in +/// the test environment, or an install step; the error's last lines. +pub fn install_failure(output: &str, codes: &[Option], installs: usize) -> Option { + let tail = |t: &str| -> String { + let lines: Vec<&str> = t.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); + let pick: Vec<&str> = lines + .iter() + .filter(|l| { + let low = l.to_ascii_lowercase(); + low.contains("err") || low.contains("error") || low.contains("not found") + }) + .copied() + .collect(); + let pick = if pick.is_empty() { + lines[lines.len().saturating_sub(2)..].to_vec() + } else { + pick[pick.len().saturating_sub(2)..].to_vec() + }; + common::truncate_str(&pick.join(" "), 300).replace('`', "'") + }; + if let Some(at) = output.find(common::test_env::INSTALL_FAILED) { + let rest = &output[at + common::test_env::INSTALL_FAILED.len()..]; + let body = rest.split(test_package::STEP_MARK).next().unwrap_or(rest); + return Some(format!("{INSTALL_FAILED} (CI's install: {})", tail(body))); + } + if codes.iter().take(installs).any(|c| *c != Some(0)) { + let out = failing_outputs(output, "install").join("\n"); + return Some(if out.is_empty() { + INSTALL_FAILED.to_string() + } else { + format!("{INSTALL_FAILED} ({})", tail(&out)) + }); + } + None +} + #[async_trait::async_trait] impl Bench for SandboxBench<'_> { async fn run(&self, files: &[String]) -> Result { let r = &self.runner; let ci_cmd = super::detect_ci_test(r.github, r.owner, r.repo, self.base_branch).await; - let mut steps: Vec = Vec::new(); - let tree: Vec = r + let tree_full = r .github .get_tree(r.owner, r.repo, self.branch) .await - .map_err(|e| e.to_string())? - .into_iter() - .map(|e| e.path) + .map_err(|e| e.to_string())?; + let tree: Vec = tree_full.iter().map(|e| e.path.clone()).collect(); + // CI's job for these files: its install wraps every command, and + // its test steps (package scripts read through) run each file. + let env = super::test_setup::for_run( + r.state, + r.github, + r.team_id, + r.owner, + r.repo, + self.base_branch, + self.branch, + r.run_id, + files, + ) + .await; + let mut texts: std::collections::HashMap = Default::default(); + for p in common::test_env::script_files(env.as_ref().map(|(e, _)| e), &tree, files) { + if let Ok(t) = r.github.read_file(r.owner, r.repo, &p, self.branch).await { + texts.insert(p, t); + } + } + let read = |p: &str| texts.get(p).cloned(); + let resolved = env.as_ref().map(|(e, _)| { + let mut e = e.clone(); + e.resolve_scripts(&tree, &read); + e + }); + let plan = bench_plan(files, &tree, ci_cmd.as_deref(), resolved.as_ref(), &read); + let commands: Vec<&String> = plan + .per_file + .iter() + .filter_map(|c| c.as_ref().ok()) .collect(); - // A test step CoderHelm's runner list doesn't know (a loop running - // each file with `python`) still runs the file the way CI does. - let narrowed = |f: &String| ci_cmd.as_deref().and_then(|c| scoped_cmd(c, f)); - let env = if files.iter().all(|f| narrowed(f).is_some()) { - None - } else { - let workflows = - super::preview::workflows(r.github, r.owner, r.repo, self.base_branch).await; - common::test_env::from_workflows_for(&workflows, &tree, files) - }; - let install: Vec = files - .first() - .and_then(|f| test_package::package_of(&tree, f, &|_| None)) - .and_then(|p| test_package::check_steps(&p)) - .map(|s| s.into_iter().filter(|s| s.kind == "install").collect()) - .unwrap_or_default(); - let installs = install.len(); - steps.extend(install); - for f in files { - let cmd = file_cmd(ci_cmd.as_deref(), env.as_ref(), f)?; - steps.push(Step { kind: KIND, cmd }); + if commands.is_empty() { + // Nothing to run: each file says why. + let none = spread(&plan, Vec::new()); + return Ok(Runs { + with: none.clone(), + without: none, + }); } + let installs = plan.install.len(); + let mut steps: Vec = plan.install.clone(); + steps.extend(commands.iter().map(|c| Step { + kind: KIND, + cmd: (*c).clone(), + })); let head = r .github .get_ref(r.owner, r.repo, self.branch) @@ -1035,8 +1376,8 @@ impl Bench for SandboxBench<'_> { .map_err(|e| e.to_string())?; // Side by side: each waits on its own sandbox build. let (with, without) = tokio::join!( - r.run_at(&head, &steps, None), - r.run_at(&before_sha, &steps, None) + r.run_at_in(&head, &steps, env.clone()), + r.run_at_in(&before_sha, &steps, env.clone()) ); Ok::<_, String>((with?, without?)) } @@ -1045,17 +1386,22 @@ impl Bench for SandboxBench<'_> { warn!(error = %e, branch = %temp, "Could not delete the branch of the test check"); } let ((with_codes, with_out), (without_codes, without_out)) = both?; + for (codes, out) in [(&with_codes, &with_out), (&without_codes, &without_out)] { + if let Some(why) = install_failure(out, codes, installs) { + warn!(run_id = r.run_id, why = %why, "The changed tests' install failed in the sandbox"); + return Err(why); + } + } let per_file = |codes: &[Option], out: &str| { - let failed_installs = codes.iter().take(installs).any(|c| *c != Some(0)); - let runs = file_runs(&codes[installs.min(codes.len())..], out, KIND); - (failed_installs, runs) + spread( + &plan, + file_runs(&codes[installs.min(codes.len())..], out, KIND), + ) }; - let (with_broken, with) = per_file(&with_codes, &with_out); - let (without_broken, without) = per_file(&without_codes, &without_out); - if with_broken || without_broken { - return Err("the package's install failed in the sandbox".to_string()); - } - Ok(Runs { with, without }) + Ok(Runs { + with: per_file(&with_codes, &with_out), + without: per_file(&without_codes, &without_out), + }) } } @@ -1162,17 +1508,190 @@ async fn wider( .collect() } -/// A bench for a step with no time for the sandbox: nothing runs, and each -/// test says so. +/// A bench for a run whose steps never had the time for the sandbox, past +/// [`MAX_PROOF_STEPS`] asks: nothing runs, and each test says so. struct NoTime; #[async_trait::async_trait] impl Bench for NoTime { async fn run(&self, _files: &[String]) -> Result { - Err("no step of the run had the time for the two sandbox runs; the repository's CI runs the tests on this pull request".to_string()) + Err(format!("{NO_TIME} in {MAX_PROOF_STEPS} steps of their own; the repository's CI runs the tests on this pull request")) + } +} + +/// The two sandbox runs of a head's changed test files, kept on the run's +/// ledger: a step that runs them first ([`run_owed`]) leaves them for the +/// check, which reads them instead of running them again. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RecordedRuns { + pub head: String, + pub files: Vec, + pub result: Result, +} + +impl RecordedRuns { + /// Whether these are the runs of `files` on `head`. + pub fn of(&self, head: &str, files: &[String]) -> bool { + !head.is_empty() && self.head == head && self.files == files + } +} + +/// A bench that answers with recorded runs. +struct Recorded(Result); + +#[async_trait::async_trait] +impl Bench for Recorded { + async fn run(&self, _files: &[String]) -> Result { + self.0.clone() } } +/// A bench that keeps what another one gave, for the ledger. +struct Recording<'b> { + inner: &'b dyn Bench, + got: std::sync::Mutex>>, +} + +#[async_trait::async_trait] +impl Bench for Recording<'_> { + async fn run(&self, files: &[String]) -> Result { + let r = self.inner.run(files).await; + *self.got.lock().unwrap() = Some(r.clone()); + r + } +} + +/// What the step does about the sandbox runs for a head. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProofTime { + /// They ran for this head and files: read them. + Recorded(Result), + /// This step has their time: run them now. + Run, + /// Owed to a fresh step, which runs them first. + Owe, + /// No step had the time, past the asks a run has. + NoTime, +} + +/// What a step does about the changed tests' sandbox runs: read the +/// recorded ones, run them, owe them to a fresh step (at most +/// [`MAX_PROOF_STEPS`] times a run, never on a path that has no step to +/// give), or, only past that, record them as not run. +pub fn proof_time( + recorded: Option<&RecordedRuns>, + head: &str, + files: &[String], + secs_left: u64, + steps_asked: u32, + can_hand_off: bool, +) -> ProofTime { + if let Some(r) = recorded.filter(|r| r.of(head, files)) { + return ProofTime::Recorded(r.result.clone()); + } + if secs_left >= SANDBOX_STEP_SECS { + return ProofTime::Run; + } + if can_hand_off && steps_asked < MAX_PROOF_STEPS { + return ProofTime::Owe; + } + ProofTime::NoTime +} + +/// The diff the check reads: the run's work files, with their status. +async fn work_diff(w: &super::proof::Work<'_>) -> Result, String> { + let diff = w + .github + .compare_files_with_patches( + &w.msg.repo_owner, + &w.msg.repo_name, + &w.msg.base_branch, + w.branch, + ) + .await + .map_err(|e| format!("the diff couldn't be read ({e})"))?; + let paths: Vec = diff.iter().map(|(p, _, _)| p.clone()).collect(); + let work = super::run_end::work_files(&paths, &w.msg.ticket_id); + Ok(diff + .into_iter() + .filter(|(p, _, _)| work.contains(p)) + .collect()) +} + +fn sandbox_bench<'a>(w: &'a super::proof::Work<'a>) -> SandboxBench<'a> { + SandboxBench { + runner: super::test_bug::Runner { + state: w.state, + github: w.github, + owner: &w.msg.repo_owner, + repo: &w.msg.repo_name, + team_id: &w.msg.team_id, + run_id: w.run_id, + provider: w.provider, + }, + base_branch: &w.msg.base_branch, + branch: w.branch, + } +} + +/// The sandbox runs a step owed this one, run first, before any other +/// check, with the step's whole budget; their result is recorded for the +/// check ([`RecordedRuns`]). Nothing when none are owed, or the head moved +/// since (the check asks again for the new one). +pub async fn run_owed(w: &super::proof::Work<'_>, secs_left: impl Fn() -> u64) { + let owed = w.ledger.update(|l| l.proof_owed.clone()); + if owed.is_empty() { + return; + } + let head = w.head().await; + if head != owed || secs_left() < SANDBOX_STEP_SECS { + if head != owed { + w.ledger.update(|l| l.proof_owed.clear()); + w.save_ledger().await; + } + return; + } + let files = match work_diff(w).await { + Ok(d) if changes_code(&d) => bench_files(&d), + Ok(_) => Vec::new(), + Err(e) => { + warn!(run_id = w.run_id, error = %e, "The owed sandbox runs couldn't read the diff; the check runs them"); + return; + } + }; + if files.is_empty() { + w.ledger.update(|l| l.proof_owed.clear()); + w.save_ledger().await; + return; + } + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + &format!( + "Running the {} changed test file(s) with and without the change first in this step, with its whole time", + files.len() + ), + ) + .await; + let result = sandbox_bench(w).run(&files).await; + info!( + run_id = w.run_id, + ok = result.is_ok(), + files = files.len(), + "The owed sandbox runs ran first in the step" + ); + w.ledger.update(|l| { + l.proof_owed.clear(); + l.proof_runs = Some(RecordedRuns { + head: head.clone(), + files: files.clone(), + result: result.clone(), + }); + }); + w.save_ledger().await; +} + async fn check_and_fix( w: &super::proof::Work<'_>, evidence: &mut super::proof::RunEvidence, @@ -1185,46 +1704,44 @@ async fn check_and_fix( return Ok(None); } loop { - let diff = w - .github - .compare_files_with_patches( - &w.msg.repo_owner, - &w.msg.repo_name, - &w.msg.base_branch, - w.branch, - ) - .await - .map_err(|e| GateStop::Why(format!("the diff couldn't be read ({e})")))?; + let diff = work_diff(w).await.map_err(GateStop::Why)?; let paths: Vec = diff.iter().map(|(p, _, _)| p.clone()).collect(); - let work = super::run_end::work_files(&paths, &w.msg.ticket_id); - let diff: Vec<(String, String, String)> = diff - .into_iter() - .filter(|(p, _, _)| work.contains(p)) - .collect(); - let needs_sandbox = !changed_tests(&diff).is_empty() && changes_code(&diff); - let short = needs_sandbox && secs_left() < SANDBOX_STEP_SECS; - if short - && !w + let files = bench_files(&diff); + let needs_sandbox = !files.is_empty() && changes_code(&diff); + let head = w.head().await; + // The proof runs have a budget of their own: read the recorded + // runs, run them now, or owe them to a fresh step that runs them + // first; only past the asks are they recorded as not run. + let time = if needs_sandbox { + let (recorded, asked, can) = w .ledger - .update(|l| std::mem::replace(&mut l.habits_waited, true)) - { + .update(|l| (l.proof_runs.clone(), l.proof_steps, !l.no_proof_step)); + proof_time(recorded.as_ref(), &head, &files, secs_left(), asked, can) + } else { + ProofTime::Run + }; + if time == ProofTime::Owe { + w.ledger.update(|l| { + l.proof_steps += 1; + l.proof_owed = head.clone(); + }); w.save_ledger().await; return Err(GateStop::NeedsTime); } - let sandbox = SandboxBench { - runner: super::test_bug::Runner { - state: w.state, - github: w.github, - owner: &w.msg.repo_owner, - repo: &w.msg.repo_name, - team_id: &w.msg.team_id, - run_id: w.run_id, - provider: w.provider, - }, - base_branch: &w.msg.base_branch, - branch: w.branch, + let sandbox = sandbox_bench(w); + let recording = Recording { + inner: &sandbox, + got: Default::default(), + }; + let recorded; + let bench: &dyn Bench = match &time { + ProofTime::Recorded(r) => { + recorded = Recorded(r.clone()); + &recorded + } + ProofTime::NoTime => &NoTime, + _ => &recording, }; - let bench: &dyn Bench = if short { &NoTime } else { &sandbox }; let mut facts = check_once( bench, &diff, @@ -1234,6 +1751,19 @@ async fn check_and_fix( &evidence.notes, ) .await; + if let Some(result) = recording.got.lock().unwrap().take() { + w.ledger.update(|l| { + l.proof_runs = Some(RecordedRuns { + head: head.clone(), + files: files.clone(), + result, + }) + }); + } + if !facts.tests_ran.line().is_empty() { + super::add_progress_note(w.state, &w.msg.team_id, w.run_id, &facts.tests_ran.line()) + .await; + } facts.e2e_missing = e2e_missing(w, &paths).await; facts.wider = wider(w, &diff, &evidence.notes).await; // Fixture ids invented while the run looked up the real ones. @@ -1243,7 +1773,13 @@ async fn check_and_fix( .extend(super::minimal_change::made_up_ids(&diff, &looked)); // A page whose state a test branch reads is probed again while // there is time: an arm that couldn't run before is re-checked. - facts.live = super::live_guard::facts_for(w, &diff, &evidence.notes, !short).await; + facts.live = super::live_guard::facts_for( + w, + &diff, + &evidence.notes, + secs_left() >= SANDBOX_STEP_SECS, + ) + .await; let comments = super::scope_ledger::comments(w.github, w.msg, w.branch).await; let people = super::scope_ledger::people(w.msg, &comments); let mut ledger = super::scope_ledger::load_or_seed( diff --git a/services/worker/src/passes/incidents/aj_coder_habits.rs b/services/worker/src/passes/incidents/aj_coder_habits.rs index 8c64b77b0..086de5355 100644 --- a/services/worker/src/passes/incidents/aj_coder_habits.rs +++ b/services/worker/src/passes/incidents/aj_coder_habits.rs @@ -282,8 +282,9 @@ fn the_pipeline_still_does_each_of_these_at_its_place() { let pr_src = include_str!("../pr.rs"); let with_checks = fn_src(pr_src, "fn with_checks("); assert!(with_checks.contains("super::habits_check::shape_body(")); - // It asks for a step once, and the sandbox wait fits a step. + // It owes the runs to a fresh step, which runs them first (see + // `tq_tests_run`), and the sandbox wait fits a step. let check_src = include_str!("../habits_check.rs"); - assert!(check_src.contains("std::mem::replace(&mut l.habits_waited, true)")); + assert!(check_src.contains("l.proof_owed = head.clone();")); const { assert!(habits_check::SANDBOX_STEP_SECS < 900) }; } diff --git a/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs b/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs index 22decfeaf..11d331f87 100644 --- a/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs +++ b/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs @@ -233,6 +233,7 @@ fn the_new_test_runs_on_the_base_the_way_ci_runs_it() { path: "tests/test_camp_sport.py".into(), verdict: habits_check::verdict(&head, &head).0, detail: String::new(), + why: None, }], ..Default::default() }; @@ -246,6 +247,7 @@ fn the_new_test_runs_on_the_base_the_way_ci_runs_it() { path: "tests/test_camp_sport.py".into(), verdict: Verdict::NotRun, detail: "the sandbox gave no result for it".into(), + why: None, }], ..Default::default() }; @@ -256,6 +258,7 @@ fn the_new_test_runs_on_the_base_the_way_ci_runs_it() { path: "tests/test_camp_sport.py".into(), verdict: Verdict::Proven, detail: "AssertionError".into(), + why: None, }], ..Default::default() }; diff --git a/services/worker/src/passes/incidents/tq_tests_run.rs b/services/worker/src/passes/incidents/tq_tests_run.rs new file mode 100644 index 000000000..1f21d8ff4 --- /dev/null +++ b/services/worker/src/passes/incidents/tq_tests_run.rs @@ -0,0 +1,286 @@ +//! tq. Across the 53 most recent runs, 17 had new or changed tests to run +//! with and without the change, and not one ran both ways: +//! +//! - 6 recorded "the package's install failed in the sandbox", all in one +//! pnpm workspace. The test files sat in a member (`apps/web`) whose +//! lockfile is the workspace root's, and the sandbox installed the member +//! on its own: `cd 'apps/web' && pnpm install --ignore-workspace +//! --frozen-lockfile`. With no lockfile in that folder pnpm stops with +//! `ERR_PNPM_NO_LOCKFILE` before any test, on every run. The run's own CI +//! install (`pnpm install --frozen-lockfile` at the root, cached per +//! manifest blob) was never used for these runs, and the failure said +//! nothing of why. One of them also listed a Playwright spec as a unit +//! test. +//! - 7 recorded "no step of the run had the time for the two sandbox +//! runs". The check asked once for a step of its own; the fresh step ran +//! every other check first (the proof, the link checks, the new-feature +//! rules, live probes, the scope ledger) and came to the runs with less +//! than their 760 seconds left, and the one request was spent: one run +//! resumed for the runs at 16:00:42 and reached them at 16:05:42. +//! - 2 recorded "the repository's CI runs no unit test command CoderHelm +//! can read" for a data pipeline whose CI loops `python "$t"` over its +//! tests, and listed fixture JSON files as tests too; one file without a +//! command stopped every file from running. +//! - 2 had no test to run (a change of only tests, or no test file). +//! +//! Guarantee: the runs install the way CI does (its job for the files, its +//! install lines in order, its Node and pnpm versions, through the cached +//! environment); without one a workspace member installs from the +//! workspace root, falling back to the member and what it depends on. A +//! failed install says why (its error lines). An end-to-end spec and test +//! data are never run as unit tests. The runs have a budget of their own: +//! owed to a fresh step, which runs them first, before any other check, +//! and records them for the head; a run asks up to `MAX_PROOF_STEPS` +//! times. Each file runs with CI's test step narrowed to it (one +//! `common::test_env::narrow` for pytest, unittest, Vitest, Jest, go test, +//! cargo test; package scripts and make targets read through), else its +//! own package's test script; a file with none doesn't stop the others. +//! Whether the tests ran, and why not, is counted on the run and in the +//! pull request. + +use crate::passes::habits_check::{ + self, bench_files, bench_plan, install_failure, proof_time, FileRun, NotRunWhy, ProofTime, + RecordedRuns, Runs, TestResult, TestsRan, Verdict, +}; +use common::e2e::test_package::{self, STEP_MARK}; +use common::test_env::{self, TestEnv}; + +fn tree(paths: &[&str]) -> Vec { + paths.iter().map(|p| p.to_string()).collect() +} + +/// A web workspace like the six runs': `apps/web` a member, the lockfile at +/// the root, an end-to-end package with its own lockfile. +fn workspace() -> Vec { + tree(&[ + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "apps/web/package.json", + "apps/web/src/components/drawer.tsx", + "apps/web/src/test/components/drawer-reopen.test.tsx", + "e2e/package.json", + "e2e/pnpm-lock.yaml", + "e2e/tests/browse/registration.spec.ts", + ]) +} + +fn manifests(p: &str) -> Option { + match p { + "package.json" => Some(r#"{"name":"acme","packageManager":"pnpm@10.28.2"}"#.into()), + "apps/web/package.json" => Some( + r#"{"name":"web","scripts":{"test":"vitest","test:run":"vitest run"},"devDependencies":{"vitest":"3.0.0"}}"# + .into(), + ), + "e2e/package.json" => Some(r#"{"devDependencies":{"@playwright/test":"1.48.0"}}"#.into()), + _ => None, + } +} + +#[test] +fn a_workspace_member_installs_from_the_root_and_says_why_when_it_fails() { + let t = workspace(); + let test = "apps/web/src/test/components/drawer-reopen.test.tsx".to_string(); + // What the six runs ran: the member on its own, where pnpm finds no + // lockfile. + let web = test_package::package_of(&t, &test, &manifests).unwrap(); + let install = &test_package::check_steps(&web).unwrap()[0].cmd; + assert!(!install.contains("cd 'apps/web' &&"), "{install}"); + assert!(!install.contains("--ignore-workspace"), "{install}"); + assert!(install.starts_with("cd '.' && "), "{install}"); + // With CI's install for these files read, CI's install runs (in the + // cached environment) and nothing else. + let ci = TestEnv { + kind: test_env::Kind::Node, + install: vec!["pnpm install --frozen-lockfile".into()], + test: vec!["pnpm --filter web run test:run".into()], + ..Default::default() + }; + let mut resolved = ci.clone(); + resolved.resolve_scripts(&t, &manifests); + let plan = bench_plan( + std::slice::from_ref(&test), + &t, + None, + Some(&resolved), + &manifests, + ); + assert!(plan.install.is_empty()); + assert_eq!( + plan.per_file, + vec![Ok( + "(cd apps/web && npx --no-install vitest run src/test/components/drawer-reopen.test.tsx)" + .to_string() + )] + ); + // Without CI's, the member's package installs from the root, once. + let plan = bench_plan(&[test.clone(), test.clone()], &t, None, None, &manifests); + assert_eq!(plan.install.len(), 1); + assert!(plan.install[0] + .cmd + .contains("pnpm install --frozen-lockfile")); + // The Playwright spec one run listed is never a unit test. + let spec = "e2e/tests/browse/registration.spec.ts".to_string(); + let plan = bench_plan(&[spec], &t, None, None, &manifests); + assert!(matches!(&plan.per_file[0], Err(w) if w == habits_check::E2E_SPEC)); + assert_eq!(NotRunWhy::of(habits_check::E2E_SPEC), NotRunWhy::EndToEnd); + // A failed install says why, from its own lines. + let out = format!( + "--- install failed (exit 1) ---\n ERR_PNPM_NO_LOCKFILE Cannot install with \"frozen-lockfile\" because pnpm-lock.yaml is absent\n{STEP_MARK} 1 1\n{STEP_MARK} 2 1\n" + ); + let why = install_failure(&out, &[Some(1), Some(1)], 1).unwrap(); + assert!(why.starts_with(habits_check::INSTALL_FAILED), "{why}"); + assert!(why.contains("ERR_PNPM_NO_LOCKFILE"), "{why}"); + let ci_out = format!( + "{} 1\nERR_PNPM_FETCH_401 GET https://npm.pkg.example/@acme%2fui: Unauthorized\n{STEP_MARK} 1 1\n", + test_env::INSTALL_FAILED + ); + let why = install_failure(&ci_out, &[Some(1)], 0).unwrap(); + assert!( + why.contains("CI's install") && why.contains("ERR_PNPM_FETCH_401"), + "{why}" + ); + assert_eq!(NotRunWhy::of(&why), NotRunWhy::InstallFailed); + assert_eq!(install_failure("ok", &[Some(0), Some(0)], 1), None); + // CI's wrapper prints that marker when its install fails. + assert!(ci.wrap("true").contains(test_env::INSTALL_FAILED)); +} + +#[test] +fn the_runs_have_a_step_of_their_own_and_run_first_in_it() { + let files = vec!["apps/web/src/test/a.test.ts".to_string()]; + // The coding step ends with 300 seconds left: the runs are owed. + assert_eq!(proof_time(None, "h1", &files, 300, 0, true), ProofTime::Owe); + // What the seven runs did next: the fresh step reached them after its + // other checks, short again, with its one request spent. Now the owed + // runs go first, with the step's whole time, and are recorded. + assert_eq!(proof_time(None, "h1", &files, 880, 1, true), ProofTime::Run); + let done = RecordedRuns { + head: "h1".into(), + files: files.clone(), + result: Ok(Runs { + with: vec![FileRun { + code: Some(0), + output: String::new(), + }], + without: vec![FileRun { + code: Some(1), + output: "AssertionError: expected 'pagehide'".into(), + }], + }), + }; + // The check, however late in the step, reads them. + assert!(matches!( + proof_time(Some(&done), "h1", &files, 40, 1, true), + ProofTime::Recorded(Ok(_)) + )); + // A fix round's new head needs its own runs: owed again, up to the cap. + assert_eq!( + proof_time(Some(&done), "h2", &files, 40, 1, true), + ProofTime::Owe + ); + assert_eq!( + proof_time( + Some(&done), + "h2", + &files, + 40, + habits_check::MAX_PROOF_STEPS, + true + ), + ProofTime::NoTime + ); + // A path with no step to give records them as not run. + assert_eq!( + proof_time(None, "h1", &files, 40, 0, false), + ProofTime::NoTime + ); + // The step runs what it owes before every other check. + let src = include_str!("../mod.rs"); + let owed = src + .find("habits_check::run_owed(&work, || remaining_secs(start)).await;") + .expect("the owed runs run in the step"); + let first_check = src + .find("hand_off_unless_time_for!(\n proof,") + .expect("the proof check"); + assert!(owed < first_check); + let check = include_str!("../habits_check.rs"); + assert!(check.contains("l.proof_owed = head.clone();")); + assert!(!check.contains("std::mem::replace(&mut l.habits_waited, true)")); +} + +#[test] +fn a_loop_ci_runs_the_test_and_its_fixtures_are_not_tests() { + // The data pipeline's CI: a loop runs each test file with `python`. + let ci = TestEnv { + kind: test_env::Kind::Python, + install: vec!["uv pip install -r requirement.txt".into()], + test: vec![ + "for t in tests/test_*.py; do".into(), + "python \"$t\" || failed=1".into(), + "done".into(), + ], + ..Default::default() + }; + let diff: Vec<(String, String, String)> = [ + "dags/utils/schedule_common.py", + "tests/fixtures/camp_activities.json", + "tests/fixtures/camp_live_names.json", + "tests/test_camp_sport.py", + ] + .iter() + .map(|p| (p.to_string(), "modified".to_string(), String::new())) + .collect(); + let files = bench_files(&diff); + assert_eq!(files, vec!["tests/test_camp_sport.py"]); + let t = tree(&["tests/test_camp_sport.py", "requirement.txt"]); + let plan = bench_plan(&files, &t, None, Some(&ci), &|_| None); + assert_eq!( + plan.per_file, + vec![Ok("python tests/test_camp_sport.py".to_string())] + ); + // A file no command runs is not run, with why; the others still run. + let plan = bench_plan( + &["tests/test_camp_sport.py".into(), "scripts/check.sh".into()], + &t, + None, + Some(&ci), + &|_| None, + ); + assert!(plan.per_file[0].is_ok()); + assert!(plan.per_file[1].is_err()); + // `make test` and package scripts are read to their runner. + let read = + |p: &str| (p == "Makefile").then(|| "test:\n\tpython -m pytest -q tests\n".to_string()); + let mut make = TestEnv { + test: vec!["make test".into()], + ..Default::default() + }; + make.resolve_scripts(&tree(&["Makefile"]), &read); + assert_eq!( + make.file_command("tests/test_camp_sport.py").as_deref(), + Some("python -m pytest tests/test_camp_sport.py") + ); +} + +#[test] +fn whether_the_tests_ran_is_counted_with_why() { + let t = |path: &str, verdict: Verdict, detail: &str| TestResult { + path: path.into(), + verdict, + detail: detail.into(), + why: None, + }; + let tests = vec![ + t("a.test.ts", Verdict::Proven, "expected 1"), + t("b.test.ts", Verdict::NotRun, habits_check::INSTALL_FAILED), + t("c.spec.ts", Verdict::NotRun, habits_check::E2E_SPEC), + ]; + let ran = TestsRan::of(&tests); + assert_eq!((ran.files, ran.ran), (3, 1)); + assert_eq!( + ran.line(), + "Tests run with and without the change: 1 of 3 (not run: 1 install failed, 1 end-to-end spec)" + ); + assert_eq!(TestsRan::of(&[]).line(), ""); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 4bbdd6432..d09b4c4c7 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -7097,6 +7097,9 @@ async fn run_passes( } }; } + // Sandbox runs a step owed this one run first, with its whole budget, + // never after the other checks spent it. + habits_check::run_owed(&work, || remaining_secs(start)).await; hand_off_unless_time_for!( proof, "The proof check needs more time than this step has left" @@ -8563,7 +8566,7 @@ async fn run_repo_pipeline( }; // This path has no step of its own to give: with too little time the // tests are recorded as not run, with why. - ledger.update(|l| l.habits_waited = true); + ledger.update(|l| l.no_proof_step = true); let habits_pr = match habits_check::gate( &work, &mut evidence, diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index e799e87d2..9105e8780 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -1036,10 +1036,26 @@ pub struct Ledger { /// What the tests and scope check last came to. #[serde(default)] pub habits_outcome: Option, String>>, - /// That check has asked once for a step of its own for its sandbox - /// runs: it never asks twice. + /// Read by nothing now: it made the sandbox runs ask for a step of + /// their own once a run, and a fresh step that came to them short again + /// recorded every changed test as not run. Older checkpoints carry it. #[serde(default)] pub habits_waited: bool, + /// The changed tests' two sandbox runs for a head and its files, run + /// first in a step of their own or by the check (`habits_check`). + #[serde(default)] + pub proof_runs: Option, + /// The head whose sandbox runs are owed to the next step, which runs + /// them before any other check (`habits_check::run_owed`). + #[serde(default)] + pub proof_owed: String, + /// How many steps of their own the sandbox runs have asked for. + #[serde(default)] + pub proof_steps: u32, + /// This path has no step of its own to give the sandbox runs (a run + /// across repositories): short of time, they are recorded as not run. + #[serde(default)] + pub no_proof_step: bool, /// What the proof check last found (`None`: the judge couldn't answer). #[serde(default)] pub proof_findings: Option>, diff --git a/services/worker/src/passes/test_bug.rs b/services/worker/src/passes/test_bug.rs index 05bae27f1..02b81b726 100644 --- a/services/worker/src/passes/test_bug.rs +++ b/services/worker/src/passes/test_bug.rs @@ -57,6 +57,20 @@ impl Runner<'_> { Ok((test_package::step_codes(&output, n), output)) } + /// [`Self::run_at`] in a given test environment (`None`: none), not the + /// run's default one: the CI job that runs these steps' files. + pub async fn run_at_in( + &self, + sha: &str, + steps: &[Step], + env: Option<(common::test_env::TestEnv, String)>, + ) -> Result<(Vec>, String), String> { + let cmds: Vec<&str> = steps.iter().map(|s| s.cmd.as_str()).collect(); + let script = test_package::sandbox_script(steps, None); + let output = self.run_script_in(sha, &cmds, &script, env).await?; + Ok((test_package::step_codes(&output, steps.len()), output)) + } + /// Runs `script` on commit `sha` in the sandbox, in the run's test /// environment, once each of `cmds` (the commands it runs) passes the /// team's agent permissions: the output. `Err` says why nothing ran. @@ -65,6 +79,31 @@ impl Runner<'_> { sha: &str, cmds: &[&str], script: &str, + ) -> Result { + // A failing test's run has no planned files: the job that runs on + // every change from the root comes first. + let env = super::test_setup::for_run( + self.state, + self.github, + self.team_id, + self.owner, + self.repo, + sha, + sha, + self.run_id, + &[], + ) + .await; + self.run_script_in(sha, cmds, script, env).await + } + + /// [`Self::run_script_at`] in the test environment `env`. + pub async fn run_script_in( + &self, + sha: &str, + cmds: &[&str], + script: &str, + env: Option<(common::test_env::TestEnv, String)>, ) -> Result { if !self.sandbox_on() { return Err("no sandbox is set up here".into()); @@ -98,22 +137,7 @@ impl Runner<'_> { ) .with_egress(crate::agent::policy::sandbox_egress(self.state, self.team_id).await) // The proof step runs in the run's test environment too. - .with_test_env( - super::test_setup::for_run( - self.state, - self.github, - self.team_id, - self.owner, - self.repo, - sha, - sha, - self.run_id, - // A failing test's run has no planned files: the job that - // runs on every change from the root comes first. - &[], - ) - .await, - ); + .with_test_env(env); let source = sandbox .ensure_source(self.run_id, sha, || { self.github.download_tarball(self.owner, self.repo, sha)