From ae344ea2bd656b3a4dd3ea96ee176a6224476a5a Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 17 Nov 2026 16:03:23 -0500 Subject: [PATCH 1/2] A bug is reproduced on the base before it is planned; people's answers decide scope The planner runs the ticket's inputs through the base code (reproduce_on_base) and writes ## Reproduce: inputs with stored variants, the command and its output, the wrong line. The fix goes in that line's mechanism; questions a lookup answers are looked up first; a diff rewriting a path for a few named records goes back; new tests run on the base the way CI runs them, loops included, and an unproven bug fix says Unverified. A person's answer or comment moves an out-of-scope item in at seed and every round, and a revert of it is a breach. --- docs/coder-loop.md | 49 ++ .../incidents/rp_reproduce_before_planning.md | 31 + .../incidents/sn_person_answer_moves_scope.md | 7 + services/common/src/agent_policy/registry.rs | 1 + services/common/src/lib.rs | 3 + services/common/src/repro_first.rs | 689 ++++++++++++++++++ services/common/src/scope_ledger.rs | 95 +++ services/common/src/test_env.rs | 211 +++++- services/common/src/tool_registry.rs | 1 + services/worker/src/passes/habits_check.rs | 74 +- .../incidents/rp_reproduce_before_planning.rs | 263 +++++++ .../incidents/sn_person_answer_moves_scope.rs | 113 +++ services/worker/src/passes/minimal_change.rs | 88 +++ services/worker/src/passes/mod.rs | 12 +- services/worker/src/passes/plan.rs | 47 ++ services/worker/src/passes/plan_shape.rs | 2 +- services/worker/src/passes/reproduce.rs | 257 +++++++ services/worker/src/passes/resume.rs | 26 +- services/worker/src/passes/scope_ledger.rs | 85 ++- services/worker/src/passes/test_bug.rs | 34 +- 20 files changed, 2054 insertions(+), 34 deletions(-) create mode 100644 docs/incidents/rp_reproduce_before_planning.md create mode 100644 docs/incidents/sn_person_answer_moves_scope.md create mode 100644 services/common/src/repro_first.rs create mode 100644 services/worker/src/passes/incidents/rp_reproduce_before_planning.rs create mode 100644 services/worker/src/passes/incidents/sn_person_answer_moves_scope.rs create mode 100644 services/worker/src/passes/reproduce.rs diff --git a/docs/coder-loop.md b/docs/coder-loop.md index 24c710f4c..62ed64720 100644 --- a/docs/coder-loop.md +++ b/docs/coder-loop.md @@ -202,6 +202,16 @@ The causes were in the loop, not only in prompt wording: comment on the pull request, and the ledger records who moved it in. (`incidents::sl_scope_decided_once`) + What people say decides scope as they say it (`Ledger::take_people`). + When the ledger is seeded, and on each round's comments (the habits check + and the planned-work rounds), an out-of-scope entry that a person's answer + or comment asks for moves into scope and records who asked. No + `Scope change:` line is needed. From then on, a diff that takes that work + out is a breach that goes back to be put back. A comment that keeps the + item out moves nothing. One run replied "Understood" to a reviewer's answer + and then reverted the work the answer asked for + (`incidents::sn_person_answer_moves_scope`). + 10. **The description describes the head.** On every push the description is rebuilt from the head's facts (`description::build`; Problem, Changes, Risk, Verification). The written @@ -221,6 +231,45 @@ The causes were in the loop, not only in prompt wording: that asks an open product question. (`incidents::sm_description_of_the_head`) +11. **A bug is reproduced before it is planned.** + For a bug, the planner has `reproduce_on_base` (`passes::reproduce`). The + tool runs one call or command in the sandbox on the base branch's head, in + the run's test environment, and returns its exit code and output. Each run + is kept. + + design.md has a `## Reproduce` section (`common::repro_first::reproduce_gaps`) + with these fields: + - `Inputs:` lists the ticket's ids and names, with every stored variant a + read-only lookup found, and says where they came from. + - `Ran on base:` is a command this run ran with the tool. + - `Output:` quotes what that command printed. + - `Wrong line:` names the `path:line` where the existing code goes wrong. + + A run that tried and can't reproduce writes `Unverified:` with why. It is + kept as unverified, never skipped silently. + + The fix goes in the mechanism the wrong line is in (`reuse_gaps`). + `## Smallest change` names it, or says why it can't hold the fix. A plan + that adds a new resolution path beside it (a keyword match, a new + resolver) goes back. + + A question the plan decides with a default goes back unless it carries + `Looked up: ` or `No lookup settles it: `. This + applies when a page load or a query would answer it (`question_gaps`). + + After the build: + - **Diff size.** A diff that changes more than 40 lines of code (map and + list entries aside) for a ticket that names 1 to 12 records goes back to + be narrowed (`minimal_change::whole_path`). A `Wider than the ticket:` + line keeps it, with the reason. + - **Fail on the base.** Each new test runs on the base and on the head the + way CI runs it. That includes a CI loop such as `for t in tests/test_*.py; + do python "$t"` (`TestEnv::file_command`, `habits_check::file_cmd`). A + bug fix that no test was shown to fail on the base for says `Unverified:` + in its description. + + (`incidents::rp_reproduce_before_planning`) + ## What is deterministic Everything above except the model's own writing: the searches, section checks, diff --git a/docs/incidents/rp_reproduce_before_planning.md b/docs/incidents/rp_reproduce_before_planning.md new file mode 100644 index 000000000..e6d36879c --- /dev/null +++ b/docs/incidents/rp_reproduce_before_planning.md @@ -0,0 +1,31 @@ +# rp. `rp_reproduce_before_planning` + +**What happened:** A data-pipeline ticket named four camps that were filed under the wrong sport. The pipeline already had an overrides table for exactly this case, with entries for those camps. Its lookup matched exact names, though, and the vendor appends "-Half Day" or "-Full Day", so the entries never matched: the lookup returned nothing for each of the ticket's names on the base. + +The run's notes said so, then planned a keyword step beside the table. The diff was +595/-186 across the pipeline: a moved extractor, keyword matching, new logging and a fixture. It also moved other programs to another lookup, which its own reviewer flagged as out of scope, and it asked two questions on the pull request that one page load answered. + +The new test was never run on the base. The repository's CI runs each test file in a `python "$t"` loop, which CoderHelm couldn't narrow to one file, so the test was recorded as not run and the description said nothing about it. The right change stripped the suffix in the lookup and added two entries (+49/-1, mostly a test of the exact stored names), and that test fails on the base. + +Across the 53 runs audited: +- 8 of the 10 bug tickets that wrote code ran nothing before their first edit; +- 6 diffs of 300 lines or more answered a ticket that named 1 to 10 records; +- none of the 17 runs whose tests were checked had a test shown to fail on the base. + +**The guarantee:** +- **Reproduce first.** A bug plan has a `## Reproduce` section with: + - the ticket's exact inputs and their stored variants, with where they came from; + - a command this run ran on the base with `reproduce_on_base`, with its output quoted; + - the line where the existing code goes wrong. + + A run that tried and couldn't reproduce writes `Unverified:` with why. +- **Fix the mechanism found.** The fix goes in the mechanism that the wrong line is in. A new resolution path beside it goes back to the planner. +- **Look questions up first.** A question that a page load or a query answers is looked up before it is decided with a default. +- **Size the diff to the ticket.** A diff that rewrites a code path for a few named records goes back to be narrowed, unless a `Wider than the ticket:` line gives the reason. +- **Fail on the base.** Each new test runs on the base and on the head, the way CI runs it, even when CI runs it in a loop. A bug fix with no test shown to fail on the base says `Unverified:` in its description. + +**Where it's enforced:** +- `common::repro_first`; +- `passes::reproduce` (the tool, and `plan_gaps` in the plan check); +- `minimal_change::whole_path`; +- `common::test_env::TestEnv::file_command`; +- `habits_check::file_cmd` and `UNVERIFIED_FIX`. diff --git a/docs/incidents/sn_person_answer_moves_scope.md b/docs/incidents/sn_person_answer_moves_scope.md new file mode 100644 index 000000000..12f8d1fef --- /dev/null +++ b/docs/incidents/sn_person_answer_moves_scope.md @@ -0,0 +1,7 @@ +# sn. `sn_person_answer_moves_scope` + +**What happened:** A plan left a page type out of scope, decided with a default. A reviewer answered on the pull request that those pages should cover both rows. The run replied "Understood", then reverted the work on those pages as out of scope. The scope ledger was seeded only from the ticket's acceptance criteria and the plan, and a person's comment counted only when the coder itself wrote a `Scope change:` line quoting it. + +**The guarantee:** What people say decides scope as they say it. When the ledger is seeded, and on every round's comments, an out-of-scope entry that a person's answer or comment asks for moves into scope and records who asked. From then on, a diff that takes that work out is a breach that goes back to be put back. A comment that keeps the item out moves nothing. + +**Where it's enforced:** `common::scope_ledger::Ledger::take_people`, `scope_ledger::breaches` (reverted items), `passes::scope_ledger::{people, load_or_seed, held, load_with_people}`. diff --git a/services/common/src/agent_policy/registry.rs b/services/common/src/agent_policy/registry.rs index 393857d7d..5979cdf2c 100644 --- a/services/common/src/agent_policy/registry.rs +++ b/services/common/src/agent_policy/registry.rs @@ -247,6 +247,7 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("restore_file", Risk::Write), ("run_codegen", Risk::Write), ("run_checks", Risk::Write), + ("reproduce_on_base", Risk::Write), // A team skill's own script in the sandbox (read-only GitHub token at // most), and the run's outputs kept in CoderHelm. ("run_skill_script", Risk::Write), diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index d25943501..6d4638326 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -208,6 +208,9 @@ pub mod pr_template; pub mod preview; /// What a fix must show before it is committed and pushed. pub mod push_gate; +/// A bug reproduced on the base before code is planned, fixed in the +/// mechanism the reproduction lands in, questions looked up first. +pub mod repro_first; pub mod run_prs; /// Scope decided once at plan time, held in every round and in the /// description. diff --git a/services/common/src/repro_first.rs b/services/common/src/repro_first.rs new file mode 100644 index 000000000..e5e72ec55 --- /dev/null +++ b/services/common/src/repro_first.rs @@ -0,0 +1,689 @@ +//! A bug is reproduced on the base before any code is planned, and the fix +//! goes in the mechanism the reproduction lands in. +//! +//! A ticket named four camps filed under the wrong sport. The camps' names +//! carried a suffix ("Squash Camp-Half Day"), and the existing overrides +//! table matched names exactly, so its entries for those camps never +//! matched. The run's own notes said as much, then planned a keyword +//! matcher beside the table, rewrote how every camp of that source got its +//! sport, moved other programs to a different lookup and asked the team a +//! question one page load answered. The right change stripped the suffix in +//! the lookup and added two entries, with a test built from the exact names +//! stored on staging that failed on the base. +//! +//! The rules here, pure text, read by the plan check: +//! +//! - **`## Reproduce`** ([`reproduce_gaps`]): a bug plan writes the exact +//! inputs (the ticket's ids and names, with every variant a read-only +//! lookup found), the call or command it ran on the base with its actual +//! output, and the one line where the existing code goes wrong. The +//! command must be one this run ran on the base (`reproduce_on_base`, +//! [`Attempt`]), and the output is quoted from what came back. A run that +//! truly can't reproduce writes `Unverified:` with why; it is kept as +//! unverified, never skipped silently. +//! - **Fix the mechanism found** ([`reuse_gaps`]): when the wrong line is +//! in an existing lookup, table or mapping, `## Smallest change` names it +//! and changes it, or says why it can't; a plan that adds a new +//! resolution path beside it goes back. +//! - **Questions are looked up first** ([`question_gaps`]): a question the +//! plan decides with a default, about what a page shows or what the data +//! holds, carries what the lookup showed (`Looked up:`) or why no lookup +//! settles it (`No lookup settles it:`). +//! - **The ticket's records** ([`ticket_ids`]): the ids and quoted names a +//! ticket names, for the reproduction's inputs and for sizing the diff +//! against the ticket (`minimal_change`). + +use serde::{Deserialize, Serialize}; + +/// The plan's section. +pub const HEADING: &str = "## Reproduce"; +/// The planner's tool that runs a call or command on the base. +pub const TOOL: &str = "reproduce_on_base"; + +const INPUTS: &str = "inputs:"; +const RAN: &str = "ran on base:"; +const OUTPUT: &str = "output:"; +const WRONG: &str = "wrong line:"; +const UNVERIFIED: &str = "unverified:"; +const FIELDS: &[&str] = &[INPUTS, RAN, OUTPUT, WRONG, UNVERIFIED]; + +/// One run of the reproduction tool on the base tree. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Attempt { + pub command: String, + /// The command's exit code; `None` when the sandbox gave none. + #[serde(default)] + pub exit: Option, + /// What it printed (the end of it, when long). + #[serde(default)] + pub output: String, + /// Why it couldn't run, when it didn't. + #[serde(default)] + pub error: String, +} + +impl Attempt { + /// Whether the command ran and gave an answer. + pub fn ran(&self) -> bool { + self.error.is_empty() && self.exit.is_some() + } +} + +/// The plan's `## Reproduce` section, field by field. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Reproduce { + pub inputs: String, + pub ran: String, + pub output: String, + pub wrong_line: String, + pub unverified: String, +} + +fn lower(s: &str) -> String { + s.to_lowercase() +} + +fn flat(s: &str) -> String { + s.split_whitespace().collect::>().join(" ") +} + +/// A markdown section's body: from its heading to the next `## ` heading. +pub fn section<'a>(text: &'a str, heading: &str) -> Option<&'a str> { + let h = lower(heading); + let mut start = None; + let mut offset = 0; + for line in text.split_inclusive('\n') { + let t = line.trim(); + if let Some(s) = start { + if t.starts_with("## ") { + return Some(&text[s..offset]); + } + } else if lower(t) == h { + start = Some(offset + line.len()); + } + offset += line.len(); + } + start.map(|s| &text[s..]) +} + +/// Reads the section's fields. A field runs from its label to the next +/// label; fences and bullets are kept as written. +pub fn read(design: &str) -> Option { + let body = section(design, HEADING)?; + let mut out = Reproduce::default(); + let mut current: Option<&str> = None; + for line in body.lines() { + let t = line.trim().trim_start_matches(['-', '*']).trim(); + let t = t.trim_start_matches("**"); + let l = lower(t); + let label = FIELDS + .iter() + .find(|f| l.starts_with(**f) || l.replacen("**", "", 2).starts_with(**f)); + let rest = if let Some(f) = label { + current = Some(f); + let cut = t.to_lowercase().find(':').map_or(0, |i| i + 1); + t[cut..].trim().trim_start_matches("**").trim().to_string() + } else { + line.to_string() + }; + let slot = match current { + Some(INPUTS) => &mut out.inputs, + Some(RAN) => &mut out.ran, + Some(OUTPUT) => &mut out.output, + Some(WRONG) => &mut out.wrong_line, + Some(UNVERIFIED) => &mut out.unverified, + _ => continue, + }; + if !slot.is_empty() { + slot.push('\n'); + } + slot.push_str(&rest); + } + for s in [ + &mut out.inputs, + &mut out.ran, + &mut out.output, + &mut out.wrong_line, + &mut out.unverified, + ] { + *s = s.trim().to_string(); + } + Some(out) +} + +fn is_uuid(w: &str) -> bool { + let parts: Vec<&str> = w.split('-').collect(); + parts.len() == 5 + && [8, 4, 4, 4, 12] + .iter() + .zip(&parts) + .all(|(n, p)| p.len() == *n && p.chars().all(|c| c.is_ascii_hexdigit())) +} + +/// The records a ticket names: its uuids, numbered ids (`id 8204`, `#8204`, +/// `(8204)`), and backticked or quoted names, each once. +pub fn ticket_ids(ticket: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut push = |s: &str| { + let s = s.trim(); + if !s.is_empty() && !out.iter().any(|o| o.eq_ignore_ascii_case(s)) { + out.push(s.to_string()); + } + }; + let words: Vec<&str> = ticket + .split(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | ',' | ';' | '[' | ']')) + .collect(); + for (i, w) in words.iter().enumerate() { + let w = w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-'); + if is_uuid(w) { + push(w); + continue; + } + let digits = w.trim_start_matches('#'); + let numbered = digits.len() >= 3 && digits.chars().all(|c| c.is_ascii_digit()); + let after_id = i > 0 && { + let p = words[i - 1].to_lowercase(); + p == "id" || p == "id:" || p.ends_with("_id") || p.ends_with("id:") + }; + if numbered && (after_id || words[i].starts_with('#')) { + push(digits); + } + } + for (open, close) in [('`', '`'), ('"', '"'), ('\u{201c}', '\u{201d}')] { + let mut rest = ticket; + while let Some(i) = rest.find(open) { + let after = &rest[i + open.len_utf8()..]; + let Some(j) = after.find(close) else { break }; + let s = &after[..j]; + if (3..=80).contains(&s.trim().len()) && !s.contains('\n') && !s.contains("://") { + push(s); + } + rest = &after[j + close.len_utf8()..]; + } + } + out +} + +/// What a bug plan's `## Reproduce` misses, one line each for the +/// send-back. `ticket` is the ticket's words; `attempts` the runs of +/// [`TOOL`] this run made; `can_run` says the sandbox can run on the base; +/// `can_look_up` says the team has a data source connected. +pub fn reproduce_gaps( + design: &str, + ticket: &str, + attempts: &[Attempt], + can_run: bool, + can_look_up: bool, +) -> Vec { + let Some(r) = read(design) else { + return vec![format!( + "design.md lacks `{HEADING}`. This is a bug: before planning code, take the exact names or ids from the ticket (and every variant a read-only lookup finds in the real data), run them through the current code on the base with `{TOOL}`, and write `Inputs:`, `Ran on base:` (the command), `Output:` (what it printed) and `Wrong line:` (`path:line` and the code there that goes wrong)." + )]; + }; + let mut out = Vec::new(); + let ids = ticket_ids(ticket); + let inputs = lower(&r.inputs); + let missing: Vec<&String> = ids.iter().filter(|i| !inputs.contains(&lower(i))).collect(); + if r.inputs.is_empty() { + out.push(format!( + "`{HEADING}` has no `Inputs:`. List the exact names or ids the ticket gives, as they are stored, with every variant a read-only lookup finds." + )); + } else if !missing.is_empty() { + out.push(format!( + "`{HEADING}` `Inputs:` leaves out what the ticket names: {}. Reproduce with each of them.", + missing + .iter() + .take(6) + .map(|m| format!("`{m}`")) + .collect::>() + .join(", ") + )); + } + if can_look_up && !r.inputs.is_empty() && !cites_lookup(&r.inputs) { + out.push(format!( + "`{HEADING}` `Inputs:` doesn't say where the names came from. Query the connected data read-only for the ticket's names (a `LIKE` on the name, not an exact match) and list every variant as stored, citing the lookup." + )); + } + if !r.unverified.is_empty() { + if can_run && attempts.is_empty() { + out.push(format!( + "`{HEADING}` says `Unverified:` but this run never tried `{TOOL}`. Run the call on the base first; only a run that can't reproduce is unverified." + )); + } + if !has_location(&r.wrong_line) { + out.push(wrong_line_gap()); + } + return out; + } + if r.ran.is_empty() { + out.push(format!( + "`{HEADING}` has no `Ran on base:`. Run the ticket's inputs through the current code with `{TOOL}` (for example `python -c \"from module import fn; print(fn(''))\"`) and write the command and its output. When it truly can't run, write `Unverified: `." + )); + } else { + match matching_attempt(&r.ran, attempts) { + None => out.push(format!( + "`{HEADING}` `Ran on base:` is not a command this run ran. Run it with `{TOOL}` and quote that command." + )), + Some(a) if !a.ran() => out.push(format!( + "`{HEADING}`: `{}` didn't run on the base ({}). Fix the command and run it again, or write `Unverified: `.", + common_trunc(&a.command, 120), + if a.error.is_empty() { "no result" } else { a.error.as_str() } + )), + Some(a) => { + if r.output.is_empty() || !quoted_from(&r.output, &a.output) { + out.push(format!( + "`{HEADING}` `Output:` is not what `{}` printed. Quote its output as it came back.", + common_trunc(&a.command, 120) + )); + } + } + } + } + if !has_location(&r.wrong_line) { + out.push(wrong_line_gap()); + } + out +} + +fn wrong_line_gap() -> String { + format!( + "`{HEADING}` `Wrong line:` doesn't name where the existing code goes wrong. Write `path:line` and the code on that line (backticked), the one line the reproduction shows is wrong." + ) +} + +fn common_trunc(s: &str, n: usize) -> String { + let s = flat(s); + if s.chars().count() <= n { + s + } else { + format!("{}...", s.chars().take(n).collect::()) + } +} + +fn cites_lookup(inputs: &str) -> bool { + let l = lower(inputs); + [ + "lookup", + "looked up", + "query", + "queried", + "select ", + "database", + "staging", + "prod", + "page", + "check_url", + "probe", + "rows", + "stored", + ] + .iter() + .any(|w| l.contains(w)) + || l.split(|c: char| !c.is_ascii_alphanumeric()).any(|w| { + w.len() >= 2 && w.starts_with('l') && w[1..].chars().all(|c| c.is_ascii_digit()) + }) +} + +/// `path:line`, a file path with a line number. +fn has_location(s: &str) -> bool { + s.split(|c: char| c.is_whitespace() || c == '`' || c == '(' || c == ')') + .any(|w| { + let Some((path, line)) = w.rsplit_once(':') else { + return false; + }; + let line = line.split(['-', ',']).next().unwrap_or(""); + path.contains('.') + && !path.contains("://") + && !line.is_empty() + && line.chars().all(|c| c.is_ascii_digit()) + }) +} + +fn strip_fence(s: &str) -> String { + s.lines() + .filter(|l| !l.trim_start().starts_with("```")) + .collect::>() + .join("\n") +} + +/// The attempt a written command is: the same command once whitespace and +/// backticks are set aside. +pub fn matching_attempt<'a>(written: &str, attempts: &'a [Attempt]) -> Option<&'a Attempt> { + let w = flat(&strip_fence(written).replace('`', "")); + if w.is_empty() { + return None; + } + attempts.iter().rev().find(|a| { + let c = flat(&a.command); + !c.is_empty() && (c == w || w.contains(&c) || (c.len() >= 20 && c.contains(&w))) + }) +} + +/// Whether the written output is quoted from what the command printed: +/// each of its non-empty lines appears in the real output. +pub fn quoted_from(written: &str, real: &str) -> bool { + let real = flat(real); + let lines: Vec = strip_fence(written) + .lines() + .map(|l| flat(l.trim().trim_matches('`'))) + .filter(|l| !l.is_empty()) + .collect(); + !lines.is_empty() && lines.iter().all(|l| real.contains(l.as_str())) +} + +/// Backticked identifiers on the wrong line: the function, table or map +/// the reproduction lands in. +pub fn wrong_names(wrong_line: &str) -> Vec { + let mut out = Vec::new(); + for (i, part) in wrong_line.split('`').enumerate() { + if i % 2 == 0 { + continue; + } + for tok in part.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) { + let ident = tok.len() >= 4 + && tok + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && (tok.contains('_') || tok.chars().skip(1).any(|c| c.is_ascii_uppercase())); + if ident && !out.iter().any(|o| o == tok) { + out.push(tok.to_string()); + } + } + } + out +} + +fn wrong_path(wrong_line: &str) -> Option { + wrong_line + .split(|c: char| c.is_whitespace() || c == '`' || c == '(' || c == ')') + .find_map(|w| { + let (path, line) = w.rsplit_once(':')?; + (path.contains('.') && line.chars().next().is_some_and(|c| c.is_ascii_digit())) + .then(|| path.to_string()) + }) +} + +/// Words that put a new resolution path beside an existing lookup. +const NEW_PATH: &[&str] = &[ + "keyword match", + "keyword step", + "keyword fallback", + "substring match", + "fuzzy match", + "new resolver", + "new resolution", + "resolution path", + "new lookup", + "second lookup", + "new matching", + "rewrite the resolution", + "rewrites the resolution", + "replace the lookup", + "replaces the lookup", + "instead of the override", + "bypass the override", + "fallback chain", +]; + +const CANT: &[&str] = &["can't", "cannot", "can not", "doesn't hold", "won't hold"]; + +/// What a bug plan misses about the mechanism its reproduction landed in: +/// `## Smallest change` must name it and change it, or say why it can't, +/// and no new resolution path goes beside it. `smallest` is the plan's +/// Smallest change section; `proposing` the words that propose (proposal, +/// design without Must not change, tasks). +pub fn reuse_gaps(design: &str, smallest: &str, proposing: &str) -> Vec { + let Some(r) = read(design) else { + return Vec::new(); + }; + let names = wrong_names(&r.wrong_line); + let path = wrong_path(&r.wrong_line); + if names.is_empty() && path.is_none() { + return Vec::new(); + } + let s = lower(smallest); + let says_why = CANT.iter().any(|w| s.contains(w)); + let mut out = Vec::new(); + let named = names.iter().any(|n| s.contains(&lower(n))); + let first = names.first().cloned().or(path.clone()).unwrap_or_default(); + if !named && !says_why { + out.push(format!( + "The reproduction lands in `{first}`, and `## Smallest change` doesn't change it. Fix the lookup that already exists (its matching, or its entries) and name it there, or say why it can't hold the fix." + )); + } + let p = lower(proposing); + if let Some(w) = NEW_PATH.iter().find(|w| p.contains(*w)) { + if !says_why { + out.push(format!( + "The plan adds a new resolution path (\"{w}\") beside `{first}`, where the reproduction says the existing one goes wrong. Change `{first}` instead; a second path beside it is sent back unless `## Smallest change` says why the existing one can't hold the fix." + )); + } + } + out +} + +/// Words of a question a page load answers. +const PAGE_WORDS: &[&str] = &[ + "show", "appear", "visible", "display", "listed", "list ", "filter", "chip", "render", "page", + "see ", +]; +/// Words of a question a read-only query answers. +const DATA_WORDS: &[&str] = &[ + "active", + "inactive", + "exist", + "how many", + "count", + "stored", + "rows", + "linked", + "mapped", + "which records", + "duplicate", + "value of", + "null", +]; + +/// How a question can be settled by looking. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Lookup { + Page, + Data, +} + +/// The lookup that would answer a question, if one would. +pub fn answered_by(question: &str) -> Option { + let q = lower(question); + if PAGE_WORDS.iter().any(|w| q.contains(w)) { + Some(Lookup::Page) + } else if DATA_WORDS.iter().any(|w| q.contains(w)) { + Some(Lookup::Data) + } else { + None + } +} + +const LOOKED: &[&str] = &[ + "looked up:", + "looked up ", + "no lookup settles it", + "checked:", + "loaded ", + "queried ", + "check_url", + "probe_page", +]; + +/// Each question the plan decides with a default (or still asks) that a +/// page load or a query would answer, and that says nothing of the lookup. +/// `questions` are the question lines and the entries decided with a +/// default, as written. +pub fn question_gaps(questions: &[String]) -> Vec { + let mut out = Vec::new(); + for q in questions { + let Some(kind) = answered_by(q) else { + continue; + }; + let l = lower(q); + if LOOKED.iter().any(|w| l.contains(w)) { + continue; + } + let how = match kind { + Lookup::Page => "load the page that shows it (`check_url`, with a cache-busting parameter) and read whether it is there", + Lookup::Data => "query the connected data read-only for it", + }; + out.push(format!( + "Before deciding \"{}\", {how}. Write what it showed after it (`Looked up: `), or `No lookup settles it: `; a question a lookup answers is never asked.", + common_trunc(q.trim().trim_start_matches(['-', '*']).trim(), 140) + )); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const TICKET: &str = "Observed\nWhen filtering for Volleyball, Squash Camp-Half Day (a0000002-0000-4000-8000-000000000002) shows.\nExpected\nSquash Camp- Full Day (a0000003-0000-4000-8000-000000000003)"; + + fn design(reproduce: &str) -> String { + format!( + "## Reuse\n- `CAMP_OVERRIDES`\n\n## Reproduce\n{reproduce}\n\n## Smallest change\nx\n" + ) + } + + fn attempt(cmd: &str, out: &str) -> Attempt { + Attempt { + command: cmd.into(), + exit: Some(0), + output: out.into(), + error: String::new(), + } + } + + const CMD: &str = + "python -c \"from dags.common import get_override as g; print(g('Squash Camp-Half Day'))\""; + + fn good() -> String { + design(&format!( + "Inputs: a0000002-0000-4000-8000-000000000002, a0000003-0000-4000-8000-000000000003; staging lookup L2: `Squash Camp-Half Day`, `Squash Camp-Full Day`, `Squash Camp- Full Day`\nRan on base: `{CMD}`\nOutput:\n```\nNone\n```\nWrong line: dags/common.py:99 `return CAMP_OVERRIDES.get(normalized)` matches the whole name, suffix included." + )) + } + + #[test] + fn the_ticket_names_its_records() { + let ids = ticket_ids(TICKET); + assert_eq!( + ids, + vec![ + "a0000002-0000-4000-8000-000000000002", + "a0000003-0000-4000-8000-000000000003" + ] + ); + let ids = + ticket_ids("Group id 8204 and #8214, the `Hockey Camp` and \"Squash Camp\", not 2026."); + assert_eq!(ids, vec!["8204", "8214", "Hockey Camp", "Squash Camp"]); + } + + #[test] + fn a_reproduction_quotes_a_run_on_the_base() { + let a = vec![attempt(CMD, "===\nNone\n")]; + assert!( + reproduce_gaps(&good(), TICKET, &a, true, true).is_empty(), + "{:?}", + reproduce_gaps(&good(), TICKET, &a, true, true) + ); + // No section at all. + let g = reproduce_gaps("## Reuse\nx\n", TICKET, &a, true, true); + assert!(g[0].contains("lacks `## Reproduce`")); + // A command this run never ran. + let g = reproduce_gaps(&good(), TICKET, &[], true, true); + assert!( + g.iter().any(|l| l.contains("not a command this run ran")), + "{g:?}" + ); + // Output that isn't what came back. + let a2 = vec![attempt(CMD, "b0000001\n")]; + let g = reproduce_gaps(&good(), TICKET, &a2, true, true); + assert!(g.iter().any(|l| l.contains("is not what")), "{g:?}"); + // A ticket id left out of the inputs. + let d = good().replace("a0000003-0000-4000-8000-000000000003; ", ""); + let g = reproduce_gaps(&d, TICKET, &a, true, true); + assert!(g.iter().any(|l| l.contains("a0000003")), "{g:?}"); + // Inputs from nowhere when data could be looked up. + let d = good().replace("staging lookup L2: ", ""); + let g = reproduce_gaps(&d, TICKET, &a, true, true); + assert!( + g.iter().any(|l| l.contains("where the names came from")), + "{g:?}" + ); + assert!(reproduce_gaps(&d, TICKET, &a, true, false).is_empty()); + // No wrong line. + let d = good().replace("dags/common.py:99", "the lookup"); + let g = reproduce_gaps(&d, TICKET, &a, true, true); + assert!(g.iter().any(|l| l.contains("Wrong line:")), "{g:?}"); + } + + #[test] + fn unverified_is_kept_only_after_trying() { + let d = design("Inputs: a0000002-0000-4000-8000-000000000002 a0000003-0000-4000-8000-000000000003 from staging rows\nUnverified: the module imports Airflow, which the sandbox can't install\nWrong line: dags/common.py:99 `CAMP_OVERRIDES.get`"); + let g = reproduce_gaps(&d, TICKET, &[], true, true); + assert!(g.iter().any(|l| l.contains("never tried")), "{g:?}"); + let failed = Attempt { + command: CMD.into(), + exit: Some(1), + output: "ModuleNotFoundError".into(), + error: String::new(), + }; + assert!(reproduce_gaps(&d, TICKET, &[failed], true, true).is_empty()); + // With no sandbox it can't be tried. + assert!(reproduce_gaps(&d, TICKET, &[], false, true).is_empty()); + } + + #[test] + fn the_fix_goes_in_the_lookup_the_reproduction_lands_in() { + let d = good(); + // A new keyword step beside the override table. + let g = reuse_gaps( + &d, + "Add `resolve_camp_sport_id`: override first, then a keyword match on the name.", + "a keyword step is added after the override", + ); + assert_eq!(g.len(), 2, "{g:?}"); + assert!(g[0].contains("`CAMP_OVERRIDES`")); + assert!(g[1].contains("keyword")); + // The lookup itself, fixed. + let g = reuse_gaps( + &d, + "Strip the trailing `-Half Day`/`-Full Day` before `CAMP_OVERRIDES.get`; add 2 entries.", + "strip the suffix in the lookup", + ); + assert!(g.is_empty(), "{g:?}"); + // A stated reason keeps a new path. + let g = reuse_gaps( + &d, + "`CAMP_OVERRIDES` can't hold this: the source gives no name.", + "a keyword match", + ); + assert!(g.is_empty(), "{g:?}"); + assert_eq!( + wrong_names("dags/a.py:9 `return MAP.get(k)` in `get_sport`"), + vec!["get_sport"] + ); + } + + #[test] + fn a_question_a_lookup_answers_is_looked_up_first() { + let q = vec![ + "- Inactive Squash camps: decided with the default: they show under the filter as today".to_string(), + "- Brand colours: decided with the default: unchanged".to_string(), + "- Is the sport active in staging? Looked up: L7 shows active=false".to_string(), + ]; + let g = question_gaps(&q); + assert_eq!(g.len(), 1, "{g:?}"); + assert!(g[0].contains("check_url")); + assert_eq!(answered_by("How many rows are linked?"), Some(Lookup::Data)); + assert_eq!(answered_by("Which copy do we use?"), None); + } +} diff --git a/services/common/src/scope_ledger.rs b/services/common/src/scope_ledger.rs index 38e083454..1a5704e3b 100644 --- a/services/common/src/scope_ledger.rs +++ b/services/common/src/scope_ledger.rs @@ -111,11 +111,24 @@ pub struct Breach { pub path: String, /// The mark found (a path, or a name on an added line). pub mark: String, + /// The diff takes out an item a person or a criterion moved into + /// scope (`why` says who asked), instead of bringing back one left out. + #[serde(default)] + pub reverted: bool, } impl Breach { /// The instruction for the round that fixes it. pub fn instruction(&self) -> String { + if self.reverted { + return format!( + "`{}` takes out \"{}\" (`{}`), which is in scope: {}. Put it back; what a person asked for is never reverted as out of scope.", + self.path, + self.item.trim_end_matches('.'), + self.mark, + self.why.trim_end_matches('.'), + ); + } format!( "`{}` brings back \"{}\" (`{}`), which the plan decided is out of scope: {}. Take it out of the code and its tests, or, only when an acceptance criterion or a person's comment asks for it, add `Scope change: {}: ` to your Evidence.", self.path, @@ -646,6 +659,34 @@ impl Ledger { (accepted, refused) } + /// What people said decides scope as they say it: each out-of-scope + /// entry that a person's answer or comment asks for (`said`: who, and + /// what they wrote; matched as [`asked_by`] matches a criterion) moves + /// in, recording who asked and their words. No `Scope change:` line is + /// needed. A reviewer once answered on a pull request that the path + /// pages should cover both rows; the run replied "Understood" and + /// reverted the path-page work as out of scope. A comment that keeps an + /// item out ("leave the path pages for a later ticket") moves nothing. + /// Returns a line for each item moved in. Run at seed and on each + /// round's comments. + pub fn take_people(&mut self, said: &[(String, String)]) -> Vec { + let mut moved = Vec::new(); + for e in self.entries.iter_mut().filter(|e| e.is_out()) { + let Some((who, text)) = said.iter().find(|(_, t)| person_asks_for(e, t)) else { + continue; + }; + let words: String = one_line(text).chars().take(160).collect(); + let who = if who.trim().is_empty() { + "a person" + } else { + who.trim() + }; + e.moved_in = format!("{who} asked for it: \"{words}\""); + moved.push(format!("\"{}\" moved into scope: {}", e.item, e.moved_in)); + } + moved + } + /// The out-of-scope entry a piece of planned work names (one of its /// marks, or its item said in full): that work is not built again. pub fn covers(&self, text: &str) -> Option<&Entry> { @@ -690,6 +731,31 @@ fn significant(text: &str) -> Vec { .collect() } +/// Words of a comment that keeps an item out rather than asking for it. +const KEEPS_OUT: &[&str] = &[ + "out of scope", + "leave out", + "leave it out", + "leave them out", + "leave the", + "not needed", + "no need", + "don't", + "do not", + "skip", + "separate ticket", + "later ticket", + "another ticket", + "not in this", +]; + +/// Whether a person's words ask for an out-of-scope entry: they cite it the +/// way a criterion would, and don't keep it out. +pub fn person_asks_for(e: &Entry, text: &str) -> bool { + let l = lower(text); + !KEEPS_OUT.iter().any(|w| l.contains(w)) && asked_by(e, &[text.to_string()]).is_some() +} + /// The criterion that asks for an entry's item, when one does. pub fn asked_by<'a>(e: &Entry, criteria: &'a [String]) -> Option<&'a String> { let said = format!("{} {}", e.item, e.marks.join(" ")); @@ -753,6 +819,26 @@ pub fn breaches(ledger: &Ledger, files: &[(String, String, String)]) -> Vec Vec impl Iterator { + patch + .lines() + .filter(|l| l.starts_with('-') && !l.starts_with("---")) + .map(|l| &l[1..]) +} + /// Phrases of a task that reach past the files it names. const OPEN_ENDED: &[&str] = &[ "any other caller", @@ -1400,6 +1494,7 @@ mod tests { why: "one id".into(), path: "apps/web/src/services/classService.ts".into(), mark: "/classes/".into(), + reverted: false, }]; let changed = vec![ "apps/web/src/services/classService.ts".to_string(), diff --git a/services/common/src/test_env.rs b/services/common/src/test_env.rs index 46fe275c7..1271837c5 100644 --- a/services/common/src/test_env.rs +++ b/services/common/src/test_env.rs @@ -284,13 +284,19 @@ pub fn from_workflows_for( let dir = s(step.get("working-directory")) .trim_start_matches("./") .to_string(); + // A step that runs tests keeps its whole script (a loop's + // body, a counter it sets), so a test file can be run the + // way the step runs it (`TestEnv::file_command`). + let step_tests = lines_of(&run) + .iter() + .any(|l| crate::ci_cover::is_check_command(l) && !is_install(l)); for line in lines_of(&run) { let line = if dir.is_empty() { line } else { format!("(cd {dir} && {line})") }; - if crate::ci_cover::is_check_command(&line) && !is_install(&line) { + if step_tests && !is_install(&line) { seen_test = true; env.test.push(line); env.env.extend(plain_env(step.get("env"))); @@ -367,6 +373,62 @@ fn common_step_dir(test: &[String]) -> String { } } +/// Interpreters that run a test file given its path. +const SCRIPT_RUNNERS: &[&str] = &["python", "python3", "node", "bash", "sh"]; + +/// A test step without its `(cd && ...)` wrapper: (dir, command). +fn unwrap_cd(line: &str) -> (String, String) { + if let Some(rest) = line.strip_prefix("(cd ") { + if let Some((dir, cmd)) = rest.split_once(" && ") { + let cmd = cmd.strip_suffix(')').unwrap_or(cmd); + return ( + dir.trim().trim_end_matches('/').to_string(), + cmd.trim().to_string(), + ); + } + } + (String::new(), line.trim().to_string()) +} + +/// A shell loop's head, `for in ; do`: its variable and globs. +fn loop_head(line: &str) -> Option<(String, Vec)> { + let rest = line.trim().strip_prefix("for ")?; + let (var, rest) = rest.split_once(" in ")?; + let list = rest.split(';').next()?.trim_end_matches(" do").trim(); + let globs: Vec = list + .split_whitespace() + .map(|g| { + g.trim_matches(['"', '\'']) + .trim_start_matches("./") + .to_string() + }) + .filter(|g| !g.is_empty() && !g.contains('$')) + .collect(); + let var = var.trim(); + (!var.is_empty() && !globs.is_empty()).then(|| (var.to_string(), globs)) +} + +/// The interpreter a loop body runs the loop's file with: `python "$t"` +/// gives `python`. +fn runs_var(line: &str, var: &str) -> Option { + let line = line.trim(); + for form in [ + format!("\"${var}\""), + format!("\"${{{var}}}\""), + format!("${{{var}}}"), + format!("${var}"), + ] { + if let Some(i) = line.find(&form) { + let runner = line[..i].trim(); + let first = runner.split_whitespace().next().unwrap_or(""); + if SCRIPT_RUNNERS.contains(&first) && !runner.contains(['|', ';', '&']) { + return Some(runner.to_string()); + } + } + } + None +} + fn quote(s: &str) -> String { format!("'{}'", s.replace('\'', "'\\''")) } @@ -497,6 +559,90 @@ bash -c {cmd}"#, ) } + /// The command that runs one test file (`file`, from the repository + /// root) the way CI runs its tests, or `None` when no test step can be + /// narrowed to it. CI may run a runner (`pytest`, `python -m + /// unittest`), a loop over test files (`for t in tests/test_*.py; do + /// python "$t"`), or the file by name. A data-pipeline repository ran + /// its tests with that loop, no runner CoderHelm knew, so a bug fix's + /// new test was never run on the base and the pull request said + /// nothing about it. + pub fn file_command(&self, file: &str) -> Option { + let safe = !file.is_empty() + && file + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '/')) + && !file.contains(".."); + if !safe { + return None; + } + let steps: Vec<(String, String)> = self.test.iter().map(|l| unwrap_cd(l)).collect(); + let in_dir = |dir: &str, cmd: String| -> Option { + if dir.is_empty() { + return Some(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. + 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); + } + } + } + } + // A loop over test files, its body running each one. + for (i, (dir, line)) in steps.iter().enumerate() { + let Some((var, globs)) = loop_head(line) else { + continue; + }; + let rel = if dir.is_empty() { + file + } else { + match file.strip_prefix(&format!("{dir}/")) { + Some(r) => r, + None => continue, + } + }; + if !globs.iter().any(|g| { + crate::skill_apply::glob_match(g, rel) && g.contains('/') == rel.contains('/') + }) { + continue; + } + // The body: the rest of this line after `do`, then the lines + // that follow it. + let after_do = line.split_once("; do").map(|(_, b)| b.to_string()); + let body = after_do + .into_iter() + .chain(steps.iter().skip(i + 1).map(|(_, l)| l.clone())); + for b in body { + if let Some(runner) = runs_var(&b, &var) { + return in_dir(dir, format!("{runner} {file}")); + } + if b.trim_start().starts_with("done") { + break; + } + } + } + // The file by name. + for (dir, line) in &steps { + let words: Vec<&str> = line.split_whitespace().collect(); + if words.len() == 2 + && SCRIPT_RUNNERS.contains(&words[0]) + && (format!("{dir}/{}", words[1]).trim_start_matches('/') == file + || words[1] == file) + { + return in_dir(dir, line.replace(words[1], file)); + } + } + None + } + /// What the coder is told: the environment is ready in every command, /// and how the tests run. pub fn coder_note(&self) -> String { @@ -628,6 +774,69 @@ jobs: .is_none()); } + /// A data-pipeline repository's CI: a loop runs each test file with + /// `python`, no runner CoderHelm knew. + const LOOP: &str = r#" +name: Tests +on: [pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - run: uv pip install --quiet "apache-airflow[postgres]==2.10.3" -r requirement.txt + - name: Run tests + env: + PYTHONHASHSEED: "0" + run: | + failed=0 + for t in tests/test_*.py; do + echo "::group::$t" + python "$t" || failed=1 + echo "::endgroup::" + done + exit $failed +"#; + + #[test] + fn one_test_file_runs_the_way_ci_runs_its_tests() { + let e = from_workflows(&[("t.yml".into(), LOOP.into())], &[]).unwrap(); + assert!( + e.test.iter().any(|t| t.contains("python \"$t\"")), + "{:?}", + e.test + ); + assert_eq!( + e.file_command("tests/test_camp_sport.py").as_deref(), + Some("python tests/test_camp_sport.py") + ); + // A file the loop doesn't run, and a path that isn't safe. + assert_eq!(e.file_command("dags/camp_sport.py"), None); + assert_eq!(e.file_command("tests/test_a.py; rm -rf /"), None); + // A runner takes the file. + let e = from_workflows(&[("t.yml".into(), PY.into())], &[]).unwrap(); + assert_eq!( + e.file_command("tests/test_a.py").as_deref(), + Some("python -m pytest tests/test_a.py") + ); + // A one-line loop, in a folder. + let mut e = TestEnv { + test: vec![ + "(cd etl && for t in tests/test_*.py; do python3 \"$t\" || exit 1; done)".into(), + ], + ..Default::default() + }; + assert_eq!( + e.file_command("etl/tests/test_a.py").as_deref(), + Some("(cd etl && python3 tests/test_a.py)") + ); + assert_eq!(e.file_command("tests/test_a.py"), None); + e.test = vec!["npm run build".into()]; + assert_eq!(e.file_command("tests/test_a.py"), None); + } + /// 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/common/src/tool_registry.rs b/services/common/src/tool_registry.rs index e59329b5f..1c0ccccea 100644 --- a/services/common/src/tool_registry.rs +++ b/services/common/src/tool_registry.rs @@ -117,6 +117,7 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("restore_file", Risk::Write), ("run_codegen", Risk::Write), ("run_checks", Risk::Write), + ("reproduce_on_base", Risk::Write), // A team skill's own script in the sandbox (read-only GitHub token at // most), and the run's outputs kept in CoderHelm. ("run_skill_script", Risk::Write), diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index ad5828f18..8a4789a4d 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -252,6 +252,33 @@ pub fn scoped_cmd(base_cmd: &str, file: &str) -> Option { .map(|c| c.replace(" --passWithNoTests", "")) } +/// The command that runs one test file on its own: the CI test command +/// CoderHelm knows, narrowed to the file, else the file run the way the CI +/// job's test step runs it (`TestEnv::file_command`). `Err` says why none +/// can, and the test is then recorded as not run, never as passing. +pub fn file_cmd( + ci_cmd: Option<&str>, + env: Option<&common::test_env::TestEnv>, + file: &str, +) -> Result { + if let Some(c) = ci_cmd.and_then(|c| scoped_cmd(c, file)) { + return Ok(c); + } + if let Some(c) = env.and_then(|e| e.file_command(file)) { + return Ok(c); + } + Err(match (ci_cmd, env) { + (Some(c), _) => format!("the test command `{c}` can't be narrowed to `{file}`"), + (None, Some(e)) => format!( + "the CI test step ({}) doesn't run `{file}` on its own", + e.source + ), + (None, None) => { + "the repository's CI runs no unit test command CoderHelm can read".to_string() + } + }) +} + /// The output of each failing step of a sandbox script, in step order. pub fn failing_outputs(output: &str, kind: &str) -> Vec { let mark = format!("--- {kind} failed (exit "); @@ -469,6 +496,10 @@ fn repro_waived(plan: &PlanResult) -> bool { .is_some_and(|d| !d.habits.repro.not_feasible.trim().is_empty()) } +/// The pull request's line for a bug fix that no test was shown to fail on +/// the base for. +pub const UNVERIFIED_FIX: &str = "Unverified: no test of this fix was shown to fail on the base code, so the reported failure is not reproduced here."; + /// The line for a change no changed test proves. pub const UNPROVEN: &str = "No changed test fails without the change, so nothing proves it. Write a test that fails on the base code and passes with the change (a unit test, or an end-to-end spec when the behaviour is what a person sees in the browser), through code that exists on the base."; @@ -616,6 +647,11 @@ pub fn open_findings(f: &PrFacts, plan: &PlanResult) -> Vec { w.point(), "CoderHelm makes the change smaller in its next round on this pull request.", ) + } else if l.contains("what a person asked for is never reverted") { + ( + "A person's ask taken out", + "CoderHelm puts it back in its next round on this pull request.", + ) } else if l.contains("decided is out of scope") { ( "Out of scope brought back", @@ -703,6 +739,12 @@ pub fn section(plan: &PlanResult, f: &PrFacts) -> String { out.push_str(&test_line(t)); out.push('\n'); } + // 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) { + out.push_str(UNVERIFIED_FIX); + out.push('\n'); + } out.push('\n'); } else if let Some(r) = repro.filter(|r| f.bug && !r.not_feasible.trim().is_empty()) { out.push_str(&format!( @@ -916,9 +958,7 @@ const KIND: &str = "unit"; impl Bench for SandboxBench<'_> { async fn run(&self, files: &[String]) -> Result { let r = &self.runner; - let base_cmd = super::detect_ci_test(r.github, r.owner, r.repo, self.base_branch) - .await - .ok_or("the repository's CI runs no unit test command CoderHelm can read")?; + 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 .github @@ -928,6 +968,16 @@ impl Bench for SandboxBench<'_> { .into_iter() .map(|e| e.path) .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)) @@ -937,9 +987,7 @@ impl Bench for SandboxBench<'_> { let installs = install.len(); steps.extend(install); for f in files { - let cmd = scoped_cmd(&base_cmd, f).ok_or_else(|| { - format!("the test command `{base_cmd}` can't be narrowed to one file") - })?; + let cmd = file_cmd(ci_cmd.as_deref(), env.as_ref(), f)?; steps.push(Step { kind: KIND, cmd }); } let head = r @@ -1196,10 +1244,17 @@ async fn check_and_fix( // 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; - let mut ledger = - super::scope_ledger::load_or_seed(w.state, &w.msg.team_id, w.run_id, w.msg, w.plan) - .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( + w.state, + &w.msg.team_id, + w.run_id, + w.msg, + w.plan, + &people, + ) + .await; facts.out_of_scope = super::scope_ledger::held( w.state, &w.msg.team_id, @@ -1207,6 +1262,7 @@ async fn check_and_fix( &mut ledger, &evidence.notes, &super::scope_ledger::sources(w.msg, &comments), + &people, &diff, ) .await; diff --git a/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs b/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs new file mode 100644 index 000000000..22decfeaf --- /dev/null +++ b/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs @@ -0,0 +1,263 @@ +//! rp. A data-pipeline ticket named four camps of a vendor's booking +//! system filed under the wrong sport ("Squash Camp-Half Day" listed under +//! volleyball, "Total Skills Hockey Camp-Full Day" missing from hockey). +//! The pipeline already had a table for exactly this, `CAMP_SPORT_OVERRIDES`, +//! with entries for "squash camp" and "total skills hockey camp". Its lookup +//! matched exact names, and the vendor appends "-Half Day" / "-Full Day", so +//! the entries never matched: the lookup returned `None` for every one of +//! the ticket's names on the base. The run's own notes said so, then +//! planned "a keyword step after the override": +595/-186 across the +//! pipeline, a moved extractor, keyword matching, new logging, a fixture, +//! other programs moved to another lookup (its own reviewer flagged that), +//! and two questions on the pull request that one page load answered. The +//! new test was never run on the base: the repository's CI runs each test +//! file with a `python "$t"` loop, which CoderHelm couldn't narrow, so the +//! test was recorded as not run and the description said nothing of it. +//! The right change stripped the suffix in the lookup and added two +//! entries, +49/-1, mostly a test of the exact names stored on staging that +//! fails on the base. Across the 53 runs audited, 8 of 10 bug tickets that +//! wrote code ran nothing before their first edit, 6 diffs of 300+ lines +//! answered a ticket naming 1 to 10 records, and none of the 17 runs whose +//! tests were checked had a test shown to fail on the base. +//! +//! Guarantee: a bug plan reproduces before it plans (`## Reproduce`: the +//! ticket's exact inputs and their stored variants, a command this run ran +//! on the base with `reproduce_on_base` and its quoted output, the wrong +//! line), or says `Unverified:` after trying. The fix goes in the mechanism +//! the wrong line is in; a new resolution path beside it goes back. A +//! question a page load or a query answers is looked up before it is +//! decided. A diff that rewrites a path for a few named records goes back +//! to be narrowed (`minimal_change::whole_path`). Each new test runs on the +//! base and the head the way CI runs it, and a bug fix no test was shown to +//! fail for says `Unverified:` in its description. + +use crate::passes::habits_check::{self, FileRun, PrFacts, TestResult, Verdict}; +use crate::passes::minimal_change::{self, Kind}; +use crate::passes::plan::PlanResult; +use crate::passes::reproduce; +use common::repro_first::{self, Attempt}; +use common::test_env; + +const TICKET: &str = "Update sport categorization for summer camps\nObserved\nThe hockey filter only catches the preschool hockey class, not the Total Skills Hockey Camp-Full Day (a0000001-0000-4000-8000-000000000001)\nWhen filtering for Volleyball, Squash Camp-Half Day (a0000002-0000-4000-8000-000000000002) shows\nExpected\nSquash Camp-Half Day (a0000002-0000-4000-8000-000000000002)\nSquash Camp- Full Day (a0000003-0000-4000-8000-000000000003)\nSquash High-Performance Camp (a0000004-0000-4000-8000-000000000004)"; + +/// The call that reproduces it on the base, and what it printed. +const CALL: &str = "cd dags && python -c \"from utils.schedule_common import get_camp_sport_override as g; [print(n, g(n)) for n in ['Squash Camp-Half Day', 'Squash Camp-Full Day', 'Squash Camp- Full Day', 'Total Skills Hockey Camp-Full Day']]\""; +const PRINTED: &str = "Squash Camp-Half Day None\nSquash Camp-Full Day None\nSquash Camp- Full Day None\nTotal Skills Hockey Camp-Full Day None"; + +fn ran() -> Vec { + vec![Attempt { + command: CALL.into(), + exit: Some(0), + output: PRINTED.into(), + error: String::new(), + }] +} + +const REUSE: &str = "## Reuse\n- `CAMP_SPORT_OVERRIDES` and `get_camp_sport_override` in dags/utils/schedule_common.py\n\n## Must not change\nOther programs' sport lookups; logging.\n\n## Measure first\nNone: the change stays inside this repository.\n"; + +/// The plan as the run wrote it. +fn plan_as_run() -> PlanResult { + PlanResult { + proposal: "## Problem\nCamps sit on the wrong sport.\n\n## Approach\nExact keys miss suffixed names, so a keyword step is added after the override, and booking programs move to the active-only sport map.".into(), + design: format!("{REUSE}\n## Smallest change\nAdd `resolve_camp_sport_id` and `build_sport_name_map`: the override first, then a keyword match on the camp name, for every camp the activities path loads.\n\n## Proof\n`tests/test_camp_sport.py` over 116 live camp names.\n\n## Out of scope\n- Inactive Squash camps: decided with the default: they show under the squash filter as today\n"), + tasks: "- [ ] dags/utils/schedule_common.py: [modify] add resolve_camp_sport_id\n- [ ] dags/camp_pipeline.py: [modify] use it for every camp\n- [ ] tests/test_camp_sport.py: [create] the test\n".into(), + ..Default::default() + } +} + +/// The plan the gates ask for. +fn plan_right() -> PlanResult { + PlanResult { + proposal: "## Problem\nCamps sit on the wrong sport.\n".into(), + design: format!("{REUSE}\n## Reproduce\nInputs: a0000001-0000-4000-8000-000000000001, a0000002-0000-4000-8000-000000000002, a0000003-0000-4000-8000-000000000003, a0000004-0000-4000-8000-000000000004; staging lookup L2 (name LIKE '%squash camp%'): `Squash Camp- Full Day`, `Squash Camp-Full Day`, `Squash Camp-Half Day`, `Summer Squash Camp Plus`\nRan on base: `{CALL}`\nOutput:\n```\n{PRINTED}\n```\nWrong line: dags/utils/schedule_common.py:99 `return CAMP_SPORT_OVERRIDES.get(normalized)` matches the whole name, suffix included.\n\n## Smallest change\nStrip a trailing `-Half Day` / `-Full Day` before `CAMP_SPORT_OVERRIDES.get` in `get_camp_sport_override`; add 2 entries.\n\n## Proof\nOne test of the four stored names; it fails on the base.\n\n## Out of scope\n- Inactive Squash camps: decided with the default: they show as today. Looked up: the summer camps page already shows a squash chip\n"), + tasks: "- [ ] tests/test_camp_sport.py: [create] the stored names map to squash\n- [ ] dags/utils/schedule_common.py: [modify] strip the suffix in get_camp_sport_override\n".into(), + ..Default::default() + } +} + +#[test] +fn the_plan_reproduces_on_the_base_and_fixes_the_lookup_it_lands_in() { + let g = reproduce::plan_gaps(&plan_as_run(), true, TICKET, &[], true, true); + let all = g.join("\n"); + assert!(all.contains("lacks `## Reproduce`"), "{all}"); + // The question one page load answers is looked up first. + assert!( + all.contains("Inactive Squash camps") && all.contains("check_url"), + "{all}" + ); + + // The plan the send-back asks for passes, with the run it quotes. + let g = reproduce::plan_gaps(&plan_right(), true, TICKET, &ran(), true, true); + assert!(g.is_empty(), "{g:?}"); + // The same section with nothing run behind it goes back. + let g = reproduce::plan_gaps(&plan_right(), true, TICKET, &[], true, true); + assert!( + g.iter().any(|l| l.contains("not a command this run ran")), + "{g:?}" + ); + + // A reproduction that lands in the overrides lookup, with the keyword + // step planned beside it, goes back. + let mut beside = plan_right(); + beside.design = beside.design.replace( + "Strip a trailing `-Half Day` / `-Full Day` before `CAMP_SPORT_OVERRIDES.get` in `get_camp_sport_override`; add 2 entries.", + "Add `resolve_camp_sport_id`: the override first, then a keyword match on the name.", + ); + let g = reproduce::plan_gaps(&beside, true, TICKET, &ran(), true, true); + assert!( + g.iter() + .any(|l| l.contains("`CAMP_SPORT_OVERRIDES`") && l.contains("doesn't change it")), + "{g:?}" + ); + assert!(g.iter().any(|l| l.contains("keyword match")), "{g:?}"); + + // The plan check calls it, on the draft and on the revision. + let src = include_str!("../plan.rs"); + assert_eq!(src.matches("super::reproduce::plan_gaps(").count(), 2); + assert!(src.contains("super::reproduce::tool()")); + // Its inputs are the ticket's own records. + assert_eq!(repro_first::ticket_ids(TICKET).len(), 4); +} + +fn patch(sign: char, lines: &[String]) -> String { + lines + .iter() + .map(|l| format!("{sign}{l}")) + .collect::>() + .join("\n") +} + +#[test] +fn a_whole_path_rewrite_for_four_camps_goes_back_and_the_lookup_fix_does_not() { + // The run's diff, in shape: the pipeline that loads every camp rewritten. + let added: Vec = (0..300) + .map(|i| format!(" sport_id = resolve_camp_sport_id(row, names_{i}, sport_map)")) + .collect(); + let removed: Vec = (0..90) + .map(|i| format!(" sport_id = group_sport.get(row['group_{i}'])")) + .collect(); + let wide = vec![( + "dags/camp_pipeline.py".to_string(), + "modified".to_string(), + format!("{}\n{}", patch('+', &added), patch('-', &removed)), + )]; + let found = minimal_change::check(&wide, &[], TICKET, false); + let w = found + .iter() + .find(|w| w.kind == Kind::WholePath) + .expect("whole path"); + assert!( + w.what.contains("390 changed code lines") && w.what.contains("4 record(s)"), + "{}", + w.what + ); + assert!(w.instruction().contains("Narrow it")); + + // The right change: the suffix stripped in the lookup, two entries. + let narrow = vec![ + ( + "dags/utils/schedule_common.py".to_string(), + "modified".to_string(), + "- normalized = re.sub(r\"\\s+\", \" \", str(name).strip().lower())\n+ normalized = re.sub(r\"\\s*-\\s*(half|full) day$\", \"\", re.sub(r\"\\s+\", \" \", str(name).strip().lower()))\n+ 'summer squash camp plus': 'b0000001-0000-4000-8000-00000000000a',\n+ 'squash high-performance camp': 'b0000001-0000-4000-8000-00000000000a',".to_string(), + ), + ( + "tests/test_camp_sport.py".to_string(), + "added".to_string(), + patch('+', &(0..45).map(|i| format!(" assert_case({i})")).collect::>()), + ), + ]; + let found = minimal_change::check(&narrow, &[], TICKET, false); + assert!(found.is_empty(), "{found:?}"); + // A reason the narrower change can't work keeps a wide one. + assert!(minimal_change::standing( + &minimal_change::check(&wide, &[], TICKET, false), + "Wider than the ticket: dags/camp_pipeline.py: the vendor gives no name for these camps" + ) + .is_empty()); +} + +const CI: &str = r#" +name: Tests +on: [pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - run: uv pip install --quiet "apache-airflow[postgres]==2.10.3" -r requirement.txt + - name: Run tests + run: | + failed=0 + for t in tests/test_*.py; do + echo "::group::$t" + python "$t" || failed=1 + echo "::endgroup::" + done + exit $failed +"#; + +#[test] +fn the_new_test_runs_on_the_base_the_way_ci_runs_it() { + let env = test_env::from_workflows(&[(".github/workflows/tests.yml".into(), CI.into())], &[]) + .expect("the test job"); + // CoderHelm's runner list knows no command here; the loop runs the file. + assert_eq!( + habits_check::file_cmd(None, Some(&env), "tests/test_camp_sport.py").as_deref(), + Ok("python tests/test_camp_sport.py") + ); + assert!( + habits_check::file_cmd(None, None, "tests/test_camp_sport.py") + .unwrap_err() + .contains("no unit test command") + ); + // Fails on the base with the reported names, passes on the head. + let base = FileRun { + code: Some(1), + output: "AssertionError: 'Squash Camp-Half Day' maps to None, expected squash".into(), + }; + let head = FileRun { + code: Some(0), + output: String::new(), + }; + assert_eq!(habits_check::verdict(&head, &base).0, Verdict::Proven); + // A test that passes on the base goes back to the coder. + let plan = PlanResult { + tasks: "- [ ] tests/test_camp_sport.py: [create] x\n".into(), + ..Default::default() + }; + let either = PrFacts { + bug: true, + tests: vec![TestResult { + path: "tests/test_camp_sport.py".into(), + verdict: habits_check::verdict(&head, &head).0, + detail: String::new(), + }], + ..Default::default() + }; + assert!(habits_check::blocking(&either, &plan) + .iter() + .any(|l| l.contains("passes with the change taken out"))); + // A bug fix whose test never ran both ways says so in its description. + let not_run = PrFacts { + bug: true, + tests: vec![TestResult { + path: "tests/test_camp_sport.py".into(), + verdict: Verdict::NotRun, + detail: "the sandbox gave no result for it".into(), + }], + ..Default::default() + }; + assert!(habits_check::section(&plan, ¬_run).contains(habits_check::UNVERIFIED_FIX)); + let proven = PrFacts { + bug: true, + tests: vec![TestResult { + path: "tests/test_camp_sport.py".into(), + verdict: Verdict::Proven, + detail: "AssertionError".into(), + }], + ..Default::default() + }; + assert!(!habits_check::section(&plan, &proven).contains("Unverified")); +} diff --git a/services/worker/src/passes/incidents/sn_person_answer_moves_scope.rs b/services/worker/src/passes/incidents/sn_person_answer_moves_scope.rs new file mode 100644 index 000000000..d375ce63e --- /dev/null +++ b/services/worker/src/passes/incidents/sn_person_answer_moves_scope.rs @@ -0,0 +1,113 @@ +//! sn. The duplicated filter-chip ticket again (see `sl`). The plan left +//! the `/classes/` path pages out of scope, decided with a default. +//! A reviewer, sam, answered on the pull request that the path pages should +//! cover both rows. The run replied "Understood" and then reverted the +//! path-page work as out of scope: the scope ledger was seeded from the +//! ticket's criteria and the plan only, and a person's comment counted only +//! when the coder itself wrote a `Scope change:` line quoting it. +//! +//! Guarantee: what people say decides scope as they say it. At seed and on +//! every round's comments, an out-of-scope entry a person's answer or +//! comment asks for moves in, recording who asked +//! (`Ledger::take_people`, `scope_ledger::people`, `load_or_seed`, `held`, +//! `load_with_people`). From then on the path-page work is in scope, and a +//! diff that takes it out is a breach that goes back to be put back. A +//! comment that keeps the item out moves nothing. + +use crate::passes::habits_check::{self, PrFacts}; +use crate::passes::stop_judge::acceptance; +use common::scope_ledger::{self, Ledger}; + +const TICKET: &str = "Observed\nTwo Multi-Sport filters show\nAcceptance Criteria\nOnly one multi-sport filter to show"; +const PROPOSAL: &str = "## Problem\nTwo Multi-Sport chips.\n"; +const DESIGN: &str = "## Out of scope\n- Merging the two schedule API rows: a data change in another repository\n- `/classes/` path pages (`selectedSport`, `findNormalizedSport`): decided with the default: one id, as today\n"; +const TASKS: &str = "- [ ] apps/web/src/utils/filterMaps.ts: [modify] Add slugToIds\n"; + +/// sam's answer on the pull request, as written. +const ANSWER: &str = "The `/classes/` path pages should cover both rows too, so classes from either Multi-Sport row show there."; + +fn ledger() -> Ledger { + Ledger::from_ticket_and_plan(&acceptance(TICKET), PROPOSAL, DESIGN, TASKS) +} + +fn said(text: &str) -> Vec<(String, String)> { + vec![("sam".to_string(), text.to_string())] +} + +/// The round that built the path pages after sam's answer. +fn path_pages_built() -> Vec<(String, String, String)> { + vec![( + "apps/web/src/services/classService.ts".into(), + "modified".into(), + "+ // A /classes/ path page filters by every row sharing the slug\n+ const ids = selectedSport ? slugToIds(all, selectedSport.slug) : [];".into(), + )] +} + +/// The later revert that took them out "as out of scope". +fn path_pages_reverted() -> Vec<(String, String, String)> { + vec![( + "apps/web/src/services/classService.ts".into(), + "modified".into(), + "- // A /classes/ path page filters by every row sharing the slug\n- const ids = selectedSport ? slugToIds(all, selectedSport.slug) : [];\n+ const ids = [];".into(), + )] +} + +#[test] +fn the_answer_moves_the_path_pages_in_and_a_revert_is_a_breach() { + // Before the answer the path pages are out, and building them breaches. + let l = ledger(); + assert_eq!(scope_ledger::breaches(&l, &path_pages_built()).len(), 1); + + // sam's answer moves them in on its own: no `Scope change:` line. + let mut l = ledger(); + let moved = l.take_people(&said(ANSWER)); + assert_eq!(moved.len(), 1, "{moved:?}"); + let e = l + .entries + .iter() + .find(|e| e.item.contains("/classes/")) + .unwrap(); + assert!(!e.is_out() && e.moved_in.starts_with("sam asked for it")); + // The other entry stays out. + assert_eq!(l.outs().count(), 1); + // Building them is no breach now. + assert!(scope_ledger::breaches(&l, &path_pages_built()).is_empty()); + + // Taking them out again is the breach, and it goes back. + let b = scope_ledger::breaches(&l, &path_pages_reverted()); + assert_eq!(b.len(), 1, "{b:?}"); + assert!(b[0].reverted); + let plan = crate::passes::plan::PlanResult { + tasks: TASKS.into(), + ..Default::default() + }; + let f = PrFacts { + out_of_scope: b, + ..Default::default() + }; + let lines = habits_check::blocking(&f, &plan); + assert!( + lines + .iter() + .any(|x| x.contains("takes out") && x.contains("sam asked for it")), + "{lines:?}" + ); + let open = habits_check::open_findings(&f, &plan); + assert!(open.iter().any(|o| o.point == "A person's ask taken out")); +} + +#[test] +fn the_answer_counts_at_seed_and_a_comment_keeping_it_out_moves_nothing() { + // An answer the run already had when the plan was made: in scope from + // the start, never written as out of scope. + let mut l = ledger(); + l.take_people(&said(ANSWER)); + assert!(l.outs().all(|e| !e.item.contains("/classes/"))); + // A comment that keeps the path pages out leaves them out. + let mut l = ledger(); + let moved = l.take_people(&said( + "Leave the `/classes/` path pages for a separate ticket.", + )); + assert!(moved.is_empty()); + assert_eq!(l.outs().count(), 2); +} diff --git a/services/worker/src/passes/minimal_change.rs b/services/worker/src/passes/minimal_change.rs index 76789b846..c6d66f43a 100644 --- a/services/worker/src/passes/minimal_change.rs +++ b/services/worker/src/passes/minimal_change.rs @@ -56,6 +56,7 @@ pub enum Kind { TestSize, InventedPayload, MadeUpIds, + WholePath, } /// One way the change is wider than its ticket. @@ -78,6 +79,7 @@ impl Widening { Kind::TestSize => "A test out of proportion to the change", Kind::InventedPayload => "A test payload nobody observed", Kind::MadeUpIds => "Made-up ids where the run looked up real ones", + Kind::WholePath => "A whole code path rewritten for a few named records", } } @@ -128,6 +130,10 @@ impl Widening { "`{}` uses made-up ids ({}) while this run looked up the real records' ids. Use the ids the lookups returned, so the test is about the records the bug is about.", self.path, self.what ), + Kind::WholePath => format!( + "The change rewrites how every record of its kind is processed ({}), while the ticket names only a few. Narrow it to those records and things exactly like them: fix the lookup, table or mapping they go through (its matching or its entries) and leave the shared path as it is.", + self.what + ), }; format!("{what}{why}") } @@ -948,6 +954,87 @@ pub fn invented_payloads(diff: &Diff, has_probe: bool) -> Vec { out } +// ── A whole path rewritten for a few records ─────────────────────────────── + +/// Changed code lines (added and removed, not entries of a map or list, not +/// comments) past which a change for a few named records rewrites a path. +pub const WHOLE_PATH_LINES: usize = 40; +/// Up to this many records named, a ticket is about those records. +pub const FEW_RECORDS: usize = 12; + +/// Ticket words that ask for every record of a kind. +const EVERY_ASKS: &[&str] = &[ + "all records", + "all camps", + "every record", + "every camp", + "for all ", + "for every ", + "across all", + "refactor", + "rewrite", +]; + +/// A changed line that is an entry of a map or list, a bracket, or a +/// comment: what a lookup fix adds without changing how records flow. +fn entry_line(line: &str) -> bool { + let t = line.trim(); + if t.is_empty() + || t.starts_with('#') + || t.starts_with("//") + || t.starts_with("--") + || t.chars() + .all(|c| matches!(c, '{' | '}' | '[' | ']' | '(' | ')' | ',' | ';')) + { + return true; + } + let quoted = t.starts_with('\'') || t.starts_with('"'); + quoted && (t.contains("':") || t.contains("\":") || t.ends_with("',") || t.ends_with("\",")) +} + +/// A change that rewrites a code path while its ticket names a few records +/// (`common::repro_first::ticket_ids`): more than [`WHOLE_PATH_LINES`] +/// changed code lines that are no entries of a map or list. A ticket that +/// named four camps filed under the wrong sport got 900 changed lines +/// across the pipeline that loads every camp; the fix was a suffix +/// stripped in the existing lookup and two entries. A `Wider than the +/// ticket:` line keeps it, with the reason the narrower change can't work. +pub fn whole_path(diff: &Diff, ticket: &str) -> Vec { + let named = common::repro_first::ticket_ids(ticket).len(); + if named == 0 || named > FEW_RECORDS || ticket_asks(ticket, EVERY_ASKS) { + return Vec::new(); + } + let mut lines = 0; + let mut files: Vec<(&str, usize)> = Vec::new(); + for (path, status, patch) in diff { + if status == "removed" || !code_file(path) || is_test(path) { + continue; + } + let n = lines_of(patch, '+') + .into_iter() + .chain(lines_of(patch, '-')) + .filter(|l| !entry_line(l)) + .count(); + if n > 0 { + lines += n; + files.push((path, n)); + } + } + if lines <= WHOLE_PATH_LINES { + return Vec::new(); + } + files.sort_by_key(|f| std::cmp::Reverse(f.1)); + vec![Widening { + kind: Kind::WholePath, + path: files[0].0.to_string(), + what: format!( + "{lines} changed code lines across {} file(s), most in `{}`, for a ticket that names {named} record(s)", + files.len(), + files[0].0 + ), + }] +} + // ── The check ────────────────────────────────────────────────────────────── /// Everything a diff adds past its ticket. `base` holds the base text of @@ -972,6 +1059,7 @@ pub fn check( out.extend(test_size(diff)); out.extend(repeated_cases(diff)); out.extend(invented_payloads(diff, has_probe)); + out.extend(whole_path(diff, ticket)); out } diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 6d43d8302..75a30911c 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1369,6 +1369,8 @@ mod replay; #[cfg(test)] mod reply_eval; pub(crate) mod repo_pick; +/// The planner reproduces a bug on the base before it plans code. +mod reproduce; mod resolve; mod resolved; pub mod restack; @@ -3164,7 +3166,15 @@ async fn run_passes( add_progress_note(state, &msg.team_id, run_id, "Plan generated").await; // Scope is decided once, here, from the ticket's criteria and the // plan, before any code; every later round is held to it. - scope_ledger::load_or_seed(state, &msg.team_id, run_id, msg, &plan_result).await; + scope_ledger::load_or_seed( + state, + &msg.team_id, + run_id, + msg, + &plan_result, + &scope_ledger::people(msg, &[]), + ) + .await; } if !plan_final { if !plan_was_reused { diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 33605f4ec..1e05bc222 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -743,6 +743,27 @@ Then the ```fix_location.json block described above."#, ); tools.push(super::web_check::tool()); full_system.push_str(&web.prompt_section()); + // A bug is reproduced on the base before code is planned: the planner + // runs the ticket's inputs through the current code (`reproduce`). + let is_bug = intent == super::triage::TicketIntent::Bug; + let reproducer = super::reproduce::Reproducer::new( + super::test_bug::Runner { + state, + github, + owner: &msg.repo_owner, + repo: &msg.repo_name, + team_id: &msg.team_id, + run_id, + provider, + }, + &msg.base_branch, + ); + if is_bug { + if reproducer.can_run() { + tools.push(super::reproduce::tool()); + } + full_system.push_str(&super::reproduce::prompt_section(reproducer.can_run())); + } let ops = super::ops_tools::OpsTools::load( state, &msg.team_id, @@ -834,6 +855,7 @@ Then the ```fix_location.json block described above."#, knowledge: knowledge.as_ref(), web: Some(&web), abilities: Some(&abilities), + repro: is_bug.then_some(&reproducer), state, }; @@ -978,6 +1000,16 @@ Then the ```fix_location.json block described above."#, &ticket_words, &write_facts, )); + // Reproduced on the base, fixed in the mechanism the reproduction lands + // in, questions looked up first (`reproduce`, `common::repro_first`). + shape_gaps.extend(super::reproduce::plan_gaps( + &draft, + is_bug, + &ticket_words, + &reproducer.attempts(), + reproducer.can_run(), + can_look_up, + )); back.extend(shape_gaps.iter().cloned()); // A decision that stops without a fix names the one step a person takes. back.extend(super::fix_location::next_step_gaps(draft.fix.as_ref())); @@ -1475,6 +1507,14 @@ Then the ```fix_location.json block described above."#, ) .await; left.extend(super::plan_shape::write_gaps(&files, &ticket_words, &facts)); + left.extend(super::reproduce::plan_gaps( + &files, + is_bug, + &ticket_words, + &reproducer.attempts(), + reproducer.can_run(), + can_look_up, + )); if !left.is_empty() { warn!(ticket_id = %msg.ticket_id, gaps = ?left, "Plan is still not the smallest change after one send-back"); super::add_progress_note( @@ -2492,6 +2532,8 @@ struct CombinedToolExecutor<'a> { skills: Option<&'a super::skills::TeamSkills>, /// Knowledge bases attached to the planner. knowledge: Option<&'a super::knowledge::KnowledgeTools>, + /// `reproduce_on_base`, for a bug. + repro: Option<&'a super::reproduce::Reproducer<'a>>, state: &'a WorkerState, } @@ -2502,6 +2544,11 @@ impl<'a> ToolExecutor for CombinedToolExecutor<'a> { name: &str, input: &serde_json::Value, ) -> Result> { + if let Some(r) = self.repro { + if let Some(out) = r.handle(name, input).await { + return Ok(serde_json::json!(out)); + } + } if let Some(k) = self.knowledge { if let Some(out) = k.handle(self.state, name, input).await { return Ok(serde_json::json!(out)); diff --git a/services/worker/src/passes/plan_shape.rs b/services/worker/src/passes/plan_shape.rs index e90016df8..0e28ffd57 100644 --- a/services/worker/src/passes/plan_shape.rs +++ b/services/worker/src/passes/plan_shape.rs @@ -216,7 +216,7 @@ const TEST_TO_VENDOR: &[&str] = &[ /// The plan's words that propose things, without its Must not change /// section (where "no deletes" is said). -fn proposing_text(files: &PlanResult) -> String { +pub(crate) fn proposing_text(files: &PlanResult) -> String { let design = match section(&files.design, MUST_NOT_CHANGE) { Some(s) => files.design.replace(s, ""), None => files.design.clone(), diff --git a/services/worker/src/passes/reproduce.rs b/services/worker/src/passes/reproduce.rs new file mode 100644 index 000000000..1baf69252 --- /dev/null +++ b/services/worker/src/passes/reproduce.rs @@ -0,0 +1,257 @@ +//! The planner reproduces a bug on the base before it plans code +//! (`common::repro_first` has the rules and why). +//! +//! - [`Reproducer`]: the planner's `reproduce_on_base` tool. It runs one +//! call or command in the sandbox on the base branch's head, in the run's +//! test environment, and returns its exit code and output. Each run is +//! kept ([`Reproducer::attempts`]), so the plan check can hold the plan's +//! `## Reproduce` to a command that ran and to what it printed. +//! - [`plan_gaps`]: the plan check's lines: the reproduction, the fix in +//! the mechanism it landed in, and questions looked up before they are +//! decided with a default. A gap goes back with the plan's one send-back; +//! what is still open stays on the decision. + +use std::sync::Mutex; + +use common::repro_first::{self, Attempt}; +use serde_json::{json, Value}; + +use super::plan::PlanResult; +use crate::agent::llm::ToolDefinition; + +/// Runs of the tool a plan may make. +pub const MAX_RUNS: usize = 6; +const OUT_MARK: &str = "===CODERHELM_REPRO_OUT==="; +const EXIT_MARK: &str = "===CODERHELM_REPRO_EXIT"; +/// The output kept of one run. +const KEEP: usize = 3000; + +/// The tool's definition. +pub fn tool() -> ToolDefinition { + ToolDefinition { + name: repro_first::TOOL.to_string(), + description: format!( + "Run one call or command on the BASE branch, before any change, in a sandbox with the \ + repository's test environment installed, and get its exit code and output. Use it to \ + reproduce a bug: put the ticket's exact names or ids (and each variant the data holds) \ + through the code path the bug is in, for example `python -c \"from dags.utils.common \ + import get_override; print(get_override('Camp-Half Day'))\"`, or run the nearest \ + existing test. Quote the command and its output in `## Reproduce`. Read-only: \ + nothing it writes is kept. At most {MAX_RUNS} runs." + ), + input_schema: json!({ + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The shell command, run from the repository root" + }, + "inputs": { + "type": "string", + "description": "The exact names or ids it feeds the code, and where each came from (the ticket, a lookup)" + } + }, + "required": ["command"] + }), + } +} + +/// The planner's lines about the tool. +pub fn prompt_section(can_run: bool) -> String { + if can_run { + format!( + "\n\n## Reproduce a bug before planning (`{}`)\nFor a bug, before you plan code: take the exact names or ids from the ticket, find every variant the real data holds with a read-only lookup (a `LIKE` on the name), and run them through the current code on the base with `{}`. Write `## Reproduce` in design.md with `Inputs:`, `Ran on base:` (the command, as you ran it), `Output:` (what it printed, quoted) and `Wrong line:` (`path:line` and the code on it, backticked). The fix goes in that line's mechanism.\n", + repro_first::TOOL, + repro_first::TOOL + ) + } else { + "\n\n## Reproduce a bug before planning\nFor a bug, write `## Reproduce` in design.md: `Inputs:` (the ticket's exact names or ids, with every variant a read-only lookup finds), `Unverified:` (no sandbox here to run the code on the base) and `Wrong line:` (`path:line` and the code on it, backticked). The fix goes in that line's mechanism.\n".to_string() + } +} + +/// A command's output from the script's: the exit code and what it printed. +pub fn read_output(output: &str) -> (Option, String) { + let exit = output.lines().rev().find_map(|l| { + l.trim() + .strip_prefix(EXIT_MARK) + .and_then(|r| r.trim().parse::().ok()) + }); + let body = output + .split_once(OUT_MARK) + .map(|(_, b)| b) + .unwrap_or(output); + let body = body.split(EXIT_MARK).next().unwrap_or(body).trim(); + let start = body.len().saturating_sub(KEEP); + let start = (start..=body.len()) + .find(|i| body.is_char_boundary(*i)) + .unwrap_or(body.len()); + (exit, body[start..].to_string()) +} + +/// The sandbox script for one command: its output and exit code, always +/// printed (a call that prints `None` and exits 0 is the reproduction). +pub fn script(command: &str) -> String { + format!( + "( {command} ) > /tmp/ch-repro.log 2>&1; ch_r=$?\necho \"{OUT_MARK}\"\ntail -c {KEEP} /tmp/ch-repro.log\necho\necho \"{EXIT_MARK} $ch_r\"\ntrue" + ) +} + +/// The planner's tool, on one run. +pub struct Reproducer<'a> { + pub runner: super::test_bug::Runner<'a>, + pub base_branch: &'a str, + attempts: Mutex>, +} + +impl<'a> Reproducer<'a> { + pub fn new(runner: super::test_bug::Runner<'a>, base_branch: &'a str) -> Self { + Self { + runner, + base_branch, + attempts: Mutex::new(Vec::new()), + } + } + + /// Whether a sandbox is set up to run on the base. + pub fn can_run(&self) -> bool { + let c = &self.runner.state.config; + !c.sandbox_bucket_name.is_empty() && !c.sandbox_project_name.is_empty() + } + + /// Every run so far. + pub fn attempts(&self) -> Vec { + self.attempts.lock().map(|a| a.clone()).unwrap_or_default() + } + + /// The tool's answer, or `None` for another tool. + pub async fn handle(&self, name: &str, input: &Value) -> Option { + if name != repro_first::TOOL { + return None; + } + let command = input["command"].as_str().unwrap_or("").trim().to_string(); + if command.is_empty() { + return Some("No command given.".into()); + } + if self.attempts().len() >= MAX_RUNS { + return Some(format!( + "Not run: this plan has used its {MAX_RUNS} runs. Write `## Reproduce` from the runs you made." + )); + } + let r = &self.runner; + let attempt = match r.github.get_ref(r.owner, r.repo, self.base_branch).await { + Err(e) => Attempt { + command: command.clone(), + error: format!("the base branch couldn't be read ({e})"), + ..Default::default() + }, + Ok(sha) => match r.run_script_at(&sha, &[&command], &script(&command)).await { + Ok(out) => { + let (exit, output) = read_output(&out); + Attempt { + command: command.clone(), + exit, + output, + error: String::new(), + } + } + Err(e) => Attempt { + command: command.clone(), + error: e, + ..Default::default() + }, + }, + }; + let answer = if attempt.error.is_empty() { + format!( + "Ran on the base ({}): exit {}\nOutput:\n{}", + self.base_branch, + attempt + .exit + .map_or("unknown".to_string(), |c| c.to_string()), + attempt.output + ) + } else { + format!("Didn't run: {}", attempt.error) + }; + if let Ok(mut a) = self.attempts.lock() { + a.push(attempt); + } + Some(answer) + } +} + +/// The plan's out-of-scope entries decided with a default and its question +/// lines: what a lookup may have to settle first. +fn questions(files: &PlanResult) -> Vec { + let mut out: Vec = + common::scope_ledger::Ledger::from_plan(&files.proposal, &files.design, "") + .entries + .into_iter() + .filter(|e| e.why.to_lowercase().contains("default")) + .map(|e| format!("{}: {}", e.item, e.why)) + .collect(); + for l in format!("{}\n{}", files.proposal, files.design).lines() { + let t = l.trim().trim_start_matches(['-', '*']).trim(); + if t.ends_with('?') && !out.iter().any(|o| o.contains(t)) { + out.push(t.to_string()); + } + } + out +} + +/// What the plan check sends back about reproducing, the mechanism and +/// questions. `is_bug` from triage; `ticket` the ticket's words; `attempts` +/// the tool's runs. +pub fn plan_gaps( + files: &PlanResult, + is_bug: bool, + ticket: &str, + attempts: &[Attempt], + can_run: bool, + can_look_up: bool, +) -> Vec { + let t = files.tasks.trim_start(); + if t.is_empty() || super::plan_sections::directive(t) { + return Vec::new(); + } + let mut out = Vec::new(); + if is_bug { + out.extend(repro_first::reproduce_gaps( + &files.design, + ticket, + attempts, + can_run, + can_look_up, + )); + let smallest = + super::feature::reuse::section(&files.design, super::plan_shape::SMALLEST_CHANGE) + .unwrap_or(""); + out.extend(repro_first::reuse_gaps( + &files.design, + smallest, + &super::plan_shape::proposing_text(files), + )); + } + out.extend(repro_first::question_gaps(&questions(files))); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_output_is_read_whatever_the_exit() { + let out = "===CODERHELM_ENV_RESTORED===\ninstall noise\n===CODERHELM_REPRO_OUT===\nNone\n\n===CODERHELM_REPRO_EXIT 0\n"; + assert_eq!(read_output(out), (Some(0), "None".to_string())); + let (exit, body) = read_output( + "===CODERHELM_REPRO_OUT===\nTraceback\nImportError\n===CODERHELM_REPRO_EXIT 1", + ); + assert_eq!(exit, Some(1)); + assert!(body.ends_with("ImportError")); + assert_eq!(read_output("nothing").0, None); + let s = script("python -c 'print(1)'"); + assert!(s.starts_with("( python -c 'print(1)' )") && s.contains(EXIT_MARK)); + assert_eq!(tool().name, "reproduce_on_base"); + } +} diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 2963308f1..0505d458f 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -5192,7 +5192,18 @@ async fn start_planned_work( let items = super::finish_planned::listed(&body); // What the plan decided is out of scope is not built again // (`common::scope_ledger`). - let items = match super::scope_ledger::load(state, &msg.team_id, &msg.run_id).await { + let items = match super::scope_ledger::load_with_people( + state, + &ctx.github, + &ctx.ticket_msg, + &msg.team_id, + &msg.run_id, + pr.owner, + pr.repo, + pr.number, + ) + .await + { Some(l) => { let (keep, gone) = super::scope_ledger::drop_covered(&l, items); if !gone.is_empty() { @@ -5334,7 +5345,18 @@ async fn recheck_planned_work( ) .await; // Nor what the plan decided is out of scope (`common::scope_ledger`). - let found = match super::scope_ledger::load(state, &msg.team_id, &msg.run_id).await { + let found = match super::scope_ledger::load_with_people( + state, + &ctx.github, + &ctx.ticket_msg, + &msg.team_id, + &msg.run_id, + pr.owner, + pr.repo, + pr.number, + ) + .await + { Some(l) => { let (keep, gone): (Vec<_>, Vec<_>) = found .into_iter() diff --git a/services/worker/src/passes/scope_ledger.rs b/services/worker/src/passes/scope_ledger.rs index 597ad62dc..02c9fe86e 100644 --- a/services/worker/src/passes/scope_ledger.rs +++ b/services/worker/src/passes/scope_ledger.rs @@ -71,17 +71,30 @@ pub(crate) async fn load_or_seed( run_id: &str, msg: &TicketMessage, plan: &PlanResult, + people: &[(String, String)], ) -> Ledger { if let Some(l) = load(state, team_id, run_id).await { return l; } - let l = Ledger::from_ticket_and_plan( + let mut l = Ledger::from_ticket_and_plan( &super::stop_judge::acceptance(&msg.body), &plan.proposal, &plan.design, &plan.tasks, ); + // What people already answered or commented is in scope from the + // start: the plan never writes a person's ask as out of scope. + let moved = l.take_people(people); save(state, team_id, run_id, &l).await; + if !moved.is_empty() { + super::add_progress_note( + state, + team_id, + run_id, + &format!("In scope because a person asked: {}", moved.join(" ")), + ) + .await; + } if !l.is_empty() { super::add_progress_note( state, @@ -97,25 +110,77 @@ pub(crate) async fn load_or_seed( l } +/// The ledger on the run with the people's answers and the comments on +/// pull request `number` taken in (`Ledger::take_people`), saved when one +/// moved an item in. A planned-work round reads scope through this, so a +/// person's answer since the last check is never built around. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn load_with_people( + state: &WorkerState, + github: &crate::clients::github::GitHubClient, + msg: &TicketMessage, + team_id: &str, + run_id: &str, + owner: &str, + repo: &str, + number: u64, +) -> Option { + let mut l = load(state, team_id, run_id).await?; + let comments = match github.list_issue_comments(owner, repo, number).await { + Ok(c) => super::review_pr::human_comments(&c, 30), + Err(_) => Vec::new(), + }; + let moved = l.take_people(&people(msg, &comments)); + if !moved.is_empty() { + save(state, team_id, run_id, &l).await; + super::add_progress_note( + state, + team_id, + run_id, + &format!("Scope changed: {}", moved.join(" ")), + ) + .await; + } + Some(l) +} + /// What a scope change may cite: the ticket's acceptance criteria, the /// answers people gave, and the people's `comments` (bodies). -pub(crate) fn sources(msg: &TicketMessage, comments: &[String]) -> Vec { +pub(crate) fn sources(msg: &TicketMessage, comments: &[(String, String)]) -> Vec { let mut out = super::stop_judge::acceptance(&msg.body); out.extend( msg.answers .iter() .map(|a| format!("{} {}", a.question, a.answer)), ); + out.extend(comments.iter().map(|(_, b)| b.clone())); + out +} + +/// What people said that decides scope, as (who, words): the answers +/// they gave the run's questions (an answer that says no is left out, its +/// question's words are not an ask) and their `comments`. +pub(crate) fn people(msg: &TicketMessage, comments: &[(String, String)]) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = msg + .answers + .iter() + .filter(|a| { + let l = a.answer.trim().to_lowercase(); + !(l == "no" || l.starts_with("no,") || l.starts_with("no.") || l.starts_with("no ")) + }) + .map(|a| (a.author.clone(), format!("{} {}", a.question, a.answer))) + .collect(); out.extend(comments.iter().cloned()); out } -/// The people's comments on the run's pull request, when it has one. +/// The people's comments on the run's pull request, when it has one, as +/// (author, body). pub(crate) async fn comments( github: &crate::clients::github::GitHubClient, msg: &TicketMessage, branch: &str, -) -> Vec { +) -> Vec<(String, String)> { let Ok(Some(pr)) = github .find_open_pr_for_branch(&msg.repo_owner, &msg.repo_name, branch) .await @@ -129,10 +194,7 @@ pub(crate) async fn comments( .list_issue_comments(&msg.repo_owner, &msg.repo_name, number) .await { - Ok(c) => super::review_pr::human_comments(&c, 30) - .into_iter() - .map(|(_, body)| body) - .collect(), + Ok(c) => super::review_pr::human_comments(&c, 30), Err(_) => Vec::new(), } } @@ -149,9 +211,14 @@ pub(crate) async fn held( ledger: &mut Ledger, notes: &str, sources: &[String], + people: &[(String, String)], diff: &[(String, String, String)], ) -> Vec { - let (accepted, refused) = ledger.apply_changes(notes, sources); + // A person's answer or comment moves its item in on its own, every + // round; the coder's `Scope change:` lines come after. + let mut accepted = ledger.take_people(people); + let (by_coder, refused) = ledger.apply_changes(notes, sources); + accepted.extend(by_coder); if !accepted.is_empty() { save(state, team_id, run_id, ledger).await; info!(run_id, moved = ?accepted, "Scope changed with a cited reason; the ledger records it"); diff --git a/services/worker/src/passes/test_bug.rs b/services/worker/src/passes/test_bug.rs index 615de9c02..05bae27f1 100644 --- a/services/worker/src/passes/test_bug.rs +++ b/services/worker/src/passes/test_bug.rs @@ -46,6 +46,26 @@ impl Runner<'_> { steps: &[Step], repeat: Option<&str>, ) -> Result<(Vec>, String), String> { + let cmds: Vec<&str> = steps + .iter() + .map(|s| s.cmd.as_str()) + .chain(repeat.iter().copied()) + .collect(); + let script = test_package::sandbox_script(steps, repeat); + let output = self.run_script_at(sha, &cmds, &script).await?; + let n = steps.len() + usize::from(repeat.is_some()); + Ok((test_package::step_codes(&output, n), 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. + pub async fn run_script_at( + &self, + sha: &str, + cmds: &[&str], + script: &str, + ) -> Result { if !self.sandbox_on() { return Err("no sandbox is set up here".into()); } @@ -57,11 +77,7 @@ impl Runner<'_> { self.provider.scope.ctx(common::agent_policy::Agent::Coder), None, ); - let cmds = steps - .iter() - .map(|s| s.cmd.as_str()) - .chain(repeat.iter().copied()); - for cmd in cmds { + for cmd in cmds.iter().copied() { match gate.check_command(cmd, "Check a failing test").await { common::agent_policy::Outcome::Run { .. } => {} common::agent_policy::Outcome::Refused { message, .. } @@ -105,15 +121,11 @@ impl Runner<'_> { .await .map_err(|e| format!("the commit couldn't be prepared ({e})"))?; let node = super::detect_node_version(self.github, self.owner, self.repo, sha).await; - let script = test_package::sandbox_script(steps, repeat); match sandbox - .run_checks(&source, &script, node.as_deref(), None, None) + .run_checks(&source, script, node.as_deref(), None, None) .await { - Ok(o) if o.ran => { - let n = steps.len() + usize::from(repeat.is_some()); - Ok((test_package::step_codes(&o.output, n), o.output)) - } + Ok(o) if o.ran => Ok(o.output), Ok(o) => Err(format!("the sandbox gave no result ({})", o.reason)), Err(e) => Err(format!("the sandbox couldn't run ({e})")), } From 093ea9e7eb271cf2b6e59d88a41a08b931356113 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 17 Nov 2026 17:04:07 -0500 Subject: [PATCH 2/2] The changed tests run both ways: CI's install, a budget of their own, every runner read Across the 53 most recent runs, none of the 17 with a test check ran a new test on the base and the head. Six failed the install: a pnpm workspace member was installed on its own (`cd apps/web && pnpm install --ignore-workspace --frozen-lockfile`), where pnpm stops with ERR_PNPM_NO_LOCKFILE. Seven ran out of time: the fresh step ran every other check first and reached the sandbox runs short again, with its one request spent. Two could not read a CI loop and listed fixtures as tests. - A workspace member installs from the workspace root (falling back to the member and its dependencies); the runs use CI's job for the test files, its install lines, Node and pnpm versions, through the cached environment. A failed install says why. - The sandbox runs are owed to a fresh step, which runs them before any other check and records them for the head; up to four asks a run. - One `test_env::narrow` for pytest, unittest, Vitest, Jest, go test and cargo test; package scripts and make targets read to their runner; a file's own package script as the narrow fallback; end-to-end specs and test data are not unit tests; one file without a command no longer stops the rest. - Whether the tests ran, and why not, is counted (`tests_ran`) on the run's checks, its notes and the pull request. Incident: tq_tests_run. --- docs/coder-loop.md | 7 +- docs/incidents/tq_tests_run.md | 22 + services/common/src/e2e/test_package.rs | 120 ++- services/common/src/test_env.rs | 496 +++++++++++- services/worker/src/passes/habits_check.rs | 712 +++++++++++++++--- .../src/passes/incidents/aj_coder_habits.rs | 5 +- .../incidents/rp_reproduce_before_planning.rs | 3 + .../src/passes/incidents/tq_tests_run.rs | 286 +++++++ services/worker/src/passes/mod.rs | 5 +- services/worker/src/passes/run_guard.rs | 20 +- services/worker/src/passes/test_bug.rs | 56 +- 11 files changed, 1608 insertions(+), 124 deletions(-) create mode 100644 docs/incidents/tq_tests_run.md create mode 100644 services/worker/src/passes/incidents/tq_tests_run.rs diff --git a/docs/coder-loop.md b/docs/coder-loop.md index 62ed64720..413386c23 100644 --- a/docs/coder-loop.md +++ b/docs/coder-loop.md @@ -113,7 +113,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 75a30911c..9a48c51b2 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -7048,6 +7048,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" @@ -8514,7 +8517,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)