From a2d01f6376649be7339f441733f5d79c2ae8cc0e Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Wed, 18 Nov 2026 14:10:39 -0500 Subject: [PATCH 1/4] Finished runs ship instead of stopping, and a changed test runs in its own package A run whose tasks are done goes on while each continuation closes something (a check runs that hadn't, or its open items fall below their best), never by a fixed count. A step the run asks for by design is not counted. When continuing closes nothing, the run ships its pull request with what is open listed, and the stop is taken back so CI's errors and comments start the next round. The changed tests' sandbox picks its install only from the files it runs, a missing runner is recorded as not run, and a test that ran and fails or proves nothing holds the draft. --- docs/incidents/da_finished_run_ships.md | 5 + .../db_test_runs_in_its_own_package.md | 5 + docs/incidents/p_finished_work_loop.md | 2 +- services/common/src/test_env.rs | 10 +- services/gateway/src/routes/analytics.rs | 3 + services/worker/src/passes/habits_check.rs | 96 +++- .../passes/incidents/da_finished_run_ships.rs | 164 +++++++ .../db_test_runs_in_its_own_package.rs | 179 ++++++++ .../passes/incidents/p_finished_work_loop.rs | 42 +- services/worker/src/passes/mod.rs | 40 +- services/worker/src/passes/replay/mod.rs | 10 +- services/worker/src/passes/resume.rs | 5 + services/worker/src/passes/run_guard.rs | 410 ++++++++++++++++-- 13 files changed, 905 insertions(+), 66 deletions(-) create mode 100644 docs/incidents/da_finished_run_ships.md create mode 100644 docs/incidents/db_test_runs_in_its_own_package.md create mode 100644 services/worker/src/passes/incidents/da_finished_run_ships.rs create mode 100644 services/worker/src/passes/incidents/db_test_runs_in_its_own_package.rs diff --git a/docs/incidents/da_finished_run_ships.md b/docs/incidents/da_finished_run_ships.md new file mode 100644 index 000000000..e05a11897 --- /dev/null +++ b/docs/incidents/da_finished_run_ships.md @@ -0,0 +1,5 @@ +# da. `da_finished_run_ships` + +**What happened:** Two runs on one ticket finished every planned task, opened their draft pull requests, and were then stopped with "CoderHelm stopped this run and handed it to you: its tasks were done and it had continued 4 more times without finishing". Of the four continuations, two were steps that ran out of time inside fix rounds that were closing findings, one was a step the run asked for by design so the changed tests could run with and without the change, and one was the fix round that check started. A fixed count of continuations after the work stopped runs that were still making progress. The stop also stayed on the run, so when the pull request's preview check went red with a readable error, the CI fix round hit the stop on its first pass and the run ended failed instead of fixed. + +**The guarantee:** There is no count of continuations after the work. Each continuation names what it is for: the checks not yet run and the items they left open (`run_guard::Target`). The run goes on while each continuation closes something, and a step the run asks for by design is never counted. Once continuing closes nothing, or nothing is left, the run ships the pull request with what is open listed, and the stop is taken back at once (`run_guard::lift_shipped_stop`), so a red check with its error or a comment starts the next round. Finished work is never handed back and never failed because of a stop; runs stopped the older way are taken back the same way when their CI goes red. diff --git a/docs/incidents/db_test_runs_in_its_own_package.md b/docs/incidents/db_test_runs_in_its_own_package.md new file mode 100644 index 000000000..6bd345c1a --- /dev/null +++ b/docs/incidents/db_test_runs_in_its_own_package.md @@ -0,0 +1,5 @@ +# db. `db_test_runs_in_its_own_package` + +**What happened:** A web change added a unit test in the web app and an end-to-end spec in the repository's end-to-end folder. The check that runs each changed test with and without the change chose its sandbox's install from the end-to-end job, because one of the files was that job's spec, and that job installs only its own folder. The unit test printed `sh: 1: vitest: not found` both ways. The check read that as "fails with the change in place" and "no changed test fails without the change", spent a fix round rewriting a test that had never run, and listed two findings that weren't true. + +**The guarantee:** The sandbox's install is chosen only by the files the sandbox runs (an end-to-end spec runs against a preview, never there), and a recorded job is kept only when its folder covers every file (`TestEnv::misses`). A test whose runner isn't installed didn't run: it is recorded as not run because the install failed, never as a failure of the change and never as proof of it. A test that did run and fails with the change, passes without it, or proves nothing is a check the change didn't pass: it holds the draft (`proof::holds_blocked_on`), even with CI green, so the run can't be done with it open. diff --git a/docs/incidents/p_finished_work_loop.md b/docs/incidents/p_finished_work_loop.md index 0e5641aad..08291c553 100644 --- a/docs/incidents/p_finished_work_loop.md +++ b/docs/incidents/p_finished_work_loop.md @@ -2,4 +2,4 @@ **What happened:** A small ticket finished its 11 tasks, then spent 2.5 hours and $41.96 with no pull request: each 15-minute step re-ran the checks before the pull request from nothing and started fresh fix rounds. -**The guarantee:** The draft pull request opens before the proof check, the rules and the review, which then can't block it. A check runs once on a head and keeps its rounds across steps. A run with no real progress (tasks, the pull request, CI green, fewer findings) ends one way: a draft with Open items, waiting on a person. +**The guarantee:** The draft pull request opens before the proof check, the rules and the review, which then can't block it. A check runs once on a head and keeps its rounds across steps. A run with no real progress (tasks, the pull request, CI green, fewer findings) ends its steps one way: a draft with Open items. Once its tasks are done that draft is shipped, not handed back: CI's errors and comments still start rounds on it (see `da_finished_run_ships`). diff --git a/services/common/src/test_env.rs b/services/common/src/test_env.rs index bbad89fc9..247f51362 100644 --- a/services/common/src/test_env.rs +++ b/services/common/src/test_env.rs @@ -744,7 +744,10 @@ pub fn package_test_command( 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. + /// changes or runs): its tests run in a folder one of them is not in. A + /// job is kept only when it covers every file: a job chosen for one file + /// (an end-to-end suite in its own folder) installs nothing for a file + /// in another package, whose runner is then missing. pub fn misses(&self, focus: &[String]) -> bool { let dir = if self.dir.is_empty() { common_step_dir(&self.test) @@ -752,10 +755,9 @@ impl TestEnv { self.dir.clone() }; !dir.is_empty() - && !focus.is_empty() - && !focus + && focus .iter() - .any(|f| f.trim_start_matches("./").starts_with(&format!("{dir}/"))) + .any(|f| !f.trim_start_matches("./").starts_with(&format!("{dir}/"))) } /// Each test step that calls a package script or a make target diff --git a/services/gateway/src/routes/analytics.rs b/services/gateway/src/routes/analytics.rs index 73483f8a9..841ceb453 100644 --- a/services/gateway/src/routes/analytics.rs +++ b/services/gateway/src/routes/analytics.rs @@ -729,6 +729,9 @@ pub fn ended_wrong(runs: &[&RunRow]) -> Value { fn loop_stop_label(code: &str) -> String { match code { "continuations_after_work" => "Kept continuing after its tasks were done".into(), + "converged_with_open_items" => { + "Shipped with open items once continuing closed nothing".into() + } "continuations" => "Kept continuing without finishing a task".into(), "pass_transitions" => "Kept moving between steps without progress".into(), "spend" => "Spent too much without progress".into(), diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index 3be1b3a85..17765b360 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -321,11 +321,60 @@ const BEFORE_ASSERT_MARKS: &[&str] = &[ "build failed", ]; +/// The test runner itself isn't there: the sandbox's install didn't give the +/// file's package its dependencies (an install for another package, none at +/// all). Whatever the test says, it never ran, so it is never a failure of +/// the change, nor a proof of it. +const NO_RUNNER_MARKS: &[&str] = &[ + "spawn enoent", + "node_modules missing", + "is not recognized as an internal or external command", + "no module named pytest", +]; + +/// Whether a run's output says its runner wasn't there: the shell couldn't +/// find the command, or the package manager says the dependencies are missing. +fn runner_missing(output: &str) -> bool { + has_any(output, NO_RUNNER_MARKS) + || output.lines().any(|l| { + let l = l.trim().to_ascii_lowercase(); + ["sh:", "bash:", "/bin/sh:", "zsh:"] + .iter() + .any(|sh| l.starts_with(sh)) + && l.contains("not found") + }) +} + +/// Why a file didn't run when its runner was missing, from what it printed. +fn no_runner(output: &str) -> String { + format!( + "{INSTALL_FAILED}: the test runner wasn't installed for this file's package ({})", + excerpt_of( + output, + &["not found", "enoent", "missing", "not recognized"] + ) + ) +} + fn has_any(text: &str, marks: &[&str]) -> bool { let low = text.to_ascii_lowercase(); marks.iter().any(|m| low.contains(m)) } +/// The first line of `output` with one of `words`, else its first line. +fn excerpt_of(output: &str, words: &[&str]) -> String { + let line = output + .lines() + .map(str::trim) + .find(|l| { + let low = l.to_ascii_lowercase(); + words.iter().any(|w| low.contains(w)) + }) + .or_else(|| output.lines().map(str::trim).find(|l| !l.is_empty())) + .unwrap_or(""); + common::truncate_str(line, 200).replace('`', "'") +} + /// The first line of a failing run that says what failed. fn excerpt(output: &str) -> String { let lines: Vec<&str> = output @@ -355,12 +404,18 @@ pub fn verdict(with: &FileRun, without: &FileRun) -> (Verdict, String) { Verdict::NotRun, "the sandbox gave no result for it".to_string(), ), + (Some(w), _) if w != 0 && runner_missing(&with.output) => { + (Verdict::NotRun, no_runner(&with.output)) + } (Some(w), _) if w != 0 && has_any(&with.output, NOT_FOUND_MARKS) => ( Verdict::NotRun, "the test command, scoped to this file, found no tests in it".to_string(), ), (Some(w), _) if w != 0 => (Verdict::FailsWithChange, excerpt(&with.output)), (Some(_), Some(0)) => (Verdict::PassesEitherWay, String::new()), + (Some(_), Some(c)) if c != 0 && runner_missing(&without.output) => { + (Verdict::NotRun, no_runner(&without.output)) + } (Some(_), Some(_)) if has_any(&without.output, NOT_FOUND_MARKS) => ( Verdict::NotRun, "the test command found no tests in it without the change".to_string(), @@ -700,6 +755,9 @@ fn repro_waived(plan: &PlanResult) -> bool { /// 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 check's name on an Open items line that holds the draft. +pub const TEST_CHECK: &str = "The changed tests"; + /// 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."; @@ -835,6 +893,7 @@ pub fn fix_feedback(lines: &[String]) -> String { /// What is still open after the fix rounds, for Open items. pub fn open_findings(f: &PrFacts, plan: &PlanResult) -> Vec { let mut lines = blocking(f, plan); + let ran = lines.clone(); if unproven(f, plan) && !lines.iter().any(|l| l == UNPROVEN) { lines.push(UNPROVEN.to_string()); } @@ -874,6 +933,14 @@ pub fn open_findings(f: &PrFacts, plan: &PlanResult) -> Vec { "No end-to-end test for a visible change", "CoderHelm writes the spec in its next round on this pull request and runs it on the preview.", ) + } else if ran.contains(&l) { + // A test that ran and fails with the change, passes without + // it, or proves nothing: the change isn't shown to work, so + // the run isn't done. It holds the draft like any check the + // change didn't pass (`proof::holds_blocked_on`), and it is a + // gap the run's next round works on. + let what = l.split(". ").next().unwrap_or(&l).trim_end_matches('.'); + return super::proof::blocked_item(TEST_CHECK, what); } else { ( "Test doesn't prove the change", @@ -1173,6 +1240,22 @@ fn is_e2e_spec(tree: &[String], file: &str, texts: &dyn Fn(&str) -> Option Vec { + let suite = common::preview::e2e_suite(tree); + files + .iter() + .filter(|f| { + !suite + .as_ref() + .is_some_and(|s| f.starts_with(&format!("{}/", s.dir.trim_end_matches('/')))) + }) + .cloned() + .collect() +} + /// 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. @@ -1286,7 +1369,11 @@ impl Bench for SandboxBench<'_> { .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. + // its test steps (package scripts read through) run each file. Only + // the files this sandbox runs choose it: an end-to-end spec runs + // against a preview, and its job's install (its own folder) never + // installs a unit test's package. + let unit = unit_focus(&tree, files); let env = super::test_setup::for_run( r.state, r.github, @@ -1296,7 +1383,7 @@ impl Bench for SandboxBench<'_> { self.base_branch, self.branch, r.run_id, - files, + &unit, ) .await; let mut texts: std::collections::HashMap = Default::default(); @@ -2093,8 +2180,11 @@ mod tests { assert!(b[0].contains("passes with the change taken out")); assert_eq!(b[1], UNPROVEN); assert!(fix_feedback(&b).contains("Do not delete or skip a test")); + // A test that ran and proves nothing is a check the change didn't + // pass: it holds the draft. let open = open_findings(&f, &p); - assert_eq!(open[0].point, "Test doesn't prove the change"); + assert_eq!(open[0].point, "check_blocked"); + assert!(open[0].detail.starts_with(TEST_CHECK), "{}", open[0].detail); assert!(section(&p, &f).contains("passes with and without the change")); } diff --git a/services/worker/src/passes/incidents/da_finished_run_ships.rs b/services/worker/src/passes/incidents/da_finished_run_ships.rs new file mode 100644 index 000000000..37801ccf5 --- /dev/null +++ b/services/worker/src/passes/incidents/da_finished_run_ships.rs @@ -0,0 +1,164 @@ +//! da. Two runs on one ticket finished every planned task, opened their draft +//! pull requests, and were then stopped with "CoderHelm stopped this run and +//! handed it to you: its tasks were done and it had continued 4 more times +//! without finishing". The four continuations were: two steps that ran out of +//! time inside the proof check's and the rules' fix rounds (each round closed +//! a finding), one step the run asked for by design so the changed tests could +//! run with and without the change, and the step whose fix round that check +//! started. A fixed count of continuations after the work stopped a run that +//! was still closing things. The stop left `guard_open` on the run, so when +//! the pull request's `Deploy Preview` check went red with a readable error, +//! the CI fix round's first pass hit the stop and the run was failed instead +//! of fixed. +//! +//! Guarantee: there is no count of continuations after the work. Each +//! continuation names what it is for, the checks not yet run and the items +//! they left open (`run_guard::Target`), and the run goes on while each one +//! closes something. A step the run asks for by design is never counted. Once +//! continuing closes nothing (or nothing is left), the run ships: the pull +//! request carries what is open, the stop is taken back at once +//! (`run_guard::lift_shipped_stop`), and a red check with its error or a +//! comment starts the next round. Finished work is never handed back and +//! never failed for a stop. + +use super::fixture::fn_src; +use crate::passes::run_guard::*; + +/// The checks a run keeps, at the start of the checks after the work: none +/// has given a result. +fn ledger() -> Ledger { + Ledger::default() +} + +fn finding(point: &str, detail: &str) -> crate::passes::proof::Finding { + crate::passes::proof::Finding { + point: point.into(), + detail: detail.into(), + ..Default::default() + } +} + +/// The recorded run's steps after its tasks were done, each continuation's +/// target read from the checks' ledger as that step left it. +fn replay() -> (GuardState, Vec>) { + let mut g = GuardState::default(); + g.apply(&Progress::TasksDone(6)); + g.apply(&Progress::WorkDone); + g.apply(&Progress::PrOpen); + let mut trips = Vec::new(); + // Step 3: the test and security audit need a fresh step; no check ran. + let mut l = ledger(); + g.on_continuation_to(0.7, &Target::of(&l)); + trips.push(g.trip()); + // Step 4: the proof check ran and its fix round closed some of its gaps; + // time ran out in the round. + l.proof.head = "h1".into(); + l.proof_findings = Some(vec![ + finding("ci_pending", "the build isn't run"), + finding("ci_pending", "the new spec hasn't run"), + finding("team_rule", "blocks are tested on the components page"), + ]); + g.on_continuation_to(1.2, &Target::of(&l)); + trips.push(g.trip()); + // Step 5: the rules ran and their round fixed what they found. + l.rules_outcome = Some(Ok(None)); + l.links_outcome = Some(Ok(String::new())); + l.test_outcome = Some(Ok(None)); + g.on_continuation_to(1.4, &Target::of(&l)); + trips.push(g.trip()); + // Step 6: the changed tests need a step of their own, by design. + g.on_continuation_to( + 0.1, + &Target { + owed: true, + ..Default::default() + }, + ); + trips.push(g.trip()); + // Step 7: the tests and scope check ran; its fix round worked on what it + // found, and the step ran out of time. + l.habits_outcome = Some(Ok(None)); + g.on_continuation_to(1.1, &Target::of(&l)); + trips.push(g.trip()); + (g, trips) +} + +#[test] +fn a_run_that_keeps_closing_things_is_never_stopped() { + let (g, trips) = replay(); + assert!(trips.iter().all(Option::is_none), "{trips:?}"); + assert_eq!(g.stale, 0); + // Only the owed step went uncounted. + assert_eq!(g.after_work, 4); +} + +#[test] +fn a_run_that_stops_closing_things_ships_and_is_never_handed_back() { + let (mut g, _) = replay(); + let l = { + let mut l = ledger(); + l.proof.head = "h2".into(); + l.proof_findings = Some(vec![finding("ci_pending", "the build isn't run")]); + l.rules_outcome = Some(Ok(None)); + l.links_outcome = Some(Ok(String::new())); + l.test_outcome = Some(Ok(None)); + l.habits_outcome = Some(Ok(None)); + l + }; + // The same open item, step after step: no check left to run and nothing + // closed. + g.on_continuation_to(1.0, &Target::of(&l)); + g.on_continuation_to(1.0, &Target::of(&l)); + assert_eq!(g.trip(), None, "one stale step is allowed"); + g.on_continuation_to(1.0, &Target::of(&l)); + let trip = g.trip().expect("it stops continuing"); + assert_eq!(trip, Trip::Converged); + assert!(trip.ships()); + let why = trip.reason(&g); + assert!(!why.contains("handed it to you"), "{why}"); + assert!(why.contains("Open items"), "{why}"); + // Older runs stopped by the count of continuations ship the same way. + assert!(ships_code(trip.code())); + assert!(ships_code("continuations_after_work")); + assert!(!ships_code("spend")); + assert!(!ships_code("ceiling_spend")); + // Shipping starts convergence over: the rounds CI or a comment starts + // aren't stopped by the steps before them. + g.shipped(); + assert_eq!(g.trip(), None); +} + +/// Every continuation names its target from the run's checks, the changed +/// tests' own step is owed, the draft's stop is taken back once the work is +/// on the pull request, and a red check's fix round takes it back before its +/// first pass. +#[test] +fn the_pipeline_targets_each_continuation_and_takes_back_a_shipping_stop() { + let src = include_str!("../mod.rs"); + let cont = fn_src(src, "\nasync fn try_auto_continue("); + assert!( + cont.contains("run_guard::on_continuation(state, &msg.team_id, run_id, &scope, owed)"), + "{cont}" + ); + // The hand-off in the checks (the last mention: a test lists it first). + let owed = src + .rfind("\"Running the changed tests with and without the change needs a step of its own\",") + .expect("the changed tests' hand-off"); + assert!(src[owed..owed + 200].contains("true,")); + let guard = include_str!("../run_guard.rs"); + let end = fn_src(guard, "\npub async fn end_if_stopped("); + assert!(end.contains("lift_shipped_stop("), "{end}"); + let settle = fn_src(guard, "\npub async fn settle_open_pr("); + assert!( + settle.find("lift_shipped_stop(").unwrap() < settle.find("stop_judge").unwrap(), + "a shipping stop is never judged as a hand-back" + ); + let resume = include_str!("../resume.rs"); + let lift = resume + .find("super::run_guard::lift_shipped_stop(state, &msg.team_id, &msg.run_id).await;") + .expect("the CI fix round takes back a shipping stop"); + let pass = resume[lift..] + .find("super::update_pass(state, &msg.team_id, &msg.run_id, \"implement\")") + .expect("then starts its pass"); + assert!(pass < 200); +} diff --git a/services/worker/src/passes/incidents/db_test_runs_in_its_own_package.rs b/services/worker/src/passes/incidents/db_test_runs_in_its_own_package.rs new file mode 100644 index 000000000..3ef538e26 --- /dev/null +++ b/services/worker/src/passes/incidents/db_test_runs_in_its_own_package.rs @@ -0,0 +1,179 @@ +//! db. A web change added a unit test (`apps/web/...test.tsx`) and an +//! end-to-end spec (`e2e/tests/...spec.ts`). The check that runs each changed +//! test with and without the change picked its sandbox's install from the +//! end-to-end job, chosen because one of the files was its spec, and that job +//! installs only its own folder. The unit test then printed +//! `sh: 1: vitest: not found` both ways, and the check read that as "fails +//! with the change in place" and "no changed test fails without the change". +//! The run spent a fix round rewriting a test that had never run, and listed +//! two findings that weren't true; the run's own coder ran the same test in +//! its shell and it passed. +//! +//! Guarantee: the sandbox's install is chosen only by the files it runs (an +//! end-to-end spec runs against a preview, never there), and a job is kept +//! only when its folder covers every file (`TestEnv::misses`). A test whose +//! runner isn't installed didn't run: it is recorded as not run, never as a +//! failure of the change nor as a proof of it. A test that did run and fails +//! with the change, or proves nothing, holds the pull request as a check the +//! change didn't pass, so the run can't be done with it open. + +use crate::passes::habits_check::{self, Bench, FileRun, Runs, Verdict}; +use crate::passes::plan::PlanResult; +use common::test_env::TestEnv; + +const UNIT: &str = "apps/web/src/test/components/block.test.tsx"; +const SPEC: &str = "e2e/tests/site/block.spec.ts"; + +/// What the sandbox printed for the unit test, both ways: the runner missing. +const NO_RUNNER: &str = "> web@0.1.0 test /tmp/src/repo/apps/web\n\ + > vitest block.test.tsx\n\n\ + sh: 1: vitest: not found\n\ + /tmp/src/repo/apps/web:\n\ + ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL web@0.1.0 test: `vitest block.test.tsx`\n\ + spawn ENOENT\n\ + WARN Local package.json exists, but node_modules missing, did you mean to install?"; + +struct Recorded(Runs); + +#[async_trait::async_trait] +impl Bench for Recorded { + async fn run(&self, _files: &[String]) -> Result { + Ok(self.0.clone()) + } +} + +fn tree() -> Vec { + [ + "package.json", + "pnpm-workspace.yaml", + "apps/web/package.json", + "apps/web/src/components/blocks/block.tsx", + UNIT, + "e2e/package.json", + "e2e/playwright.config.ts", + SPEC, + ] + .iter() + .map(|s| s.to_string()) + .collect() +} + +fn plan() -> PlanResult { + PlanResult { + proposal: String::new(), + tasks: String::new(), + spec: String::new(), + design: String::new(), + repo_tasks: vec![], + fix: None, + } +} + +fn diff() -> Vec<(String, String, String)> { + ["apps/web/src/components/blocks/block.tsx", UNIT, SPEC] + .iter() + .map(|p| (p.to_string(), "modified".to_string(), String::new())) + .collect() +} + +fn missing() -> FileRun { + FileRun { + code: Some(1), + output: NO_RUNNER.into(), + } +} + +fn e2e() -> FileRun { + FileRun { + code: None, + output: habits_check::E2E_SPEC.into(), + } +} + +/// The recorded runs: the unit test's runner missing both ways, the spec not +/// run in the sandbox. Nothing ran, so nothing failed and nothing is proven. +#[tokio::test] +async fn a_test_whose_runner_is_missing_did_not_run() { + let bench = Recorded(Runs { + with: vec![missing(), e2e()], + without: vec![missing(), e2e()], + }); + let f = habits_check::check_once(&bench, &diff(), &plan(), "acme/site", &[], "").await; + assert_eq!(f.tests[0].verdict, Verdict::NotRun, "{:?}", f.tests[0]); + assert!( + f.tests[0].detail.contains("install failed"), + "{}", + f.tests[0].detail + ); + let blocking = habits_check::blocking(&f, &plan()); + assert!( + !blocking + .iter() + .any(|l| l.contains("fails with the change in place")), + "{blocking:?}" + ); + assert!(!blocking.contains(&habits_check::UNPROVEN.to_string())); + assert!(f.tests_ran.line().contains("install failed")); +} + +/// The sandbox's job is chosen by the unit test alone: the end-to-end spec +/// never picks it. +#[test] +fn the_install_is_chosen_by_the_files_the_sandbox_runs() { + let focus = habits_check::unit_focus(&tree(), &[UNIT.to_string(), SPEC.to_string()]); + assert_eq!(focus, vec![UNIT.to_string()]); +} + +/// A job whose folder doesn't cover every file is another package's: the +/// end-to-end job kept from an earlier choice is worked out again for the +/// unit test, even when one of the files is its own. +#[test] +fn a_job_is_kept_only_when_it_covers_every_file() { + let e2e_job = TestEnv { + dir: "e2e".into(), + install: vec!["pnpm install --frozen-lockfile --ignore-workspace".into()], + test: vec!["pnpm exec playwright test".into()], + ..Default::default() + }; + assert!(e2e_job.misses(&[UNIT.to_string(), SPEC.to_string()])); + assert!(e2e_job.misses(&[UNIT.to_string()])); + assert!(!e2e_job.misses(&[SPEC.to_string()])); + assert!(!e2e_job.misses(&[])); +} + +/// A test that ran and fails with the change is a check the change didn't +/// pass: it holds the draft, so the run is never done with it open. +#[tokio::test] +async fn a_test_that_ran_and_fails_holds_the_pull_request() { + let bench = Recorded(Runs { + with: vec![ + FileRun { + code: Some(1), + output: "AssertionError: expected 'closed' to be 'open'".into(), + }, + e2e(), + ], + without: vec![ + FileRun { + code: Some(1), + output: "AssertionError: expected 'closed' to be 'open'".into(), + }, + e2e(), + ], + }); + let f = habits_check::check_once(&bench, &diff(), &plan(), "acme/site", &[], "").await; + assert_eq!(f.tests[0].verdict, Verdict::FailsWithChange); + let open = habits_check::open_findings(&f, &plan()); + assert!( + open.iter() + .any(|o| o.point == "check_blocked" && o.detail.contains(UNIT)), + "{open:?}" + ); + // Written as the pull request writes it, it holds the draft even with + // CI green: CI passing doesn't make the test prove the change. + let body = crate::passes::proof::gaps_section(&open); + assert!( + crate::passes::proof::holds_blocked_on(&body, true), + "{body}" + ); +} diff --git a/services/worker/src/passes/incidents/p_finished_work_loop.rs b/services/worker/src/passes/incidents/p_finished_work_loop.rs index e7c07e7d0..1782226e6 100644 --- a/services/worker/src/passes/incidents/p_finished_work_loop.rs +++ b/services/worker/src/passes/incidents/p_finished_work_loop.rs @@ -7,7 +7,8 @@ //! Guarantee: the draft pull request opens as soon as the work is built, before //! the checks, which then can't hold it back. A check runs once on a head and //! keeps its rounds for the whole run. And whatever any pass does, a run with no -//! real progress ends one way: a draft with its Open items, waiting on a person. +//! real progress ends its steps one way: a draft with its Open items, shipped +//! once the tasks are done (`da_finished_run_ships`). use crate::passes::proof::{self, Finding, Next}; use crate::passes::run_guard::*; @@ -70,7 +71,18 @@ fn replay(work_done: bool) -> Replayed { }; } } - g.on_continuation(0.0); + // Each continuation names what it is for: the proof check's open + // items as that step left them. + g.on_continuation_to( + 0.0, + &Target { + owed: false, + unrun: 0, + open: (0..counts[step % counts.len()]) + .map(|i| format!("gap {i}")) + .collect(), + }, + ); if let Some(trip) = g.trip() { return Replayed { trip: Some(trip), @@ -88,16 +100,18 @@ fn replay(work_done: bool) -> Replayed { } } -/// With nothing else changed, the guard alone stops that run at its fourth -/// continuation: 22 passes and about $15.26, 36% of what it spent. +/// With nothing else changed, the guard alone ends that run's steps at its +/// third continuation, the second in a row that closed nothing (the proof +/// check's count went 2, 4, 3 with the tasks done), and ships it: 16 passes, +/// under a third of what it spent. #[test] -fn the_recorded_run_stops_at_its_fourth_continuation() { +fn the_recorded_run_ships_once_its_continuations_stop_closing_anything() { let r = replay(true); - assert_eq!(r.trip, Some(Trip::ContinuationsAfterWork)); - assert_eq!(r.continuations, 4); - assert_eq!(r.passes, 22); - assert!((r.usd - 15.26).abs() < 0.01, "{}", r.usd); - assert!(r.usd < INCIDENT_USD / 2.0); + assert_eq!(r.trip, Some(Trip::Converged)); + assert!(Trip::Converged.ships()); + assert_eq!(r.continuations, 3); + assert_eq!(r.passes, 16); + assert!(r.usd < INCIDENT_USD / 3.0, "{}", r.usd); } /// Even if the run never reported its tasks done, it doesn't go the distance. @@ -645,9 +659,13 @@ fn a_normal_large_ticket_never_trips_the_guard() { fn the_steps_are_ended_by_a_reason_a_person_can_act_on() { let r = replay(true); let g = GuardState { - after_work: r.continuations as u32, + stale: 2, ..Default::default() }; let why = r.trip.unwrap().reason(&g); - assert!(why.contains("handed it to you"), "{why}"); + // Finished work is shipped, never handed back: what is open is on the + // pull request, and CI or a comment starts the next round. + assert!(!why.contains("handed it to you"), "{why}"); + assert!(why.contains("Open items"), "{why}"); + assert!(why.contains("a push or a comment"), "{why}"); } diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index d09b4c4c7..30d47a2c4 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -368,6 +368,7 @@ impl Handoff { /// step starts, see `steps`); only the team's usage limit, a person /// cancelling and the runaway ceiling stop it here. `why` is what the run /// page reads ("... continuing in step N"). +#[allow(clippy::too_many_arguments)] async fn try_auto_continue( state: &WorkerState, msg: &TicketMessage, @@ -376,6 +377,8 @@ async fn try_auto_continue( continuable_passes: &[&str], planning: bool, why: &str, + // A step the run asks for by design (`run_guard::Target::owed`). + owed: bool, ) -> Handoff { // Gate on the checkpoint's pass IDENTITY, not just on there being a branch. // The wall-clock-timeout arm passes the broad set (any late pass with work @@ -403,7 +406,10 @@ async fn try_auto_continue( steps::MAX_RUN_STEPS )); } - if let Some(reason) = run_guard::on_continuation(state, &msg.team_id, run_id).await { + let scope = format!("{}/{}", msg.repo_owner, msg.repo_name); + if let Some(reason) = + run_guard::on_continuation(state, &msg.team_id, run_id, &scope, owed).await + { return Handoff::Stopped(reason); } let now_ms = chrono::Utc::now().timestamp_millis().max(0) as u64; @@ -1661,6 +1667,7 @@ pub async fn orchestrate_ticket( &["implement", "implement_started", "security"], false, "The coder used this step's turns with work left", + false, ) .await .continued(); @@ -1683,6 +1690,7 @@ pub async fn orchestrate_ticket( &["implement", "implement_started", "security"], false, "A step after the work stopped on an error; the next one tries again", + false, ) .await .continued(); @@ -1797,6 +1805,7 @@ pub async fn orchestrate_ticket( } else { "This step reached its time limit with work left" }, + false, ) .await; @@ -4234,7 +4243,8 @@ async fn run_passes( None, "The remaining planned tasks made no progress; the run goes on with the work on the branch", usage, - ) +false, +) .await; } info!(run_id, step, stalled, at = %at, "Continuing the run in this step"); @@ -5533,6 +5543,7 @@ async fn run_passes( &["implement_started"], false, "Planning used most of this step; the coder starts in a fresh one", + false, ) .await; if handoff.continued() { @@ -5589,6 +5600,7 @@ async fn run_passes( &["implement_started"], false, "The dependency checks continue in a fresh step", + false, ) .await; if handoff.continued() { @@ -5882,6 +5894,7 @@ async fn run_passes( &["implement_started"], false, "The coder ran out of this step's time before writing a file", + false, ) .await; if handoff.continued() { @@ -6285,6 +6298,7 @@ async fn run_passes( "{} planned task(s) not done yet", cov.required_missing().len() ), + false, ) .await; if handoff.continued() { @@ -6327,6 +6341,7 @@ async fn run_passes( None, "The work is built; its test and security audit need more time than this step has left", usage, + false, ) .await; } @@ -6373,7 +6388,8 @@ async fn run_passes( None, "The work changed files a code generator reads and this step has too little time left for the generator's build", usage, - ) +false, +) .await; } } @@ -6745,7 +6761,8 @@ async fn run_passes( Some(&carry), "The generator check needs a sandbox build and this step has too little time left for one", usage, - ) +false, +) .await; } Err(generators::GateStop::Blocked(why)) => { @@ -6888,7 +6905,8 @@ async fn run_passes( Some(&carry), "The work is built; opening the pull request needs more time than this step has left", usage, - ) +false, +) .await; } update_pass(state, &msg.team_id, run_id, "pr").await?; @@ -7092,6 +7110,7 @@ async fn run_passes( Some(&carry), $why, usage, + false, ) .await; } @@ -7205,6 +7224,7 @@ async fn run_passes( Some(&carry), "Running the changed tests with and without the change needs a step of its own", usage, + true, ) .await; } @@ -7503,6 +7523,7 @@ async fn plan_again_or_stop( &[], true, &format!("Plan check (format): {why}; planning again"), + false, ) .await { @@ -7545,11 +7566,14 @@ async fn hand_off_at( carry: Option<&steps::Carry>, why: &str, usage: &TokenUsage, + // The run asks for this step by design (the changed tests' sandbox + // runs need a whole one): the run guard doesn't count it. + owed: bool, ) -> Result<(), Box> { save_checkpoint(state, &msg.team_id, run_id, "implement", branch, 0, usage).await; steps::save_gate(state, &msg.team_id, run_id, gate, carry).await; let from = Some(("implement".to_string(), branch.to_string(), 0u8)); - match try_auto_continue(state, msg, run_id, &from, &["implement"], false, why).await { + match try_auto_continue(state, msg, run_id, &from, &["implement"], false, why, owed).await { Handoff::Continued => Ok(()), Handoff::Stopped(reason) => { let kept = keep_wip_branch(github, &msg.repo_owner, &msg.repo_name, branch).await; @@ -7586,7 +7610,9 @@ async fn settle_in_fresh_step( .await; steps::save_mark(state, &msg.team_id, run_id, "", 0, 0).await; let from = Some(("implement".to_string(), branch.to_string(), 0u8)); - try_auto_continue(state, msg, run_id, &from, &["implement"], false, why).await + // Owed: the settle stage's own steps are bounded (`settle::MAX_STEPS`) + // and wait for a sandbox window, which is no sign of a loop. + try_auto_continue(state, msg, run_id, &from, &["implement"], false, why, true).await } /// A finished run's checks, again, in a fresh step of the run that resumes diff --git a/services/worker/src/passes/replay/mod.rs b/services/worker/src/passes/replay/mod.rs index 506694b54..f8d77caa6 100644 --- a/services/worker/src/passes/replay/mod.rs +++ b/services/worker/src/passes/replay/mod.rs @@ -362,7 +362,15 @@ fn run_loop(c: &Case, model: &Model) -> Result<(), String> { fix_rounds += 1; } } - guard.on_continuation(usd); + // The continuation names its target: the proof check's open items. + guard.on_continuation_to( + usd, + &crate::passes::run_guard::Target { + owed: false, + unrun: 0, + open: (0..open).map(|n| format!("gap {n}")).collect(), + }, + ); totals.continuations += 1; totals.spend_usd += usd; if guard.trip().is_some() || totals.over().is_some() { diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 0a7c9e092..7887e6cb1 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -2772,6 +2772,11 @@ pub async fn run( super::webhooks::emit_ci_fix_started(state, &ci_fix, &failing_checks).await; let pass_start = std::time::Instant::now(); let usage_before = usage.clone(); + // A red check with its error is new evidence on a shipped run: a stop + // that shipped the work (its tasks done) never keeps this round from + // starting. The round's own bounds (the fix ledger, the pushes, the + // run's ceiling) still hold. + super::run_guard::lift_shipped_stop(state, &msg.team_id, &msg.run_id).await; super::update_pass(state, &msg.team_id, &msg.run_id, "implement").await?; let plan_result = plan::PlanResult { diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index 9105e8780..dd7dc96a0 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -62,10 +62,14 @@ pub const MAX_RULES_FIX_ROUNDS: u32 = 2; pub const MAX_LINK_FIX_ROUNDS: u32 = 1; /// Failing-test fix rounds in one run, across all its steps. pub const MAX_TEST_FIX_ROUNDS: u32 = 2; -/// Continuations a run may take once its tasks are done. Findings going down -/// don't reset this: opening the pull request and checking it take one step, -/// and three more fresh 15-minute steps are far more than finished work needs. -pub const MAX_CONTINUATIONS_AFTER_WORK: u32 = 3; +/// Continuations in a row, once the tasks are done, that brought the run no +/// closer to finished: no check that hadn't run ran, and the open items didn't +/// fall below their best. There is no count of continuations after the work +/// itself: a run goes on while each step closes something, and stops going on +/// (shipping what it has, with what is open listed) at the first stale step +/// past this one. A step the run asked for by design (the changed tests' own +/// sandbox step) is never counted ([`Target::owed`]). +pub const MAX_STALE_CONTINUATIONS: u32 = 1; /// Continuations without progress while the tasks are still being built: one /// task spread over six full steps (90 minutes) isn't happening. pub const MAX_CONTINUATIONS_WITHOUT_PROGRESS: u32 = 6; @@ -112,11 +116,23 @@ const _: () = assert!(MAX_TRANSITIONS_WITHOUT_PROGRESS >= worst_normal_run()); // ── The guard's state ────────────────────────────────────────────────────── +/// The stored code of a [`Trip::Converged`] stop. +pub const CONVERGED: &str = "converged_with_open_items"; + +/// Stop codes that ship the work instead of handing it back: the current one +/// and the after-work cap it replaced (still on older runs' records). +pub fn ships_code(code: &str) -> bool { + matches!(code, CONVERGED | "continuations_after_work") +} + /// Why the guard ended a run. The stored code is what analytics counts. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Trip { - /// Finished work kept continuing without a pull request. - ContinuationsAfterWork, + /// The tasks are done and continuing stopped closing anything (or left + /// nothing to close): the run ships what it has with what is open listed. + /// Never a hand-back: CI and comments on the pull request still start + /// rounds ([`Trip::ships`]). + Converged, /// Continuations without progress, tasks still open. Continuations, /// Pass transitions without progress. @@ -128,20 +144,41 @@ pub enum Trip { impl Trip { pub fn code(self) -> &'static str { match self { - Trip::ContinuationsAfterWork => "continuations_after_work", + Trip::Converged => CONVERGED, Trip::Continuations => "continuations", Trip::Transitions => "pass_transitions", Trip::Spend => "spend", } } + /// A stop that ships the work rather than handing it back: the tasks are + /// done, so what is left is checks and fixes CoderHelm can still make, + /// and new evidence (a red check with its error, a comment) starts them. + pub fn ships(self) -> bool { + matches!(self, Trip::Converged) + } + /// What the run page says, in plain words. pub fn reason(self, g: &GuardState) -> String { + if self == Trip::Converged { + let why = if g.nothing_left { + "nothing it can act on is open".to_string() + } else { + format!( + "its last {} continuation(s) closed nothing that was open", + g.stale + ) + }; + return format!( + "CoderHelm finished the work and shipped it on the pull request: its tasks are \ + done and {why}. What is still open is listed there under Open items with how each \ + is settled; CoderHelm fixes what CI reports on the pull request, and a push or a \ + comment there starts another round." + ); + } let what = match self { - Trip::ContinuationsAfterWork => format!( - "its tasks were done and it had continued {} more times without finishing", - g.after_work - ), + // Answered above: it ships, it is never handed back. + Trip::Converged => String::new(), Trip::Continuations => format!( "it continued {} times without finishing another task", g.continuations @@ -218,16 +255,130 @@ pub struct GuardState { /// a checker reporting 2, 4, 3, 2 has made no progress at all. #[serde(default)] pub low: BTreeMap, + /// Continuations in a row after the work that closed nothing + /// ([`MAX_STALE_CONTINUATIONS`]). + #[serde(default)] + pub stale: u32, + /// The fewest checks not yet run at an after-work continuation. + #[serde(default)] + pub best_unrun: Option, + /// The fewest open items at that many unrun checks. + #[serde(default)] + pub best_open: Option, + /// The last after-work continuation had no open item to work on. + #[serde(default)] + pub nothing_left: bool, +} + +/// What a continuation after the work is for: the run's checks as they +/// stand. Every continuation names its open items; one with none to work on +/// has nothing to continue for. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Target { + /// The run asked for this step by design (the changed tests' sandbox + /// runs need a whole step): it is no sign of a loop, so it isn't counted. + pub owed: bool, + /// Checks that haven't given a result yet. + pub unrun: usize, + /// The open items the checks left, one line each. + pub open: Vec, +} + +impl Target { + /// The ledger's checks as a continuation's target. + pub fn of(ledger: &Ledger) -> Target { + let unrun = ledger.unrun_checks(); + let mut open: Vec = ledger + .open_findings() + .into_iter() + .filter(|f| !f.detail.contains("didn't finish")) + .map(|f| format!("{}: {}", f.point, f.detail)) + .collect(); + // The tests and scope check's items: what its fix rounds work on. + if let Some(Ok(Some(facts))) = &ledger.habits_outcome { + let plan = super::plan::PlanResult { + proposal: String::new(), + tasks: String::new(), + spec: String::new(), + design: String::new(), + repo_tasks: vec![], + fix: None, + }; + open.extend( + super::habits_check::blocking(facts, &plan) + .into_iter() + .map(|l| format!("tests: {l}")), + ); + } + open.sort(); + open.dedup(); + Target { + owed: false, + unrun, + open, + } + } } impl GuardState { + /// A continuation with what it is for. Before the work is done this is + /// [`Self::on_continuation`]. After it, the run goes on only while it + /// converges: a check runs that hadn't, or the open items fall below their + /// best. A step the run owes by design isn't counted at all. A + /// continuation with no check left to run and nothing open has nothing to + /// do, and the run ships ([`Trip::Converged`]). + pub fn on_continuation_to(&mut self, spent: f64, target: &Target) { + self.spend_usd += spent.max(0.0); + if target.owed { + return; + } + if !self.work_done { + self.continuations = self.continuations.saturating_add(1); + return; + } + self.after_work = self.after_work.saturating_add(1); + self.nothing_left = target.unrun == 0 && target.open.is_empty(); + let open = target.open.len(); + let closer = match (self.best_unrun, self.best_open) { + (None, _) => true, + (Some(u), _) if target.unrun < u => true, + (Some(u), Some(o)) if target.unrun == u => open < o, + (Some(u), None) => target.unrun == u, + _ => false, + }; + if closer { + if self.best_unrun != Some(target.unrun) { + self.best_open = None; + } + self.best_unrun = Some(target.unrun); + self.best_open = Some(self.best_open.map_or(open, |o| o.min(open))); + self.stale = 0; + } else { + self.stale = self.stale.saturating_add(1); + } + } + + /// The run shipped after a [`Trip::Converged`]: its convergence starts + /// over, so the rounds new evidence starts (CI, a comment) aren't stopped + /// by the steps before it. + pub fn shipped(&mut self) { + self.stale = 0; + self.nothing_left = false; + self.best_unrun = None; + self.best_open = None; + self.reset(); + } + /// One pass started, with what was spent since the guard last looked. pub fn on_pass(&mut self, spent: f64) { self.transitions = self.transitions.saturating_add(1); self.spend_usd += spent.max(0.0); } - /// One continuation, with what was spent since the guard last looked. + /// One continuation with no target known, with what was spent since the + /// guard last looked: counted against progress like any other. The + /// pipeline always names its target ([`Self::on_continuation_to`]). + #[cfg(test)] pub fn on_continuation(&mut self, spent: f64) { self.continuations = self.continuations.saturating_add(1); self.spend_usd += spent.max(0.0); @@ -302,14 +453,14 @@ impl GuardState { /// A person acted on the run: everything starts again from here, and what /// the checks have reported stands. pub fn person_acted(&mut self) { - self.reset(); + self.shipped(); self.after_work = 0; } /// Whether the run has gone too far without progress. pub fn trip(&self) -> Option { - if self.after_work > MAX_CONTINUATIONS_AFTER_WORK { - return Some(Trip::ContinuationsAfterWork); + if self.work_done && (self.nothing_left || self.stale > MAX_STALE_CONTINUATIONS) { + return Some(Trip::Converged); } if self.continuations > MAX_CONTINUATIONS_WITHOUT_PROGRESS { return Some(Trip::Continuations); @@ -352,6 +503,8 @@ struct Loaded { totals: Totals, /// The reason, once the guard fired and no person has acted since. stopped: Option, + /// The stop's code (`loop_stop_reason`), empty when none. + stop_code: String, } /// Fails open: a read that doesn't answer never stops a run. @@ -363,8 +516,8 @@ async fn load(state: &WorkerState, team_id: &str, run_id: &str) -> Option Option bool { } /// A step is about to hand off (from `try_auto_continue`, so every -/// continuation). `Some(reason)` when the next step must not start. -pub async fn on_continuation(state: &WorkerState, team_id: &str, run_id: &str) -> Option { +/// continuation). `scope` is the repository whose checks the run keeps +/// (`owner/repo`): after the work, the continuation's target is what they +/// left open ([`Target::of`]). `owed`: the run asked for this step by design. +/// `Some(reason)` when the next step must not start. +pub async fn on_continuation( + state: &WorkerState, + team_id: &str, + run_id: &str, + scope: &str, + owed: bool, +) -> Option { let mut l = load(state, team_id, run_id).await?; if l.stopped.is_some() { return l.stopped; } let spent = take_spend(); - l.guard.on_continuation(spent); + let target = if owed { + Target { + owed: true, + ..Default::default() + } + } else if l.guard.work_done { + LedgerCell::load(state, team_id, run_id, scope) + .await + .update(|ledger| Target::of(ledger)) + } else { + Target::default() + }; + l.guard.on_continuation_to(spent, &target); l.totals.continuations = l.totals.continuations.saturating_add(1); l.totals.spend_usd += spent; save(state, team_id, run_id, &l.guard, 0, 1, spent).await; @@ -662,6 +842,46 @@ pub async fn person_acted(state: &WorkerState, team_id: &str, run_id: &str) { } } +/// Takes back a stop that ships the work ([`ships_code`]) once the work is on +/// its pull request: the stop ended the steps' loop, and nothing more. What +/// CoderHelm can still act on (a red check with its error, a comment, the +/// ready decision) goes on as on any open pull request; the run's lifetime +/// ceiling still holds every round. True when a stop was taken back. +pub async fn lift_shipped_stop(state: &WorkerState, team_id: &str, run_id: &str) -> bool { + let Some(mut l) = load(state, team_id, run_id).await else { + return false; + }; + if l.stopped.is_none() || !ships_code(&l.stop_code) { + return false; + } + l.guard.shipped(); + let Ok(json) = serde_json::to_string(&l.guard) else { + return false; + }; + match state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET run_guard = :g REMOVE guard_open") + .condition_expression("attribute_exists(run_id) AND loop_stop_reason = :code") + .expression_attribute_values(":g", attr_s(&json)) + .expression_attribute_values(":code", attr_s(&l.stop_code)) + .send() + .await + { + Ok(_) => { + info!(run_id, code = %l.stop_code, "Run guard: the shipped run goes on from its pull request"); + true + } + Err(e) => { + warn!(run_id, error = %e, "Run guard: could not take back a shipping stop"); + false + } + } +} + /// A message is ending, perhaps because a model call was refused: what it spent /// is counted, and a run that has gone over its ceiling is marked as stopped. async fn flush(state: &WorkerState, team_id: &str, run_id: &str) { @@ -752,10 +972,17 @@ pub async fn end_if_stopped( } None => Err("no branch to open a pull request from".into()), }; - if let Err(e) = opened { - // Nothing to open (no work yet): still never silent. - warn!(run_id, error = %e, "Run guard: no draft pull request for the stopped run"); - super::mark_run_stopped_by_guard(state, msg, run_id, &reason, &judged).await; + match opened { + Err(e) => { + // Nothing to open (no work yet): still never silent. + warn!(run_id, error = %e, "Run guard: no draft pull request for the stopped run"); + super::mark_run_stopped_by_guard(state, msg, run_id, &reason, &judged).await; + } + // The work is shipped: a stop that ships ends here, and the pull + // request's own rounds (CI's errors, comments) are free to run. + Ok(_) => { + lift_shipped_stop(state, &msg.team_id, run_id).await; + } } true } @@ -765,9 +992,19 @@ pub async fn end_if_stopped( /// when it had fired. pub async fn settle_open_pr(state: &WorkerState, team_id: &str, run_id: &str) -> bool { flush(state, team_id, run_id).await; - let Some(reason) = load(state, team_id, run_id).await.and_then(|l| l.stopped) else { + let Some(l) = load(state, team_id, run_id).await else { return false; }; + let Some(reason) = l.stopped else { + return false; + }; + // The tasks are done and the work is on its pull request: this stop is + // never a hand-back nor a failure. The run waits on its pull request's + // CI, whose red check with an error starts the next fix round. + if ships_code(&l.stop_code) && lift_shipped_stop(state, team_id, run_id).await { + await_ci_on_pr(state, team_id, run_id, &reason).await; + return true; + } let mut usage = crate::models::TokenUsage::default(); let mut picture = super::stop_judge::Picture::new(super::stop_judge::Kind::Handoff, "run_guard", &reason); @@ -906,6 +1143,37 @@ async fn finish_open_pr(state: &WorkerState, team_id: &str, run_id: &str, reason } } +/// A shipped run goes back to waiting on its pull request's CI, with what is +/// still open as the deferred reason: CI's next result resumes it, and a red +/// check with its error starts a fix round. +async fn await_ci_on_pr(state: &WorkerState, team_id: &str, run_id: &str, reason: &str) { + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET #s = :s, status_run_id = :sri, deferred_reason = :dr, updated_at = :t, \ + current_pass = :s", + ) + .condition_expression(run_status::not_ended("#s")) + .ended_values() + .expression_attribute_names("#s", "status") + .expression_attribute_values(":s", attr_s(run_status::AWAITING_CI)) + .expression_attribute_values( + ":sri", + attr_s(&format!("{}#{run_id}", run_status::AWAITING_CI)), + ) + .expression_attribute_values(":dr", attr_s(common::truncate_str(reason, 500))) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await; + if let Err(e) = res { + warn!(run_id, error = %e, "Run guard: could not put the shipped run back on its CI"); + } +} + /// The run's pull request (number, address), from its record. async fn run_pr(state: &WorkerState, team_id: &str, run_id: &str) -> (u64, String) { let item = state @@ -1137,6 +1405,21 @@ impl Ledger { set_aside } + /// The checks that have given no result yet, on any head: what a step + /// after the work still has to run. + pub fn unrun_checks(&self) -> usize { + [ + self.proof_findings.is_none() && self.proof.head.is_empty(), + self.rules_outcome.is_none(), + self.links_outcome.is_none(), + self.test_outcome.is_none(), + self.habits_outcome.is_none(), + ] + .iter() + .filter(|u| **u) + .count() + } + /// What is still open, for a run the guard stopped. Honest about both: /// what the checks found, and what they didn't get to. pub fn open_findings(&self) -> Vec { @@ -1362,18 +1645,63 @@ mod tests { .await; } + fn target(unrun: usize, open: usize) -> Target { + Target { + owed: false, + unrun, + open: (0..open).map(|i| format!("gap {i}")).collect(), + } + } + + /// After the work, a run goes on while each continuation closes + /// something, however many that takes, and ships at the first stale + /// one past the allowance. #[test] - fn fewer_findings_never_buy_finished_work_more_continuations() { + fn finished_work_goes_on_while_it_converges_and_ships_when_it_stops() { let mut g = GuardState::default(); g.apply(&Progress::WorkDone); - g.apply(&Progress::Findings("proof", 9)); - for (i, open) in [8, 7, 6].into_iter().enumerate() { - g.on_continuation(1.0); - assert!(g.apply(&Progress::Findings("proof", open))); + for (i, (unrun, open)) in [(5, 0), (4, 3), (2, 3), (0, 6), (0, 4), (0, 2), (0, 1)] + .into_iter() + .enumerate() + { + g.on_continuation_to(1.0, &target(unrun, open)); assert_eq!(g.trip(), None, "continuation {i}"); } - g.on_continuation(1.0); - assert_eq!(g.trip(), Some(Trip::ContinuationsAfterWork)); + g.on_continuation_to(1.0, &target(0, 1)); + assert_eq!(g.trip(), None, "one stale continuation is allowed"); + g.on_continuation_to(1.0, &target(0, 2)); + assert_eq!(g.trip(), Some(Trip::Converged)); + assert!(Trip::Converged.ships()); + g.shipped(); + assert_eq!(g.trip(), None, "shipping starts convergence over"); + } + + #[test] + fn nothing_open_and_nothing_to_run_ships_at_once() { + let mut g = GuardState::default(); + g.apply(&Progress::WorkDone); + g.on_continuation_to(0.0, &target(0, 0)); + assert_eq!(g.trip(), Some(Trip::Converged)); + assert!(Trip::Converged + .reason(&g) + .contains("nothing it can act on is open")); + } + + #[test] + fn an_owed_step_is_never_counted() { + let mut g = GuardState::default(); + g.apply(&Progress::WorkDone); + g.on_continuation_to(0.0, &target(0, 3)); + let owed = Target { + owed: true, + ..Default::default() + }; + for _ in 0..20 { + g.on_continuation_to(0.1, &owed); + assert_eq!(g.trip(), None); + } + assert_eq!(g.stale, 0); + assert_eq!(g.after_work, 1); } #[test] @@ -1422,13 +1750,19 @@ mod tests { #[test] fn the_reason_is_plain_and_says_what_to_do() { let g = GuardState { - after_work: 4, + stale: 2, ..Default::default() }; - let why = Trip::ContinuationsAfterWork.reason(&g); - assert!(why.contains("tasks were done"), "{why}"); - assert!(why.contains("continued 4 more times"), "{why}"); + let why = Trip::Converged.reason(&g); + assert!(why.contains("tasks are done"), "{why}"); + assert!( + why.contains("last 2 continuation(s) closed nothing"), + "{why}" + ); assert!(why.contains("Open items"), "{why}"); + assert!(why.contains("fixes what CI reports"), "{why}"); + assert!(!why.contains("handed it to you"), "{why}"); + let why = Trip::Continuations.reason(&GuardState::default()); assert!(why.contains("Push to the branch or comment"), "{why}"); let g = GuardState { spend_usd: 20.5, @@ -1441,14 +1775,14 @@ mod tests { fn stop_codes_are_stable_for_analytics() { assert_eq!( [ - Trip::ContinuationsAfterWork, + Trip::Converged, Trip::Continuations, Trip::Transitions, Trip::Spend ] .map(Trip::code), [ - "continuations_after_work", + "converged_with_open_items", "continuations", "pass_transitions", "spend" From 21f4b3228fb2c1ae35faffe9a03942d71ca5633e Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Wed, 18 Nov 2026 14:10:56 -0500 Subject: [PATCH 2/4] One ticket, one run, whatever starts it Every fresh run takes one atomic claim keyed by the ticket the work is for, not the event that carried it in: an issue CoderHelm opens for a tracker ticket carries a marker and a stored link back to it, so both resolve to the same key and the second trigger starts nothing. A plan task for a ticket a live run already works opens no issue at all. --- docs/incidents/dc_one_run_per_ticket.md | 5 + services/common/src/lib.rs | 3 + services/common/src/one_run.rs | 263 ++++++++++++++++++ .../passes/incidents/dc_one_run_per_ticket.rs | 208 ++++++++++++++ services/worker/src/passes/mod.rs | 16 ++ services/worker/src/passes/one_run.rs | 230 +++++++++++++++ services/worker/src/passes/plan_execute.rs | 109 +++++++- 7 files changed, 832 insertions(+), 2 deletions(-) create mode 100644 docs/incidents/dc_one_run_per_ticket.md create mode 100644 services/common/src/one_run.rs create mode 100644 services/worker/src/passes/incidents/dc_one_run_per_ticket.rs create mode 100644 services/worker/src/passes/one_run.rs diff --git a/docs/incidents/dc_one_run_per_ticket.md b/docs/incidents/dc_one_run_per_ticket.md new file mode 100644 index 000000000..9966142d2 --- /dev/null +++ b/docs/incidents/dc_one_run_per_ticket.md @@ -0,0 +1,5 @@ +# dc. `dc_one_run_per_ticket` + +**What happened:** A tracker ticket started a run. Seconds later a person approved a plan written for that same ticket, and the plan's task opened a GitHub issue for it, labelled for CoderHelm. The issue started a second run. The two runs carried different ticket ids (the tracker key and `GH-`), so every guard keyed by ticket id saw two tickets. One ticket got two runs, two branches and two pull requests, and both runs spent their budget on the same change. + +**The guarantee:** Every fresh run takes one claim on its ticket's canonical key before it writes anything, at the run start that every trigger goes through (`common::one_run`, `passes::one_run::claim`). The key is the ticket the run is for, not the event that carried it in. An issue CoderHelm opens for another ticket names that ticket twice: in a marker in its body and in the stored link from the issue to its plan task. Its run therefore resolves to the ticket's own key. A second trigger for a ticket that a live run holds starts nothing, from any source and in either order, and the live run's page says the ticket arrived again. A run that has ended hands the claim to the ticket's next run. A plan task written for a ticket that a live run already works opens no issue: it is linked to that ticket and run. diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index bdfcb1d20..87843a476 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -110,6 +110,9 @@ pub mod live; /// Log findings and the fix runs started from them. pub mod log_findings; pub mod log_incident; +/// One ticket, one run: the canonical ticket key and the claim every run +/// start takes on it. +pub mod one_run; /// Reachability read from the code: imports, calls, lockfile parents. pub mod reachability; /// One repo's reviewer settings: the page's view and the saved item. diff --git a/services/common/src/one_run.rs b/services/common/src/one_run.rs new file mode 100644 index 000000000..446dad744 --- /dev/null +++ b/services/common/src/one_run.rs @@ -0,0 +1,263 @@ +//! One ticket, one run. +//! +//! A ticket reached CoderHelm twice within seconds: once from its tracker, +//! and once as a GitHub issue that CoderHelm itself opened for it from a plan +//! a person approved. The two runs carried different ids (the tracker's key +//! and `GH-`), so the per-id guards saw two tickets, and the same work got +//! two runs and two pull requests. +//! +//! Every run of a ticket now starts through one claim, keyed by the ticket's +//! canonical key ([`canonical`]): the ticket it is for, whatever carried it +//! in. An issue CoderHelm opens for a ticket names that ticket in a marker in +//! its body ([`marker`]) and in the stored link from the issue to its plan +//! task, so its run resolves to the same key as the ticket's own. The claim +//! is one conditional write ([`claim_sk`]): a second trigger finds it held by +//! a live run ([`decide`]) and is dropped in favour of that run, whatever the +//! source, whatever the order. + +use crate::messages::TicketSource; + +const MARKER_OPEN: &str = ""; + +/// The line an issue CoderHelm opens for another ticket carries, so its run +/// is that ticket's run. +pub fn marker(key: &str) -> String { + format!("{MARKER_OPEN}{}{MARKER_CLOSE}", key.trim()) +} + +/// Whether `s` is a tracker key: letters, then digits or letters, a dash and +/// a number (`ABC-12`, `GH-41`). +pub fn is_key(s: &str) -> bool { + let Some((head, num)) = s.split_once('-') else { + return false; + }; + let mut chars = head.chars(); + chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') + && !num.is_empty() + && num.chars().all(|c| c.is_ascii_digit()) +} + +/// The ticket a body's marker names, uppercased. +pub fn marked_ticket(body: &str) -> Option { + let at = body.find(MARKER_OPEN)?; + let rest = &body[at + MARKER_OPEN.len()..]; + let key = rest.split(MARKER_CLOSE).next()?.trim(); + is_key(key).then(|| key.to_ascii_uppercase()) +} + +/// The ticket a plan task was written for: a marker in its description, or +/// the tracker key its title leads with (`ABC-12: Title`, `[ABC-12] Title`, +/// `ABC-12 Title`), the way a plan made from a ticket is titled. +pub fn named_ticket(title: &str, description: &str) -> Option { + if let Some(k) = marked_ticket(description) { + return Some(k); + } + let t = title.trim().trim_start_matches('['); + let word: String = t + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') + .collect(); + let after = t[word.len()..].chars().next(); + let ends = matches!(after, None | Some(':' | ']' | ' ' | '\u{a0}')); + (is_key(&word) && ends).then(|| word.to_ascii_uppercase()) +} + +/// The key of a ticket named by `key`, seen from `repo` (`owner/name`): a +/// GitHub issue number is only unique within its repository. +fn key_in(key: &str, repo: &str) -> String { + let key = key.trim().to_ascii_uppercase(); + match key.strip_prefix("GH-") { + Some(n) if !repo.is_empty() => format!("github:{}#{n}", repo.to_ascii_lowercase()), + _ => format!("ticket:{key}"), + } +} + +/// The canonical key of the ticket a run is for: the ticket a marker or a +/// stored link (`linked`) names, else the ticket that carried it in. Two +/// triggers for one ticket get one key, from any source. +pub fn canonical( + source: &TicketSource, + ticket_id: &str, + repo: &str, + body: &str, + linked: Option<&str>, +) -> String { + if let Some(k) = linked + .map(str::trim) + .filter(|k| is_key(k)) + .map(str::to_string) + .or_else(|| marked_ticket(body)) + { + return key_in(&k, repo); + } + match source { + TicketSource::Alert => format!("alert:{}", ticket_id.trim()), + _ if is_key(ticket_id.trim()) => key_in(ticket_id, repo), + _ => format!("ticket:{}", ticket_id.trim()), + } +} + +/// The claim's sort key on the teams table. +pub fn claim_sk(canonical: &str) -> String { + format!("TICKET_RUN#{canonical}") +} + +/// A claim not yet backed by its run's record is a run still starting: it +/// holds for this long. +pub const STARTING_SECS: i64 = 300; + +/// Who holds a ticket's claim, as the run table shows them. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Holder { + pub run_id: String, + /// The holder run's status; `None` when it has no record yet. + pub status: Option, + /// Hours since the holder run's record last changed. + pub idle_hours: i64, + /// Seconds since the claim was taken. + pub claim_secs: i64, +} + +impl Holder { + /// Whether the holder is still working the ticket: the same bounds as + /// the run start's duplicate check, so a run that died can't hold a + /// ticket forever. + pub fn live(&self) -> bool { + match self.status.as_deref() { + None => self.claim_secs < STARTING_SECS, + Some("running" | "queued") => self.idle_hours < 2, + Some("awaiting_ci") => self.idle_hours < 26, + Some(_) => false, + } + } +} + +/// What a run starting does about a ticket's claim. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Claim { + /// Nobody held it: this run took it. + Take, + /// A live run holds it: this trigger is that run's ticket, and no + /// second run starts. + Held(String), + /// A run that ended holds it: this run takes it over from that run id. + TakeOver(String), +} + +/// The decision for run `me` given the claim's holder. +pub fn decide(me: &str, holder: Option<&Holder>) -> Claim { + match holder { + None => Claim::Take, + Some(h) if h.run_id == me => Claim::Take, + Some(h) if h.live() => Claim::Held(h.run_id.clone()), + Some(h) => Claim::TakeOver(h.run_id.clone()), + } +} + +/// The note on the live run when a second trigger for its ticket arrives. +pub fn held_note(ticket_id: &str, source: &TicketSource) -> String { + let from = match source { + TicketSource::Github => "a GitHub issue", + TicketSource::Jira => "the tracker", + TicketSource::Alert => "an alert", + }; + format!( + "The same ticket arrived again from {from} (`{ticket_id}`): this run is its one run, so no \ + second run or pull request was started." + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keys_and_markers() { + assert!(is_key("ABC-12") && is_key("GH-41") && is_key("abc-1")); + assert!(!is_key("ABC") && !is_key("-12") && !is_key("ABC-") && !is_key("1A-2")); + let body = format!("Do it.\n\n{}", marker("abc-12")); + assert_eq!(marked_ticket(&body).as_deref(), Some("ABC-12")); + assert_eq!(marked_ticket("no marker"), None); + } + + #[test] + fn a_plan_task_names_the_ticket_its_title_leads_with() { + for t in ["ABC-12: Make it work", "[ABC-12] Make it", "ABC-12 make it"] { + assert_eq!(named_ticket(t, "").as_deref(), Some("ABC-12"), "{t}"); + } + assert_eq!(named_ticket("Make ABC-12 work", ""), None); + assert_eq!(named_ticket("ABC-12x: no", ""), None); + assert_eq!( + named_ticket("Title", &marker("XY-3")).as_deref(), + Some("XY-3") + ); + } + + #[test] + fn one_key_for_one_ticket_from_any_source() { + let jira = canonical(&TicketSource::Jira, "ABC-12", "o/r", "", None); + let issue = canonical( + &TicketSource::Github, + "GH-7", + "o/r", + &marker("ABC-12"), + None, + ); + let linked = canonical(&TicketSource::Github, "GH-7", "o/r", "", Some("abc-12")); + assert_eq!(jira, "ticket:ABC-12"); + assert_eq!(issue, jira); + assert_eq!(linked, jira); + // GitHub numbers are per repository. + assert_ne!( + canonical(&TicketSource::Github, "GH-7", "o/a", "", None), + canonical(&TicketSource::Github, "GH-7", "o/b", "", None) + ); + assert_eq!( + canonical(&TicketSource::Github, "GH-7", "O/R", "", None), + "github:o/r#7" + ); + assert_eq!( + canonical(&TicketSource::Alert, "alarm-x", "o/r", "", None), + "alert:alarm-x" + ); + } + + #[test] + fn a_live_holder_keeps_the_ticket_and_an_ended_one_hands_it_over() { + let h = |status: Option<&str>, idle_hours, claim_secs| Holder { + run_id: "R1".into(), + status: status.map(str::to_string), + idle_hours, + claim_secs, + }; + assert_eq!(decide("R2", None), Claim::Take); + assert_eq!(decide("R1", Some(&h(Some("running"), 0, 9))), Claim::Take); + for live in [ + h(Some("running"), 1, 9), + h(Some("queued"), 0, 9), + h(Some("awaiting_ci"), 25, 9), + h(None, 0, 30), + ] { + assert_eq!( + decide("R2", Some(&live)), + Claim::Held("R1".into()), + "{live:?}" + ); + } + for ended in [ + h(Some("failed"), 0, 9), + h(Some("completed"), 0, 9), + h(Some("running"), 3, 9), + h(Some("awaiting_ci"), 27, 9), + h(None, 0, STARTING_SECS + 1), + ] { + assert_eq!( + decide("R2", Some(&ended)), + Claim::TakeOver("R1".into()), + "{ended:?}" + ); + } + } +} diff --git a/services/worker/src/passes/incidents/dc_one_run_per_ticket.rs b/services/worker/src/passes/incidents/dc_one_run_per_ticket.rs new file mode 100644 index 000000000..c50f7d0d6 --- /dev/null +++ b/services/worker/src/passes/incidents/dc_one_run_per_ticket.rs @@ -0,0 +1,208 @@ +//! dc. A person approved a plan written for a tracker ticket that already +//! had a run starting. The plan's task opened a GitHub issue for the same +//! work, labelled for CoderHelm; the issue's run carried `GH-` while the +//! tracker's run carried the tracker key, so the guards keyed by ticket id +//! saw two tickets. One ticket got two runs and two pull requests, and both +//! runs spent their budgets on the same change. +//! +//! Guarantee: every fresh run takes one claim on the ticket's canonical key +//! before it writes anything, at the run start every trigger goes through. +//! An issue CoderHelm opens for another ticket names that ticket (a marker +//! in its body, and the stored link from the issue to its plan task), so it +//! resolves to the same key. A second trigger for a ticket a live run holds +//! starts nothing, whatever its source or order; and a plan task for a +//! ticket a live run already works opens no issue at all. + +use std::collections::HashMap; + +use common::messages::TicketSource; +use common::one_run::{self, Claim, Holder}; + +use super::fixture::*; +use crate::models::TicketMessage; + +const KEY: &str = "WEB-77"; +const TRACKER_RUN: &str = "01JRUNTRACKER0000000000000"; +const ISSUE_RUN: &str = "01JRUNISSUE000000000000000"; +const ISSUE: u64 = 41; + +/// The tracker's ticket, as its webhook sends it. +fn tracker_ticket() -> TicketMessage { + TicketMessage { + source: TicketSource::Jira, + ticket_id: KEY.into(), + title: "Make the accordion block work without JavaScript".into(), + body: "Every answer is in the server HTML.".into(), + repo_owner: OWNER.into(), + repo_name: REPO.into(), + ..Default::default() + } +} + +/// The issue the plan task opens, as the GitHub webhook turns it into a +/// ticket: the plan is titled after the tracker ticket, the issue body is +/// what `plan_execute` writes, the sender is CoderHelm's own bot. +fn issue_ticket(body_edited_away: bool) -> TicketMessage { + let title = format!("{KEY}: Make the accordion block work without JavaScript"); + let description = "Every answer is in the server HTML."; + let named = one_run::named_ticket(&title, description); + assert_eq!(named.as_deref(), Some(KEY), "the task names its ticket"); + let body = + crate::passes::plan_execute::with_ticket_marker(description.to_string(), named.as_deref()); + TicketMessage { + source: TicketSource::Github, + ticket_id: format!("GH-{ISSUE}"), + title, + body: if body_edited_away { + description.to_string() + } else { + body + }, + repo_owner: OWNER.into(), + repo_name: REPO.into(), + issue_number: ISSUE, + sender: "coderhelm[bot]".into(), + ..Default::default() + } +} + +/// The claim table, with DynamoDB's conditional write: new, or the same +/// run, or over the run id the writer read. +#[derive(Default)] +struct Claims { + rows: HashMap, +} + +impl Claims { + fn write(&mut self, sk: &str, me: &str, from: Option<&str>) -> bool { + let ok = match (self.rows.get(sk), from) { + (None, None) => true, + (Some(held), None) => held == me, + (Some(held), Some(old)) => held == old || held == me, + (None, Some(_)) => false, + }; + if ok { + self.rows.insert(sk.into(), me.into()); + } + ok + } + + /// The holder, with its run's status as the run table has it. + fn holder(&self, sk: &str, runs: &HashMap<&str, &str>) -> Option { + self.rows.get(sk).map(|run| Holder { + run_id: run.clone(), + status: runs.get(run.as_str()).map(|s| s.to_string()), + idle_hours: 0, + claim_secs: 5, + }) + } +} + +/// `one_run::claim` as the worker runs it, on the fake table: `Ok` when +/// the run may start, `Err(live run)` when it must not. +fn start( + claims: &mut Claims, + runs: &HashMap<&str, &str>, + msg: &TicketMessage, + me: &str, + linked: Option<&str>, +) -> Result<(), String> { + let key = one_run::canonical( + &msg.source, + &msg.ticket_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + &msg.body, + linked, + ); + let sk = one_run::claim_sk(&key); + let mut from: Option = None; + for _ in 0..3 { + if claims.write(&sk, me, from.as_deref()) { + return Ok(()); + } + match one_run::decide(me, claims.holder(&sk, runs).as_ref()) { + Claim::Take => from = None, + Claim::TakeOver(old) => from = Some(old), + Claim::Held(live) => return Err(live), + } + } + Ok(()) +} + +#[test] +fn the_issue_coderhelm_opened_for_a_ticket_starts_no_second_run() { + let mut claims = Claims::default(); + let runs: HashMap<&str, &str> = HashMap::from([(TRACKER_RUN, "running")]); + // The tracker's run starts first and holds the ticket. + assert_eq!( + start(&mut claims, &runs, &tracker_ticket(), TRACKER_RUN, None), + Ok(()) + ); + // The issue's run, a second later, resolves to the same ticket. + let issue = issue_ticket(false); + let end = start(&mut claims, &runs, &issue, ISSUE_RUN, None); + assert_eq!(end, Err(TRACKER_RUN.to_string()), "one ticket, one run"); + // Its body edited by a person: the stored link still names the ticket. + let edited = issue_ticket(true); + assert_eq!( + start(&mut claims, &runs, &edited, ISSUE_RUN, Some(KEY)), + Err(TRACKER_RUN.to_string()) + ); + // The live run's page says the ticket arrived again; the old ending + // (a second run and a second pull request) never happens. + let note = one_run::held_note(&issue.ticket_id, &issue.source); + assert!(note.contains("no second run or pull request"), "{note}"); +} + +#[test] +fn the_order_does_not_matter_and_an_ended_run_hands_the_ticket_on() { + let mut claims = Claims::default(); + let mut runs: HashMap<&str, &str> = HashMap::from([(ISSUE_RUN, "awaiting_ci")]); + // The issue's run wins the race this time: the tracker's is the second. + assert_eq!( + start(&mut claims, &runs, &issue_ticket(false), ISSUE_RUN, None), + Ok(()) + ); + assert_eq!( + start(&mut claims, &runs, &tracker_ticket(), TRACKER_RUN, None), + Err(ISSUE_RUN.to_string()) + ); + // Once that run has ended, the ticket's next run takes the claim over. + runs.insert(ISSUE_RUN, "failed"); + assert_eq!( + start(&mut claims, &runs, &tracker_ticket(), TRACKER_RUN, None), + Ok(()) + ); + // Another ticket is never held by this one. + let mut other = tracker_ticket(); + other.ticket_id = "WEB-78".into(); + assert_eq!(start(&mut claims, &runs, &other, "01JOTHER", None), Ok(())); +} + +#[test] +fn every_trigger_goes_through_the_claim_and_the_plan_opens_no_duplicate_issue() { + // The run start: every fresh run claims its ticket before its record. + let src = include_str!("../mod.rs"); + let f = &src[src.find("\npub async fn orchestrate_ticket(").unwrap()..]; + let f = &f[..f.find("\n}\n").unwrap()]; + let claim = f + .find("one_run::claim(state, &msg, &run_id)") + .expect("the run start takes the ticket's claim"); + let record = f.find("create_run_record(state, &msg, &run_id").unwrap(); + assert!(claim < record, "the claim comes before anything is written"); + // The claim resolves a CoderHelm issue through its stored link. + let one = include_str!("../one_run.rs"); + assert!(one.contains("\"source_ticket\"")); + // The plan: each issue-opening path names its ticket and skips a ticket + // a live run already works. + let plan = include_str!("../plan_execute.rs"); + assert_eq!(plan.matches(".create_issue(").count(), 2); + for at in plan.match_indices(".create_issue(").map(|(i, _)| i) { + let before = &plan[..at]; + let near = &before[before.len().saturating_sub(1800)..]; + assert!(near.contains("one_run::named_ticket(")); + assert!(near.contains("one_run::live_run(")); + assert!(near.contains("with_ticket_marker(")); + } + assert!(plan.contains("put.item(\"source_ticket\"")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 30d47a2c4..657797bb9 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1335,6 +1335,7 @@ pub mod model_check; #[cfg(test)] mod model_route_eval; pub mod onboard; +pub mod one_run; pub mod open_pr_choice; pub mod ops_tools; pub mod outcome; @@ -1537,6 +1538,21 @@ pub async fn orchestrate_ticket( ); return Ok(()); } + // One ticket, one run, from any source: the claim on the ticket's + // canonical key (`common::one_run`). A second trigger for a ticket a live + // run holds (its tracker and an issue CoderHelm opened for it) starts + // nothing; the live run's page says it arrived. + if !is_continuation { + if let Err(live) = one_run::claim(state, &msg, &run_id).await { + info!( + run_id, + live = %live, + ticket_id = %msg.ticket_id, + "Skipping duplicate: a live run holds this ticket" + ); + return Ok(()); + } + } if is_continuation { // Reuse the existing run record — but ONLY if it isn't cancelled. This diff --git a/services/worker/src/passes/one_run.rs b/services/worker/src/passes/one_run.rs new file mode 100644 index 000000000..6c4c67957 --- /dev/null +++ b/services/worker/src/passes/one_run.rs @@ -0,0 +1,230 @@ +//! The claim every fresh run of a ticket takes before it writes anything +//! (`common::one_run`): one run per ticket, whatever carried it in. + +use aws_sdk_dynamodb::types::AttributeValue; +use common::one_run::{self, Claim, Holder}; +use tracing::{info, warn}; + +use crate::models::TicketMessage; +use crate::WorkerState; + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +/// The ticket a GitHub issue was opened for, from the stored link from the +/// issue to the plan task that opened it (`plan_execute`). +async fn linked_ticket(state: &WorkerState, msg: &TicketMessage) -> Option { + if msg.issue_number == 0 || state.config.settings_table_name.is_empty() { + return None; + } + let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", s(&msg.team_id)) + .key( + "sk", + s(&common::plan_dependents::github_link_sk( + &repo, + msg.issue_number, + )), + ) + .projection_expression("source_ticket") + .send() + .await + .ok()? + .item?; + item.get("source_ticket") + .and_then(|v| v.as_s().ok()) + .filter(|k| !k.is_empty()) + .cloned() +} + +/// The canonical key of the ticket `msg` is for. +pub async fn ticket_key(state: &WorkerState, msg: &TicketMessage) -> String { + let linked = match msg.source { + common::messages::TicketSource::Github => linked_ticket(state, msg).await, + _ => None, + }; + one_run::canonical( + &msg.source, + &msg.ticket_id, + &format!("{}/{}", msg.repo_owner, msg.repo_name), + &msg.body, + linked.as_deref(), + ) +} + +async fn holder(state: &WorkerState, team_id: &str, sk: &str) -> Option { + let item = state + .dynamo + .get_item() + .table_name(&state.config.teams_table_name) + .key("team_id", s(team_id)) + .key("sk", s(sk)) + .send() + .await + .ok()? + .item?; + let get = |i: &std::collections::HashMap, k: &str| { + i.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let run_id = get(&item, "run_id"); + let now = chrono::Utc::now(); + let age = |t: &str| { + chrono::DateTime::parse_from_rfc3339(t) + .ok() + .map(|t| now.signed_duration_since(t)) + }; + let claim_secs = age(&get(&item, "claimed_at")).map_or(i64::MAX, |d| d.num_seconds()); + let run = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", s(team_id)) + .key("run_id", s(&run_id)) + .projection_expression("#s, updated_at") + .expression_attribute_names("#s", "status") + .send() + .await + .ok() + .and_then(|r| r.item); + Some(Holder { + status: run.as_ref().map(|r| get(r, "status")), + idle_hours: run + .as_ref() + .and_then(|r| age(&get(r, "updated_at"))) + .map_or(i64::MAX, |d| d.num_hours()), + claim_secs, + run_id, + }) +} + +/// Writes the claim: new, or over `from` (a run that ended). False when +/// another writer got there first. +async fn write( + state: &WorkerState, + team_id: &str, + sk: &str, + run_id: &str, + from: Option<&str>, +) -> Result { + let put = state + .dynamo + .put_item() + .table_name(&state.config.teams_table_name) + .item("team_id", s(team_id)) + .item("sk", s(sk)) + .item("run_id", s(run_id)) + .item("claimed_at", s(&chrono::Utc::now().to_rfc3339())); + let put = match from { + None => put.condition_expression("attribute_not_exists(sk) OR run_id = :me"), + Some(old) => put + .condition_expression("run_id = :old OR run_id = :me") + .expression_attribute_values(":old", s(old)), + } + .expression_attribute_values(":me", s(run_id)); + match put.send().await { + Ok(_) => Ok(true), + Err(e) + if e.as_service_error() + .is_some_and(|x| x.is_conditional_check_failed_exception()) => + { + Ok(false) + } + Err(e) => Err(aws_sdk_dynamodb::error::DisplayErrorContext(&e).to_string()), + } +} + +/// Takes the ticket's claim for fresh run `run_id`. `Err(run)` when a live +/// run holds the ticket: this trigger starts nothing, and that run's page +/// says the ticket arrived again. Fails open on an unexpected error, like +/// the ticket lock. +pub async fn claim(state: &WorkerState, msg: &TicketMessage, run_id: &str) -> Result<(), String> { + if state.config.teams_table_name.is_empty() { + return Ok(()); + } + let key = ticket_key(state, msg).await; + let sk = one_run::claim_sk(&key); + let mut from: Option = None; + // A lost race is read again once; past that the live holder decides. + for _ in 0..3 { + match write(state, &msg.team_id, &sk, run_id, from.as_deref()).await { + Ok(true) => { + info!(run_id, ticket = %key, "The run holds its ticket"); + return Ok(()); + } + Ok(false) => {} + Err(e) => { + warn!(run_id, ticket = %key, error = %e, "Ticket claim failed: allowing the run"); + return Ok(()); + } + } + let h = holder(state, &msg.team_id, &sk).await; + match one_run::decide(run_id, h.as_ref()) { + Claim::Take => from = None, + Claim::TakeOver(old) => from = Some(old), + Claim::Held(live) => { + warn!(run_id, live = %live, ticket = %key, ticket_id = %msg.ticket_id, "A live run holds this ticket: no second run"); + super::add_progress_note( + state, + &msg.team_id, + &live, + &one_run::held_note(&msg.ticket_id, &msg.source), + ) + .await; + return Err(live); + } + } + } + warn!(run_id, ticket = %key, "Ticket claim kept changing hands: allowing the run"); + Ok(()) +} + +/// The live run that holds the ticket named `key` (seen from `repo`), if any: +/// its claim, or for a run that started before claims were kept, a live run +/// carrying that ticket id. +pub async fn live_run(state: &WorkerState, team_id: &str, key: &str, repo: &str) -> Option { + let canonical = one_run::canonical( + &common::messages::TicketSource::Jira, + key, + repo, + "", + Some(key), + ); + if let Some(h) = holder(state, team_id, &one_run::claim_sk(&canonical)).await { + if h.live() { + return Some(h.run_id); + } + } + let out = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .index_name("ticket-index") + .key_condition_expression("team_id = :tid AND ticket_id = :ticket") + .expression_attribute_values(":tid", s(team_id)) + .expression_attribute_values(":ticket", s(&key.to_ascii_uppercase())) + .send() + .await + .ok()?; + let now = chrono::Utc::now(); + out.items().iter().find_map(|item| { + let get = |k: &str| item.get(k).and_then(|v| v.as_s().ok()).cloned(); + let idle_hours = get("updated_at") + .and_then(|t| chrono::DateTime::parse_from_rfc3339(&t).ok()) + .map_or(i64::MAX, |t| now.signed_duration_since(t).num_hours()); + let h = Holder { + run_id: get("run_id")?, + status: get("status"), + idle_hours, + claim_secs: i64::MAX, + }; + h.live().then_some(h.run_id) + }) +} diff --git a/services/worker/src/passes/plan_execute.rs b/services/worker/src/passes/plan_execute.rs index 0361f1943..115e1eac0 100644 --- a/services/worker/src/passes/plan_execute.rs +++ b/services/worker/src/passes/plan_execute.rs @@ -138,6 +138,7 @@ pub async fn run( &msg.plan_id, task_id, PlanTicket::Jira(ticket_key), + None, ) .await; let ticket_url = if let Some(ref site) = jira_site_url { @@ -183,8 +184,31 @@ pub async fn run( continue; } + // A task written for a ticket that already has a live run is + // that run's work: no issue of its own, so no second run. + let named = common::one_run::named_ticket(&task.title, &task.description); + if let Some(key) = named.as_deref() { + if let Some(live) = + super::one_run::live_run(state, &msg.team_id, key, task_repo).await + { + link_to_live_run( + state, + &msg.team_id, + &msg.plan_id, + task_id, + key, + task_repo, + &live, + ) + .await?; + continue; + } + } let (owner, repo) = split_repo(task_repo); - let issue_body = format_issue_body(&task.description, &task.acceptance_criteria); + let issue_body = with_ticket_marker( + format_issue_body(&task.description, &task.acceptance_criteria), + named.as_deref(), + ); match github .create_issue(owner, repo, &task.title, &issue_body) @@ -202,6 +226,7 @@ pub async fn run( repo: task_repo, issue_number, }, + named.as_deref(), ) .await; // Label the issue FIRST to trigger the ticket pipeline @@ -331,6 +356,55 @@ impl PlanTicket<'_> { } } +/// An issue body with the marker naming the ticket it is opened for, so +/// its run resolves to that ticket's key (`common::one_run`). +pub(crate) fn with_ticket_marker(body: String, ticket: Option<&str>) -> String { + match ticket { + Some(k) if common::one_run::marked_ticket(&body).is_none() => { + format!("{}\n\n{}", body.trim_end(), common::one_run::marker(k)) + } + _ => body, + } +} + +/// A plan task whose ticket a live run already works: the task is linked to +/// that ticket and done, and the live run's page says so. No issue opens. +async fn link_to_live_run( + state: &WorkerState, + team_id: &str, + plan_id: &str, + task_id: &str, + key: &str, + repo: &str, + live: &str, +) -> Result<(), Box> { + let number = key + .to_ascii_uppercase() + .strip_prefix("GH-") + .and_then(|n| n.parse::().ok()); + let ticket = match number { + Some(issue_number) => PlanTicket::Github { repo, issue_number }, + None => PlanTicket::Jira(key), + }; + link_ticket_to_plan(state, team_id, plan_id, task_id, ticket, None).await; + update_task_with_jira(state, team_id, plan_id, task_id, key, "").await?; + info!( + task_id, + key, live, "Plan task's ticket already has a live run: linked, no issue" + ); + super::add_progress_note( + state, + team_id, + live, + &format!( + "A plan task was written for this ticket (`{key}`): it is this run's work, so \ + CoderHelm opened no second issue and started no second run." + ), + ) + .await; + Ok(()) +} + /// The plan a run's ticket came from: `(plan_id, plan_title, plan_by)`. pub(crate) async fn plan_of_ticket( state: &WorkerState, @@ -367,6 +441,7 @@ async fn link_ticket_to_plan( plan_id: &str, task_id: &str, ticket: PlanTicket<'_>, + source: Option<&str>, ) { if matches!(ticket, PlanTicket::Jira(k) if k.is_empty() || k == "UNKNOWN") { return; @@ -404,6 +479,11 @@ async fn link_ticket_to_plan( if !by.is_empty() { put = put.item("plan_by", AttributeValue::S(by.clone())); } + // The ticket this one was opened for: its run is that ticket's run + // (`common::one_run`). + if let Some(src) = source.filter(|k| common::one_run::is_key(k)) { + put = put.item("source_ticket", AttributeValue::S(src.to_ascii_uppercase())); + } if let Err(e) = put.send().await { tracing::warn!(team_id, plan_id, task_id, error = %e, "Could not link the ticket to its plan"); return; @@ -809,6 +889,7 @@ pub async fn continue_tasks( &msg.plan_id, task_id, PlanTicket::Jira(ticket_key), + None, ) .await; let ticket_url = if let Some(ref site) = jira_site_url { @@ -850,8 +931,31 @@ pub async fn continue_tasks( continue; } + // A task written for a ticket that already has a live run is + // that run's work: no issue of its own, so no second run. + let named = common::one_run::named_ticket(&task.title, &task.description); + if let Some(key) = named.as_deref() { + if let Some(live) = + super::one_run::live_run(state, &msg.team_id, key, task_repo).await + { + link_to_live_run( + state, + &msg.team_id, + &msg.plan_id, + task_id, + key, + task_repo, + &live, + ) + .await?; + continue; + } + } let (owner, repo) = split_repo(task_repo); - let issue_body = format_issue_body(&task.description, &task.acceptance_criteria); + let issue_body = with_ticket_marker( + format_issue_body(&task.description, &task.acceptance_criteria), + named.as_deref(), + ); match github .create_issue(owner, repo, &task.title, &issue_body) @@ -869,6 +973,7 @@ pub async fn continue_tasks( repo: task_repo, issue_number, }, + named.as_deref(), ) .await; if let Err(e) = github From 98d0ed5d8f403d5fc64dbf06309f464535f2b473 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Wed, 18 Nov 2026 14:12:01 -0500 Subject: [PATCH 3/4] Prove a ticket's criterion on the page the preview's server sends A criterion about what the server sends (its HTML, the page source, the page with JavaScript off) is checked by fetching the preview and the base deployment and judging each, before the pull request is done; a criterion not shown on the preview goes back to the coder. A run whose ticket text names no criteria proves the plan's criteria map instead of nothing. --- docs/incidents/dd_criterion_on_the_preview.md | 5 + services/common/src/e2e_proof.rs | 251 +++++++++++++ services/worker/src/passes/ci_repro.rs | 44 ++- services/worker/src/passes/e2e_proof.rs | 339 +++++++++++++++++- .../incidents/cp_criteria_proven_both_ways.rs | 1 + .../incidents/dd_criterion_on_the_preview.rs | 252 +++++++++++++ 6 files changed, 871 insertions(+), 21 deletions(-) create mode 100644 docs/incidents/dd_criterion_on_the_preview.md create mode 100644 services/worker/src/passes/incidents/dd_criterion_on_the_preview.rs diff --git a/docs/incidents/dd_criterion_on_the_preview.md b/docs/incidents/dd_criterion_on_the_preview.md new file mode 100644 index 000000000..a96256290 --- /dev/null +++ b/docs/incidents/dd_criterion_on_the_preview.md @@ -0,0 +1,5 @@ +# dd. `dd_criterion_on_the_preview` + +**What happened:** A ticket asked that a page's answers be in the HTML the server sends, so they show with scripts turned off and crawlers read them. The run rewrote the block as markup that needs no script, wrote unit tests that render the component on its own, and pushed. Nothing it ran fetched the preview's page as the server sends it. The page loads the block on the client only, so the served HTML still had none of the answers, and the preview's own check found it after the push ("the text is not in the server HTML"). The run that opened that pull request had started from an issue with an empty body, so the two-way proof had no criterion to prove, and the ready decision read "nothing to prove". + +**The guarantee:** The criteria to prove come from the ticket, else from the plan's criteria map (`common::e2e_proof::criteria_or_map`), so an empty ticket body never means nothing to prove. A criterion about what the server sends (the page source, the page with scripts off, what a crawler reads: `Criterion::about_served`) is also proven on the served page itself. CoderHelm fetches the criterion's page as the server sends it, on the preview and on staging, with a plain request and no script run (`e2e_proof::served_legs`, through `web_check::fetch_page`), and judges each side against the criterion. Not shown on the preview is coder work whatever the browser test says: it goes back as a fix round and the ready decision waits for it (`common::e2e_proof::outcome`, `standing_of`). Shown on the preview and missing on staging is proven. A side that couldn't be fetched or judged is labelled unverified with why, never a pass. diff --git a/services/common/src/e2e_proof.rs b/services/common/src/e2e_proof.rs index 3c04311a6..fe14aa1ba 100644 --- a/services/common/src/e2e_proof.rs +++ b/services/common/src/e2e_proof.rs @@ -73,6 +73,89 @@ impl Criterion { pub fn needs_e2e(&self) -> bool { self.visible || self.page.is_some() } + + /// Whether it is about what the server sends, before any script runs + /// in the browser: the page's source, its server HTML, the page with + /// scripts turned off, what a crawler reads. A browser test runs the + /// page's scripts and can pass while the server sends none of it, so + /// such a criterion is also proven on the served page itself + /// ([`Served`]). + pub fn about_served(&self) -> bool { + let t = self.text.to_ascii_lowercase(); + SERVED_WORDS.iter().any(|w| t.contains(w)) + } +} + +/// Words that say a criterion is about the served page ([`Criterion::about_served`]). +const SERVED_WORDS: &[&str] = &[ + "server html", + "server-rendered", + "server rendered", + "server-side render", + "server side render", + "rendered on the server", + "page source", + "view source", + "view-source", + "raw html", + "initial html", + "html response", + "curl", + "wget", + "without javascript", + "without js", + "javascript off", + "javascript turned off", + "javascript disabled", + "javascript is off", + "javascript is disabled", + "js off", + "js disabled", + "js turned off", + "no-js", + "no javascript", + "noscript", + "crawler", + "search engine", + "seo", + "json-ld", + "structured data", +]; + +/// The criteria to prove: the ticket's own ([`criteria`]), else the lines +/// of the plan's criteria map. A run whose ticket text gives no criteria +/// (an empty issue body, a ticket whose criteria only the plan wrote down) +/// is still proven on what the plan said it would do, never waved through +/// with nothing to prove. +pub fn criteria_or_map( + title: &str, + body: &str, + acceptance: &[String], + map: &[MapLine], +) -> Vec { + let from_ticket = criteria(title, body, acceptance); + if from_ticket.iter().any(Criterion::needs_e2e) { + return from_ticket; + } + let from_map: Vec = map + .iter() + .filter(|m| !m.criterion.trim().is_empty()) + .map(|m| { + let page = Some(m.page.trim()) + .filter(|p| !p.is_empty()) + .map(|p| pages(p).into_iter().next().unwrap_or_else(|| p.to_string())); + Criterion { + text: m.criterion.trim().to_string(), + visible: page.is_some() || is_visible(&m.criterion), + page, + } + }) + .collect(); + if from_map.is_empty() { + from_ticket + } else { + from_map + } } /// Section names plain ticket text uses without any mark. @@ -470,6 +553,167 @@ pub struct Proof { pub test: String, /// The two runs: `base` on staging, `change` on the preview. pub record: Record, + /// The criterion's page as the server sends it, no script run: on + /// staging (`served_base`) and on the preview (`served_change`), for a + /// criterion about the served page ([`Criterion::about_served`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub served_base: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub served_change: Option, +} + +/// One fetch of a criterion's page as the server sends it (a plain GET, no +/// cookies, no script run), and what the judgment read in it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Served { + /// The address fetched. + #[serde(default)] + pub url: String, + /// The fetch got an answer. + #[serde(default)] + pub fetched: bool, + #[serde(default)] + pub status: u16, + /// Whether the served page shows what the criterion asks: `None` when + /// nothing could judge it. + #[serde(default)] + pub shown: Option, + /// What in the served page settles it, quoted, or what is missing. + #[serde(default)] + pub quote: String, + /// Why it wasn't fetched or judged. + #[serde(default)] + pub note: String, +} + +impl Served { + /// The server answered with a page. + pub fn ok(&self) -> bool { + self.fetched && (200..300).contains(&self.status) + } + + fn why(&self) -> String { + let q = self.quote.trim(); + let n = self.note.trim(); + let w = if !q.is_empty() { q } else { n }; + if w.is_empty() { + "no result".to_string() + } else { + crate::truncate_str(w, 200).to_string() + } + } + + fn at(&self) -> String { + if self.url.is_empty() { + String::new() + } else { + format!(" ({})", self.url) + } + } +} + +/// What the served-page legs show, when they settle the proof: `None` when +/// they are absent or couldn't judge it (the end-to-end test decides). +fn served_outcome(p: &Proof) -> Option { + let change = p.served_change.as_ref()?; + let what = format!("\"{}\" in the server HTML (no script run)", p.criterion); + if change.fetched && !change.ok() { + return Some(Outcome::CoderWork(format!( + "{what}: the preview{} answered {}", + change.at(), + change.status + ))); + } + match change.shown { + Some(false) => { + return Some(Outcome::CoderWork(format!( + "{what}: not on the preview{}: {}", + change.at(), + change.why() + ))) + } + Some(true) => {} + None => { + // Not judged: the test decides; with no test, it is unverified. + return p.test.is_empty().then(|| { + Outcome::Unverified(format!( + "{what}: the preview{} couldn't be judged: {}", + change.at(), + change.why() + )) + }); + } + } + // Shown on the preview: a failing browser test still sends work back. + if !p.test.is_empty() && p.record.change.ran && p.record.change.red() { + return None; + } + let base = p.served_base.as_ref(); + Some(match base.and_then(|b| b.shown.filter(|_| b.ok())) { + Some(false) => Outcome::Proven(format!( + "{what}: missing on staging{} and shown on the preview{}: {}", + base.map(Served::at).unwrap_or_default(), + change.at(), + change.why() + )), + Some(true) => Outcome::Unverified(format!( + "{what}: shown on the preview{} and already on staging{}, so staging doesn't show what the ticket says is wrong", + change.at(), + base.map(Served::at).unwrap_or_default() + )), + None => Outcome::Unverified(format!( + "{what}: shown on the preview{}, staging couldn't be read{}", + change.at(), + base.map(|b| format!(": {}", b.why())).unwrap_or_default() + )), + }) +} + +/// Characters of a served page a judgment reads. +pub const SERVED_VIEW_CHARS: usize = 60_000; + +/// The served page as a judgment reads it: its markup with scripts and +/// styles taken out (structured data, `application/ld+json`, kept: the +/// server sends it for crawlers), whitespace collapsed, bounded. +pub fn served_view(html: &str) -> String { + let mut out = String::with_capacity(html.len().min(SERVED_VIEW_CHARS)); + let low = html.to_ascii_lowercase(); + let mut i = 0; + while i < html.len() { + let rest = &low[i..]; + let skip_tag = ["').map(|e| i + e + 1).unwrap_or(html.len()); + let open = &low[i..open_end]; + let close = if tag == "" + } else { + "" + }; + let end = low[open_end..] + .find(close) + .map(|e| open_end + e + close.len()) + .unwrap_or(html.len()); + if tag == " String { /// What the two runs show (see the module's rules). pub fn outcome(p: &Proof) -> Outcome { + if let Some(o) = served_outcome(p) { + return o; + } let (base, change) = (&p.record.base, &p.record.change); let what = if p.test.is_empty() { format!("\"{}\"", p.criterion) @@ -599,6 +846,9 @@ impl Proof { "Two-way proof: {w}. Make the test assert what the ticket says is wrong on {page} (\"{}\"), so it fails on staging and passes on this preview.", self.criterion )), + Outcome::CoderWork(w) if self.served_change.is_some() => Some(format!( + "Two-way proof: {w}. The criterion is about what the server sends, so a person (or a crawler) without scripts must get it from {page} as served: fix the code (not the test) so the server renders it, then fetch the preview's page source to see it there.", + )), Outcome::CoderWork(w) => Some(format!( "Two-way proof: {w}. The change doesn't do \"{}\" on the preview yet; fix the code (not the test) until it passes there.", self.criterion @@ -769,6 +1019,7 @@ mod tests { source: "sandbox".into(), at: String::new(), }, + ..Default::default() } } diff --git a/services/worker/src/passes/ci_repro.rs b/services/worker/src/passes/ci_repro.rs index e09f0d74b..f2b93f2c5 100644 --- a/services/worker/src/passes/ci_repro.rs +++ b/services/worker/src/passes/ci_repro.rs @@ -233,6 +233,33 @@ pub(crate) struct Target<'a> { pub head: &'a str, } +/// The base branch's deployment (staging): the configured test address +/// without `{pr}`, else the staging address the repository's end-to-end +/// setup names (`ci_repro::base_target`), read from `tree` at the head. +pub(crate) async fn base_address( + github: &GitHubClient, + (owner, repo, head): (&str, &str, &str), + tree: &[String], + configured: Option<&str>, +) -> Option { + let mut setup: Vec<(String, String)> = Vec::new(); + for p in tree + .iter() + .filter(|p| { + let low = p.to_ascii_lowercase(); + low.contains("playwright.config") + || (low.starts_with(".github/workflows/") + && (low.contains("e2e") || low.contains("playwright"))) + }) + .take(6) + { + if let Ok(text) = github.read_file(owner, repo, p, head).await { + setup.push((p.clone(), text)); + } + } + ci_repro::base_target(configured, &setup) +} + /// One Playwright test (`file › title`) with the head's test code, run in /// the sandbox against the base branch's deployment (`base`, staging) and /// against the pull request's preview (`change`). A side that couldn't run @@ -299,22 +326,7 @@ pub(crate) async fn two_way( // Where each side runs: the configured test address and the preview, // else the staging address the repository's end-to-end setup names. let configured = test_address(state, t.team_id, &format!("{owner}/{repo}")).await; - let mut setup: Vec<(String, String)> = Vec::new(); - for p in tree - .iter() - .filter(|p| { - let low = p.to_ascii_lowercase(); - low.contains("playwright.config") - || (low.starts_with(".github/workflows/") - && (low.contains("e2e") || low.contains("playwright"))) - }) - .take(6) - { - if let Ok(text) = github.read_file(owner, repo, p, head).await { - setup.push((p.clone(), text)); - } - } - let base_url = ci_repro::base_target(configured.as_deref(), &setup); + let base_url = base_address(github, (owner, repo, head), &tree, configured.as_deref()).await; let preview = super::preview::load(state, t.team_id, t.run_id) .await .filter(|p| p.head == head && !p.url.trim().is_empty()) diff --git a/services/worker/src/passes/e2e_proof.rs b/services/worker/src/passes/e2e_proof.rs index 360908e0f..19a6c37aa 100644 --- a/services/worker/src/passes/e2e_proof.rs +++ b/services/worker/src/passes/e2e_proof.rs @@ -90,19 +90,336 @@ async fn run_strings( .collect() } -/// The run's ticket criteria that need an end-to-end proof. +/// The run's criteria that need an end-to-end proof: the ticket's, else +/// the plan's criteria map (`ep::criteria_or_map`), so a run whose ticket +/// text gives none (an empty issue body) is still proven on what its plan +/// said it does. async fn criteria_of(state: &WorkerState, team_id: &str, run_id: &str) -> Vec { - let v = run_strings(state, team_id, run_id, &["title", "ticket_body"]).await; - let (title, body) = ( + let v = run_strings(state, team_id, run_id, &["title", "ticket_body", "repo"]).await; + let (title, body, repo) = ( v[0].clone().unwrap_or_default(), v[1].clone().unwrap_or_default(), + v[2].clone().unwrap_or_default(), ); - ep::criteria(&title, &body, &super::stop_judge::acceptance(&body)) + let acceptance = super::stop_judge::acceptance(&body); + let from_ticket = ep::criteria(&title, &body, &acceptance); + let map = match repo.split_once('/') { + Some((owner, name)) if !from_ticket.iter().any(ep::Criterion::needs_e2e) => { + ep::parse_map(&design_of(state, team_id, run_id, owner, name).await) + } + _ => Vec::new(), + }; + ep::criteria_or_map(&title, &body, &acceptance, &map) .into_iter() .filter(ep::Criterion::needs_e2e) .collect() } +// ── The served page ───────────────────────────────────────────────────────── + +/// The hosts a served-page fetch may reach: the preview's and the base +/// deployment's, both from CoderHelm's own records, never from a model or +/// the change. Every other `web_check` rule (https, public addresses, +/// redirects re-checked) still holds. +struct OwnDeployments(Vec); + +#[async_trait::async_trait] +impl super::web_check::HostGate for OwnDeployments { + async fn allowed(&self, host: &str) -> bool { + self.0.iter().any(|h| h.eq_ignore_ascii_case(host)) + } +} + +fn host_of(url: &str) -> Option { + reqwest::Url::parse(url) + .ok() + .and_then(|u| u.host_str().map(str::to_string)) +} + +/// `page` (a site path) on the deployment at `origin`. +pub fn page_url(origin: &str, page: &str) -> String { + let page = page.trim(); + if page.starts_with("https://") || page.starts_with("http://") { + return page.to_string(); + } + format!( + "{}/{}", + origin.trim().trim_end_matches('/'), + page.trim_start_matches('/') + ) +} + +/// One plain GET of `url` as the server sends it: no cookies, no script +/// run. The page's view for the judgment comes back with it. +async fn fetch_served(url: &str, gate: &OwnDeployments) -> (ep::Served, String) { + let req = common::coder_shell::Fetch { + urls: vec![url.to_string()], + head: false, + follow: true, + headers: Vec::new(), + body: true, + }; + match super::web_check::fetch_page(url, &req, gate, &super::web_check::Net).await { + Ok(f) => { + let view = ep::served_view(&String::from_utf8_lossy(&f.body)); + let note = f.stopped.clone().unwrap_or_default(); + ( + ep::Served { + url: url.to_string(), + fetched: f.status > 0, + status: f.status, + note, + ..Default::default() + }, + view, + ) + } + Err(e) => ( + ep::Served { + url: url.to_string(), + note: e.text().to_string(), + ..Default::default() + }, + String::new(), + ), + } +} + +/// One thing the judgment reads: a criterion on one side's served page. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ServedCheck { + pub criterion: String, + /// `preview` or `staging`. + pub side: &'static str, + pub url: String, + pub view: String, +} + +pub const SERVED_SYSTEM: &str = "You check whether a web page, exactly as its server sends it \ +(its HTML before any script runs: what a visitor with JavaScript off, a crawler, or `curl` gets), \ +satisfies one acceptance criterion of a ticket. Scripts were taken out of the page; JSON-LD \ +structured data was kept. Answer only from the page text given: `yes` when the page shows what \ +the criterion asks, `no` when it doesn't (the content is missing, only a placeholder or empty \ +container is there, or it would need a script to appear), `cant_tell` when the criterion can't \ +be judged from served HTML at all. Quote the part of the page that settles it, or say in a few \ +words what is missing."; + +/// The judgment's prompt: each distinct page once, then the checks. +pub fn served_prompt(checks: &[ServedCheck]) -> String { + let mut urls: Vec<&str> = Vec::new(); + for c in checks { + if !urls.contains(&c.url.as_str()) { + urls.push(&c.url); + } + } + let mut out = String::new(); + for (i, u) in urls.iter().enumerate() { + let view = checks + .iter() + .find(|c| c.url == *u) + .map(|c| c.view.as_str()) + .unwrap_or(""); + out.push_str(&format!( + "\n{view}\n\n\n" + )); + } + out.push_str("Checks:\n"); + for (i, c) in checks.iter().enumerate() { + let page = urls.iter().position(|u| *u == c.url).unwrap_or(0); + out.push_str(&format!("{i}. page {page} ({}): {}\n", c.side, c.criterion)); + } + out +} + +pub fn served_schema() -> serde_json::Value { + serde_json::json!({ + "type": "object", + "properties": { + "verdicts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "check": {"type": "integer"}, + "shown": {"type": "string", "enum": ["yes", "no", "cant_tell"]}, + "quote": {"type": "string"} + }, + "required": ["check", "shown", "quote"], + "additionalProperties": false + } + } + }, + "required": ["verdicts"], + "additionalProperties": false + }) +} + +/// Each check's verdict from the judgment's answer: `(shown, quote)`, with +/// `None` for a check it didn't answer or couldn't tell. +pub fn apply_served(v: &serde_json::Value, n: usize) -> Vec<(Option, String)> { + let mut out = vec![(None, String::new()); n]; + for item in v["verdicts"].as_array().into_iter().flatten() { + let Some(i) = item["check"] + .as_u64() + .map(|i| i as usize) + .filter(|i| *i < n) + else { + continue; + }; + let shown = match item["shown"].as_str() { + Some("yes") => Some(true), + Some("no") => Some(false), + _ => None, + }; + let quote = + common::truncate_str(item["quote"].as_str().unwrap_or("").trim(), 300).to_string(); + out[i] = (shown, quote); + } + out +} + +/// The served pages judged against their criteria. A page the server +/// didn't answer with is settled without asking; a judgment that can't be +/// asked leaves each one unjudged (never a pass). +async fn judge_served( + state: &WorkerState, + team_id: &str, + checks: &[ServedCheck], +) -> Vec<(Option, String)> { + if checks.is_empty() { + return Vec::new(); + } + let provider = match crate::agent::provider::ModelProvider::load_for_team( + &state.dynamo, + &state.config.settings_table_name, + team_id, + ) + .await + { + Ok(p) => p, + Err(e) => { + warn!(error = %e, "Served-page proof: no model to judge with"); + return vec![(None, format!("no model to judge with ({e})")); checks.len()]; + } + }; + let mut usage = crate::models::TokenUsage::default(); + match crate::agent::anthropic::converse_json( + &provider.client(), + provider.judgment_model_id(), + SERVED_SYSTEM, + &served_prompt(checks), + &served_schema(), + true, + common::stop_judge::JUDGMENT_EFFORT, + 4096, + &mut usage, + ) + .await + { + Ok(v) => apply_served(&v, checks.len()), + Err(e) => { + warn!(error = %e, "Served-page proof: the judgment didn't answer"); + vec![(None, format!("the judgment didn't answer ({e})")); checks.len()] + } + } +} + +/// The served-page legs of each criterion about the served page +/// (`Criterion::about_served`), by criterion text: its page fetched on the +/// preview and on the base deployment, and judged. +async fn served_legs( + state: &WorkerState, + github: &GitHubClient, + p: super::preview::Pr<'_>, + st: &State, + criteria: &[ep::Criterion], +) -> std::collections::HashMap)> { + let mut out = std::collections::HashMap::new(); + let wanted: Vec<&ep::Criterion> = criteria + .iter() + .filter(|c| c.about_served() && c.page.is_some()) + .collect(); + if wanted.is_empty() || st.url.trim().is_empty() { + return out; + } + let tree: Vec = github + .get_tree(p.owner, p.repo, &st.head) + .await + .map(|t| t.into_iter().map(|e| e.path).collect()) + .unwrap_or_default(); + let configured = + super::ci_repro::test_address(state, p.team_id, &format!("{}/{}", p.owner, p.repo)).await; + let base = super::ci_repro::base_address( + github, + (p.owner, p.repo, &st.head), + &tree, + configured.as_deref(), + ) + .await; + let gate = OwnDeployments( + [Some(st.url.as_str()), base.as_deref()] + .into_iter() + .flatten() + .filter_map(host_of) + .collect(), + ); + let mut fetched: std::collections::HashMap = + std::collections::HashMap::new(); + let mut checks: Vec = Vec::new(); + let mut slots: Vec<(String, &'static str)> = Vec::new(); + for c in &wanted { + let page = c.page.as_deref().unwrap_or(""); + let sides = [ + ("preview", Some(st.url.as_str())), + ("staging", base.as_deref()), + ]; + for (side, origin) in sides { + let Some(origin) = origin else { continue }; + let url = page_url(origin, page); + if !fetched.contains_key(&url) { + let got = fetch_served(&url, &gate).await; + fetched.insert(url.clone(), got); + } + let (served, view) = &fetched[&url]; + if served.ok() && !view.is_empty() { + checks.push(ServedCheck { + criterion: c.text.clone(), + side, + url: url.clone(), + view: view.clone(), + }); + slots.push((c.text.clone(), side)); + } + } + } + let verdicts = judge_served(state, p.team_id, &checks).await; + for c in &wanted { + let page = c.page.as_deref().unwrap_or(""); + let leg = |side: &str, origin: &str| { + let url = page_url(origin, page); + let mut s = fetched + .get(&url) + .map(|(s, _)| s.clone()) + .unwrap_or_default(); + if let Some(i) = slots.iter().position(|(t, sd)| *t == c.text && *sd == side) { + if let Some((shown, quote)) = verdicts.get(i) { + s.shown = *shown; + if shown.is_some() { + s.quote = quote.clone(); + } else if s.note.is_empty() { + s.note = quote.clone(); + } + } + } + s + }; + let change = leg("preview", &st.url); + let base_leg = base.as_deref().map(|b| leg("staging", b)); + out.insert(c.text.clone(), (change, base_leg)); + } + out +} + /// The plan's design.md for the run's ticket and repository, empty when /// it can't be read. async fn design_of( @@ -188,7 +505,12 @@ pub(crate) async fn prove( .repo(&format!("{}/{}", p.owner, p.repo)) .run(p.run_id); let mut proofs = all; - for c in criteria.iter().take(MAX_CRITERIA) { + let criteria: Vec = criteria.into_iter().take(MAX_CRITERIA).collect(); + // What the server sends for each criterion about it, no script run: a + // browser test runs the page's scripts and can pass while the server + // sends none of it. + let mut served = served_legs(state, github, p, st, &criteria).await; + for c in &criteria { // The plan's test when it is on the head, else a changed spec that // loads the page. let planned = ep::line_for(c, &map) @@ -227,11 +549,17 @@ pub(crate) async fn prove( ..Default::default() }, }; + let (served_change, served_base) = match served.remove(&c.text) { + Some((change, base)) => (Some(change), base), + None => (None, None), + }; let proof = Proof { criterion: c.text.clone(), page: c.page.clone().unwrap_or_default(), test: test.unwrap_or_default(), record, + served_base, + served_change, }; info!(run_id = p.run_id, outcome = ?ep::outcome(&proof), "Two-way proof of a criterion"); super::add_progress_note( @@ -318,6 +646,7 @@ mod tests { change, ..Default::default() }, + ..Default::default() } } diff --git a/services/worker/src/passes/incidents/cp_criteria_proven_both_ways.rs b/services/worker/src/passes/incidents/cp_criteria_proven_both_ways.rs index fec586525..d26639d59 100644 --- a/services/worker/src/passes/incidents/cp_criteria_proven_both_ways.rs +++ b/services/worker/src/passes/incidents/cp_criteria_proven_both_ways.rs @@ -122,6 +122,7 @@ fn proof(test: &str, base_out: &str, change_out: &str) -> Proof { source: "sandbox".into(), at: String::new(), }, + ..Default::default() } } diff --git a/services/worker/src/passes/incidents/dd_criterion_on_the_preview.rs b/services/worker/src/passes/incidents/dd_criterion_on_the_preview.rs new file mode 100644 index 000000000..4fe4fefd9 --- /dev/null +++ b/services/worker/src/passes/incidents/dd_criterion_on_the_preview.rs @@ -0,0 +1,252 @@ +//! dd. A ticket asked that a page's answers be in the HTML the server +//! sends, so they show with scripts turned off and crawlers read them. The +//! run rewrote the block as markup that needs no script, wrote unit tests +//! that render the component on its own, and pushed. Its pull request had +//! nothing that fetched the preview's page as the server sends it: the +//! page loads the block on the client only, so the served HTML still had +//! none of the answers. The preview's own check found it ("the text is not +//! in the server HTML") after the push. The run that opened the pull +//! request came from an issue with an empty body, so the two-way proof had +//! no criterion to prove at all and the ready decision read "nothing to +//! prove". +//! +//! Guarantee: the criteria to prove come from the ticket, else from the +//! plan's criteria map (`common::e2e_proof::criteria_or_map`), so an empty +//! ticket body never means nothing to prove. A criterion about what the +//! server sends (its page source, the page with scripts off, what a +//! crawler reads: `Criterion::about_served`) is also proven on the served +//! page itself: the page is fetched as the server sends it on the preview +//! and on staging (`e2e_proof::served_legs`, a plain GET through +//! `web_check::fetch_page`, no script run) and each side is judged against +//! the criterion. Not shown on the preview is coder work whatever the +//! browser test says, so it goes back as a fix round and the ready +//! decision waits for it (`common::e2e_proof::outcome`, `standing_of`); +//! shown on the preview and missing on staging is proven; a side that +//! couldn't be fetched or judged is unverified with why, never a pass. + +use crate::passes::e2e_proof::{ + apply_served, page_url, served_prompt, standing_of, ServedCheck, Standing, +}; +use common::ci_repro::{Leg, Record}; +use common::e2e_proof::{self as ep, Outcome, Proof, Served}; + +const TITLE: &str = "Make the questions block work without JavaScript"; +/// The issue the run started from: no body at all. +const BODY: &str = ""; +const HEAD: &str = "5e84f9390fe6"; + +/// The plan's criteria map: the only place the run's criteria were written. +const DESIGN: &str = "## Approach\nRender the block with native markup.\n\n## Criteria map\n- Every answer, including those behind Show more, is in the server HTML | page: /acme/classes | e2e: e2e/tests/site/questions.spec.ts › every answer is served | asserts: all answers are in the page source\n- One item opens at a time | page: /acme/classes | e2e: e2e/tests/site/questions.spec.ts › one open | asserts: opening one closes the other\n"; + +/// The preview's page as its server sent it: the block is loaded on the +/// client only, so the served HTML has the section and no answers. +const PREVIEW_HTML: &str = "

Questions

"; + +fn browser_green() -> Leg { + Leg { + ran: true, + passed: 1, + ..Default::default() + } +} + +fn served(url: &str, shown: Option, quote: &str) -> Served { + Served { + url: url.into(), + fetched: true, + status: 200, + shown, + quote: quote.into(), + ..Default::default() + } +} + +fn proof(criterion: &str, change: Option, base: Option) -> Proof { + Proof { + criterion: criterion.into(), + page: "/acme/classes".into(), + test: "e2e/tests/site/questions.spec.ts › every answer is served".into(), + record: Record { + head: HEAD.into(), + check: "two-way proof".into(), + // The browser runs the page's scripts: its test passes on both. + base: browser_green(), + change: browser_green(), + ..Default::default() + }, + served_change: change, + served_base: base, + } +} + +#[test] +fn an_empty_ticket_body_still_has_the_plans_criteria_to_prove() { + let map = ep::parse_map(DESIGN); + // The ticket text alone gives nothing to prove. + assert!(ep::criteria(TITLE, BODY, &[]) + .iter() + .all(|c| !c.needs_e2e())); + let criteria = ep::criteria_or_map(TITLE, BODY, &[], &map); + assert_eq!(criteria.len(), 2, "{criteria:?}"); + assert!(criteria.iter().all(|c| c.needs_e2e())); + assert_eq!(criteria[0].page.as_deref(), Some("/acme/classes")); + // The served-page criterion is known as one; the click one is not. + assert!(criteria[0].about_served()); + assert!(!criteria[1].about_served()); + // A ticket that has its own criteria keeps them. + let own = ep::criteria_or_map( + TITLE, + "Expected\nThe answers show on /acme/classes with JavaScript off", + &[], + &map, + ); + assert_eq!(own.len(), 1); + assert!(own[0].text.contains("JavaScript off")); +} + +#[test] +fn the_served_page_is_read_without_its_scripts() { + let view = ep::served_view(PREVIEW_HTML); + assert!(view.contains("

Questions

"), "{view}"); + assert!(!view.contains("__chunks"), "{view}"); + assert!(!view.contains(".x{}"), "{view}"); + // Structured data is what the server sends for crawlers: kept. + let ld = ep::served_view( + "", + ); + assert!(ld.contains("FAQPage"), "{ld}"); + assert_eq!( + page_url("https://pr-12.preview.example.dev/", "/acme/classes"), + "https://pr-12.preview.example.dev/acme/classes" + ); +} + +#[test] +fn the_judgment_reads_each_side_and_an_unanswered_check_is_never_a_pass() { + let criterion = "Every answer, including those behind Show more, is in the server HTML"; + let checks = vec![ + ServedCheck { + criterion: criterion.into(), + side: "preview", + url: "https://pr-12.preview.example.dev/acme/classes".into(), + view: ep::served_view(PREVIEW_HTML), + }, + ServedCheck { + criterion: criterion.into(), + side: "staging", + url: "https://staging.example.dev/acme/classes".into(), + view: ep::served_view(PREVIEW_HTML), + }, + ]; + let prompt = served_prompt(&checks); + assert!(prompt.contains(" { + assert!(w.contains("server HTML"), "{w}"); + assert!(w.contains("pr-12.preview.example.dev"), "{w}"); + } + o => panic!("{o:?}"), + } + let items = ep::coder_items(std::slice::from_ref(&p), HEAD); + assert_eq!(items.len(), 1); + assert!(items[0].contains("server renders it"), "{}", items[0]); + assert!(items[0].contains("page source"), "{}", items[0]); + // The ready decision waits on the fix round, never ready. + assert_eq!(standing_of(&[p], HEAD), Standing::Fixing(1)); +} + +#[test] +fn shown_on_the_preview_and_missing_on_staging_is_proven_and_a_failed_fetch_is_unverified() { + let criterion = "Every answer, including those behind Show more, is in the server HTML"; + let proven = proof( + criterion, + Some(served( + "https://pr-12.preview.example.dev/acme/classes", + Some(true), + "
Can I book online?Yes", + )), + Some(served( + "https://staging.example.dev/acme/classes", + Some(false), + "answers are empty hidden divs", + )), + ); + assert!(matches!(ep::outcome(&proven), Outcome::Proven(_))); + assert_eq!(standing_of(&[proven], HEAD), Standing::Done(vec![])); + + // A preview that answers with an error page is coder work. + let mut down = served("https://pr-12.preview.example.dev/acme/classes", None, ""); + down.status = 500; + let p = proof(criterion, Some(down), None); + assert!(ep::outcome(&p).is_coder_work(), "{:?}", ep::outcome(&p)); + + // Not judged and no browser test: unverified with why, never a pass. + let unjudged = Served { + url: "https://pr-12.preview.example.dev/acme/classes".into(), + note: "the judgment didn't answer".into(), + ..Default::default() + }; + let mut p = proof(criterion, Some(unjudged), None); + p.test.clear(); + match standing_of(&[p], HEAD) { + Standing::Done(notes) => { + assert_eq!(notes.len(), 1); + assert!(notes[0].contains("couldn't be judged"), "{notes:?}"); + } + s => panic!("{s:?}"), + } +} + +/// The pull request watch's proof runs the served-page legs, and its +/// criteria come through the plan's map when the ticket gives none. +#[test] +fn the_proof_fetches_the_served_page_and_falls_back_to_the_plan() { + let src = include_str!("../e2e_proof.rs"); + let prove = &src[src.find("pub(crate) async fn prove(").unwrap()..]; + let prove = &prove[..prove.find("\n}\n").unwrap()]; + assert!( + prove.contains("served_legs("), + "prove doesn't fetch the served page" + ); + assert!(prove.contains("served_change")); + let criteria = &src[src.find("async fn criteria_of(").unwrap()..]; + let criteria = &criteria[..criteria.find("\n}\n").unwrap()]; + assert!(criteria.contains("criteria_or_map(")); + assert!(criteria.contains("design_of(")); + let legs = &src[src.find("async fn served_legs(").unwrap()..]; + assert!(legs.contains("about_served()")); + assert!(legs.contains("fetch_served(")); + assert!(legs.contains("judge_served(")); +} From e7ade739d216808b3db44603caa4f75db938562b Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Wed, 18 Nov 2026 14:13:40 -0500 Subject: [PATCH 4/4] Plan check gaps once and in the ticket's terms; a working alternative is a code fix Only top-level Out of scope bullets are items (nested lookups and evidence never are), a name the ticket uses is never out of scope, a criterion matches an item only on words that tell items apart, and every gap reaches the decision once. A fix-location trace that shows a working value of the same kind beside the wrong one, with a code layer in our repositories, is a code fix, and a cached outside verdict is judged again under that rule. --- docs/incidents/de_plan_check_gaps_once.md | 5 + .../df_working_alternative_is_code.md | 5 + services/common/src/scope_ledger.rs | 132 ++++++++++++- services/worker/src/passes/fix_location.rs | 75 ++++++++ services/worker/src/passes/habits.rs | 2 +- .../incidents/de_plan_check_gaps_once.rs | 113 +++++++++++ .../df_working_alternative_is_code.rs | 178 ++++++++++++++++++ services/worker/src/passes/plan.rs | 12 +- services/worker/src/passes/plan_shape.rs | 5 +- services/worker/src/passes/scope_ledger.rs | 8 +- services/worker/src/passes/ticket_history.rs | 8 +- 11 files changed, 524 insertions(+), 19 deletions(-) create mode 100644 docs/incidents/de_plan_check_gaps_once.md create mode 100644 docs/incidents/df_working_alternative_is_code.md create mode 100644 services/worker/src/passes/incidents/de_plan_check_gaps_once.rs create mode 100644 services/worker/src/passes/incidents/df_working_alternative_is_code.rs diff --git a/docs/incidents/de_plan_check_gaps_once.md b/docs/incidents/de_plan_check_gaps_once.md new file mode 100644 index 000000000..c987f7f6f --- /dev/null +++ b/docs/incidents/de_plan_check_gaps_once.md @@ -0,0 +1,5 @@ +# de. `de_plan_check_gaps_once` + +**What happened:** A ticket asked for a page block to work without JavaScript, with its structured data (`FAQPage`) in the server HTML. The plan's `## Out of scope` held one item decided with its default, and under it two indented lines recording what a lookup showed ("Looked up: ... `FAQPage` was not in the server HTML", "No lookup settles ..."). The plan check read each indented line as an item left out, so `FAQPage` became the mark of an out-of-scope item called "Looked up", and each of the five task lines naming it added the same gap. The run note and the decision's open gaps carried "A task names `FAQPage`, which `## Out of scope` leaves out" five times, telling the run to take the ticket's own ask out of its tasks. A second plan for the same ticket was told that an item about one script per page was asked for by the criterion "No layout shift when the page loads or when items toggle": the two shared only "when" (counted twice) and "page". + +**The guarantee:** An out-of-scope section's items are its top-level bullets; an indented line under one, and any line recording a lookup, is that item's evidence and never an item (`common::scope_ledger`). Bold markers are no part of an item's name. What the ticket itself names (its title and body) is in scope: it is no mark of an out-of-scope item, and an item the ticket says in full moves in, both in the plan check and in the ledger kept on the run. A criterion asks for an item only on distinct words that tell items apart, never on common words or a word counted twice. Every plan-check gap is said once, in the run note and on the decision's open gaps (`scope_ledger::unique`, `FixDecision::add_gaps`), whichever check found it and on however many task lines. diff --git a/docs/incidents/df_working_alternative_is_code.md b/docs/incidents/df_working_alternative_is_code.md new file mode 100644 index 000000000..2f3cc132c --- /dev/null +++ b/docs/incidents/df_working_alternative_is_code.md @@ -0,0 +1,5 @@ +# df. `df_working_alternative_is_code` + +**What happened:** A ticket said a camp card showed a broken image: the page used an older image address that returned an error, while the address the reporter expected was already stored in our database. The trace found the whole path: the class's own record in the source system held the broken address, a second source record of the same kind (its league) held a working one, and our pipeline gave the class's own image priority, so the broken one was stored and rendered. A thousand other classes carried addresses of the same kind. The run decided the fix was outside the code (edit the one source record), and a later run of the unchanged ticket stopped on that earlier verdict without planning again: "the ticket is unchanged since CoderHelm learned the fix is outside the code". A careful engineer makes the pipeline fall back to the working image, for every record. + +**The guarantee:** A broken source value that our code chooses over a working one in its reach is a code fix. When a decision says `outside_code` and its own trace shows a layer holding a working value of the same kind as a wrong layer, and a layer that is code in one of our repositories, the plan check sends it back to fix that code (prefer, or fall back to, the working value, with a test), and the planner's guidance says so from the start (`fix_location::working_alternative`). `outside_code` stays right when no layer our code reads holds a working value. An earlier "outside the code" verdict is judged again under the same rule before it may stop a new plan on an unchanged ticket (`TicketHistory::guard`). diff --git a/services/common/src/scope_ledger.rs b/services/common/src/scope_ledger.rs index 1a5704e3b..e4e808aef 100644 --- a/services/common/src/scope_ledger.rs +++ b/services/common/src/scope_ledger.rs @@ -364,6 +364,13 @@ pub fn parse_line(line: &str, by: &str) -> Option { } else { (t.clone(), String::new()) }; + // Bold the line's markers left behind ("**Item**: why" splits into + // "Item**" and "why") is no part of either. + let item = item.trim_matches('*').trim().to_string(); + let why = why.trim_matches('*').trim().to_string(); + if item.is_empty() { + return None; + } Some(Entry { item: item.trim_end_matches(['.', ',']).to_string(), why: why.trim_end_matches('.').to_string(), @@ -480,6 +487,51 @@ const OUT_HEADINGS: &[&str] = &[ "non goals", ]; +/// Openers of a line that records what a lookup showed: the evidence for +/// the entry above it, never an item of its own. A plan once wrote +/// "Looked up: the page returned 200 and `X` was not in it" under an item, +/// and the check read it as an item left out, named `X`, and told the +/// planner five times over that its tasks name an out-of-scope item. +const EVIDENCE_OPENERS: &[&str] = &[ + "looked up", + "lookup:", + "no lookup settles", + "no lookup", + "evidence:", + "checked:", + "measured:", + "source:", + "seen:", + "shows:", + "showed:", +]; + +fn is_evidence(text: &str) -> bool { + let l = lower(text.trim().trim_matches('*').trim()); + EVIDENCE_OPENERS.iter().any(|o| l.starts_with(o)) +} + +/// The items an out-of-scope section lists: its top-level bullets. A +/// bullet nested under one (deeper than the section's first bullet) is +/// that item's evidence or detail, and a line that records a lookup is +/// evidence wherever it stands; neither is an item. +fn out_bullets(text: &str) -> Vec { + let mut out = Vec::new(); + let mut top: Option = None; + for l in sections(text, OUT_HEADINGS) { + let Some(b) = bullet(l) else { + continue; + }; + let indent = l.len() - l.trim_start().len(); + let top = *top.get_or_insert(indent); + if indent > top || is_evidence(&b) { + continue; + } + out.push(b); + } + out +} + /// Adds `e` unless an entry already says it: the same item, one item /// opening the other ("`/x` pages" and "`/x` pages also cover y"), or a /// path or route both name; marks are merged. @@ -570,7 +622,7 @@ impl Ledger { pub fn from_plan(proposal: &str, design: &str, tasks: &str) -> Ledger { let mut entries: Vec = Vec::new(); for text in [design, proposal] { - for b in sections(text, OUT_HEADINGS).into_iter().filter_map(bullet) { + for b in out_bullets(text) { if let Some(e) = parse_line(&b, BY_PLAN) { push_entry(&mut entries, e); } @@ -619,6 +671,28 @@ impl Ledger { l } + /// What the ticket itself names is in scope, whatever the plan wrote + /// (`ticket`: its title and body). A name or path the ticket says is no + /// mark of an out-of-scope item (a task may name it, a diff may add it), + /// and an item the ticket says in full is moved in with that reason. + /// Returns a line for each item moved in. + pub fn named_by_ticket(&mut self, ticket: &str) -> Vec { + let t = lower(ticket); + if t.trim().is_empty() { + return Vec::new(); + } + let mut moved = Vec::new(); + for e in self.entries.iter_mut().filter(|e| e.is_out()) { + e.marks.retain(|m| !t.contains(&lower(m))); + let item = lower(e.item.trim().trim_end_matches('.')); + if item.chars().count() >= 12 && t.contains(&item) { + e.moved_in = "the ticket names it".to_string(); + moved.push(format!("\"{}\" moved into scope: {}", e.item, e.moved_in)); + } + } + moved + } + /// Moves an item into scope, recording who asked and why. False when no /// entry matches. pub fn move_in(&mut self, item: &str, why: &str) -> bool { @@ -723,12 +797,30 @@ pub fn changes(notes: &str) -> Vec<(String, String)> { .collect() } +/// Words that tell no item apart from another: a criterion and an item +/// that share only these share nothing. "No layout shift when the page +/// loads or when items toggle" once matched an item about one script per +/// page, on "when" (counted twice) and "page". +const COMMON_WORDS: &[&str] = &[ + "when", "with", "that", "this", "from", "have", "will", "into", "each", "only", "then", "than", + "there", "their", "what", "which", "while", "also", "does", "should", "must", "they", "them", + "been", "being", "were", "more", "most", "some", "such", "other", "after", "before", "about", + "over", "under", "same", "both", "every", "where", "there", "here", "page", "pages", "user", + "users", "make", "made", "work", "works", "show", "shows", +]; + +/// The distinct words of `text` that tell an item apart. fn significant(text: &str) -> Vec { - lower(text) + let mut out: Vec = Vec::new(); + for w in lower(text) .split(|c: char| !c.is_alphanumeric() && c != '-' && c != '_') - .filter(|w| w.chars().count() >= 4) - .map(str::to_string) - .collect() + .filter(|w| w.chars().count() >= 4 && !COMMON_WORDS.contains(w)) + { + if !out.iter().any(|o| o == w) { + out.push(w.to_string()); + } + } + out } /// Words of a comment that keeps an item out rather than asking for it. @@ -884,7 +976,7 @@ pub fn plan_gaps(proposal: &str, design: &str, tasks: &str, criteria: &[String]) )); } out.extend(decision_gaps(proposal, design, tasks, criteria)); - out + unique(out) } /// Whether design.md has its out-of-scope section. @@ -901,6 +993,19 @@ pub fn decision_gaps( design: &str, tasks: &str, criteria: &[String], +) -> Vec { + decision_gaps_for(proposal, design, tasks, criteria, "") +} + +/// [`decision_gaps`] read against the ticket's own words (`ticket`: its +/// title and body): what the ticket names is in scope, so a task naming it +/// is never a task naming an out-of-scope item ([`Ledger::named_by_ticket`]). +pub fn decision_gaps_for( + proposal: &str, + design: &str, + tasks: &str, + criteria: &[String], + ticket: &str, ) -> Vec { let t = tasks.trim_start(); if t.is_empty() || t.starts_with("NO_CHANGES_NEEDED") || t.starts_with("CLARIFICATION_NEEDED") { @@ -920,7 +1025,8 @@ pub fn decision_gaps( one_line(&asks[0]) )); } - let ledger = Ledger::from_plan(proposal, design, ""); + let mut ledger = Ledger::from_plan(proposal, design, ""); + ledger.named_by_ticket(ticket); for e in ledger.outs() { if let Some(c) = asked_by(e, criteria) { out.push(format!( @@ -956,6 +1062,18 @@ pub fn decision_gaps( )); } } + unique(out) +} + +/// `lines` in their order, each said once: a check that finds the same +/// thing on five task lines says it once. +pub fn unique(lines: Vec) -> Vec { + let mut out: Vec = Vec::new(); + for l in lines { + if !out.iter().any(|o| o.trim() == l.trim()) { + out.push(l); + } + } out } diff --git a/services/worker/src/passes/fix_location.rs b/services/worker/src/passes/fix_location.rs index f27b6c195..79c29f272 100644 --- a/services/worker/src/passes/fix_location.rs +++ b/services/worker/src/passes/fix_location.rs @@ -458,6 +458,18 @@ pub enum Route { } impl FixDecision { + /// Adds the plan check's open gaps, each said once: the checks run + /// line by line (a task, an item), and one finding read on five task + /// lines is still one gap. + pub fn add_gaps>(&mut self, lines: I) { + for l in lines { + let l = l.trim().to_string(); + if !l.is_empty() && !self.open_gaps.iter().any(|g| g.trim() == l) { + self.open_gaps.push(l); + } + } + } + /// What the decision actually supports. An outside change with nothing to /// change is not a decision: it is reported as unknown, never coded around. pub fn effective_location(&self) -> FixLocation { @@ -472,6 +484,63 @@ impl FixDecision { } } +/// Whether a layer's `where` is code in a repository (`owner/repo:path`), +/// as opposed to a system that holds data. +fn is_code_layer(l: &Layer) -> bool { + let w = l.where_.trim(); + w.split_once(':') + .is_some_and(|(repo, path)| repo.contains('/') && !repo.contains(' ') && !path.is_empty()) +} + +/// The kind of a layer, from its name's first word (`source`, `store`, +/// `index`, `page`). +fn layer_kind(l: &Layer) -> String { + l.layer + .split(|c: char| !c.is_alphanumeric()) + .find(|w| !w.is_empty()) + .unwrap_or("") + .to_ascii_lowercase() +} + +/// A wrong value from a source that has a working alternative in our own +/// reach: the trace shows a layer of the same kind as a wrong one holding +/// a working value (a sibling field, a parent record, a second source of the +/// same thing), and a layer that is code in one of our repositories, which +/// passes the wrong one along. Our code chooses which value reaches the +/// page, so the fix is in that code: prefer, or fall back to, the working +/// value. `None` when the trace shows no such alternative. +/// +/// A ticket once reported a broken image on a page: a source record held an +/// address that returned an error, a second source record of the same kind +/// held a working one, and our pipeline gave the first priority. The run +/// called it a change outside the code (edit the source record), though a +/// thousand other records carried addresses of the same kind and our own +/// pipeline already had the working one in hand. +pub fn working_alternative(d: &FixDecision) -> Option { + let layers = &d.evidence.layers; + let code = layers.iter().find(|l| is_code_layer(l))?; + let state = |l: &Layer| l.state.trim().to_ascii_lowercase(); + let wrong: Vec<&Layer> = layers + .iter() + .filter(|l| state(l) == "wrong" && !is_code_layer(l)) + .collect(); + let ok = layers.iter().find(|o| { + state(o) == "ok" + && !is_code_layer(o) + && !o.shows.trim().is_empty() + && wrong + .iter() + .any(|w| !layer_kind(w).is_empty() && layer_kind(w) == layer_kind(o)) + })?; + Some(format!( + "Your trace shows a working value in reach: `{}` holds \"{}\", and `{}` ({}) is our code, which passes the broken value along instead. A broken source value that our code chooses over a working one is a code fix: make that code prefer, or fall back to, the working value (`code`, or `both` when the source record should be corrected too), with a test of the fallback. `outside_code` is right only when no layer our code reads holds a working value.", + ok.layer.trim(), + common::truncate_str(ok.shows.trim(), 160), + code.where_.trim(), + code.layer.trim() + )) +} + /// What a settled decision about data still lacks, in plain instructions /// (empty when nothing is missing): a lookup at all, what writes the wrong /// value, that code named as the writer was actually opened in this run @@ -528,6 +597,11 @@ pub fn gaps( return out; } let p = &d.evidence.producer; + if d.fix_location == FixLocation::OutsideCode { + if let Some(why) = working_alternative(d) { + out.push(why); + } + } if p.kind.trim() == "code" && d.fix_location == FixLocation::OutsideCode { out.push("You found that code writes the wrong value, so it is our bug: the fix is in that code (`code`, or `both` when a source record must change too), not outside it. A display fallback alone isn't the fix.".to_string()); } @@ -1145,6 +1219,7 @@ Before writing tasks, decide whether the fix belongs in this code at all. - Before your first query on a table, read its columns (describe it); don't guess column names from other tables' conventions. - Never name a cause in a system you couldn't read. If the trace through what you can read is complete and leads into another system, say so with that trace. If you couldn't finish the trace, use `unknown`, say where it stopped, and list the next lookups that would finish it, without a likely culprit. - If the code behaves as designed and the outcome comes from data or configuration in a source system (a booking or scheduling system, a CMS, a ticket tool's configuration, a feature flag held in another system, a cloud console setting), the fix is a change in that system, not in this code. Set `fix_location` to `outside_code`, describe the exact change, and set tasks.md to `NO_CODE_CHANGE: `. +- When a source record holds a broken value (an address that errors, an empty or invalid field) and your trace shows a working value for the same thing that our code can read (a second source record of the same kind, a parent or group record, a value our pipeline already computes), and our code chooses the broken one, the fix is in that code: prefer or fall back to the working value, for every record, with a test. Use `code` (or `both` when the source record should be corrected too). `outside_code` is right only when nothing our code reads holds a working value. - Never override source data in code: no hardcoded record ids, allowlists, denylists or "force" lists that change behavior for specific records the source system already decides. That hides the cause and goes stale. If that is the only way you see to make the ticket's symptom go away, the fix is outside the code. - If a code change is needed AND a change in another system, use `both`: plan the code part normally and describe the outside change. - If you looked and still cannot tell whether the code or the data is at fault, use `unknown`, say what you checked and what a person needs to confirm, and set tasks.md to `NO_CODE_CHANGE: `. Prefer asking over coding. diff --git a/services/worker/src/passes/habits.rs b/services/worker/src/passes/habits.rs index 7f501b00f..386e60cd6 100644 --- a/services/worker/src/passes/habits.rs +++ b/services/worker/src/passes/habits.rs @@ -477,7 +477,7 @@ pub fn keep_open(d: &mut FixDecision, facts: &Facts, left: &[String]) { why: String::new(), }); } - d.open_gaps.extend( + d.add_gaps( left.iter() .map(|g| common::truncate_str(g.lines().next().unwrap_or(g), 400).to_string()), ); diff --git a/services/worker/src/passes/incidents/de_plan_check_gaps_once.rs b/services/worker/src/passes/incidents/de_plan_check_gaps_once.rs new file mode 100644 index 000000000..c97cdd9e5 --- /dev/null +++ b/services/worker/src/passes/incidents/de_plan_check_gaps_once.rs @@ -0,0 +1,113 @@ +//! de. A ticket asked for a page block to work without JavaScript and for +//! its structured data (`FAQPage`) to be in the server HTML. The plan's +//! `## Out of scope` held one item decided with its default, and under it +//! two indented lines recording what a lookup had shown ("Looked up: the +//! page returned 200 and `FAQPage` was not in the server HTML", "No lookup +//! settles which is better"). The plan check read each indented line as an +//! item left out of scope, so `FAQPage` became the mark of an out-of-scope +//! item called "Looked up", and every task line naming it (five of them) +//! added the same gap: "A task names `FAQPage`, which `## Out of scope` +//! leaves out (\"Looked up\")". The run note and the decision's open gaps +//! carried that line five times, and the run told itself to take the +//! ticket's own ask out of its tasks. The same day a second plan for the +//! same ticket was told an item about one script per page was asked for +//! by the criterion "No layout shift when the page loads or when items +//! toggle": the two share only "when" (counted twice) and "page". +//! +//! Guarantee: an out-of-scope section's items are its top-level bullets; +//! an indented line under one, and a line that records a lookup, is that +//! item's evidence, never an item (`scope_ledger::out_bullets`). What the +//! ticket itself names (title, body) is in scope: no mark of an +//! out-of-scope item, and an item it says in full moves in +//! (`Ledger::named_by_ticket`, read by the plan check and by the ledger +//! kept on the run). A criterion asks for an item only on distinct words +//! that tell items apart. Every plan-check gap is said once, in the note +//! and on the decision (`scope_ledger::unique`, `FixDecision::add_gaps`). + +use crate::passes::fix_location::FixDecision; +use crate::passes::plan::PlanResult; +use crate::passes::plan_shape; +use common::scope_ledger::Ledger; + +const TICKET: &str = "Make the FAQ block work without JavaScript\n\nEvery question and answer of the FAQ block is in the server HTML, and the block's `FAQPage` structured data is rendered on the server.\n\nAcceptance criteria:\n- Answers are readable with JavaScript off\n- No layout shift when the page loads or when items toggle\n"; + +const DESIGN: &str = "## Out of scope\n- **Merging the structured data of several blocks on one page**: decided with the default: one script per block\n - Looked up: `https://example.test/parking?cb=1` returned 200 with two blocks, and `FAQPage` was not in the server HTML\n - No lookup settles which is better for search: today's script is added only in the browser\n- `apps/web/src/components/ui/accordion.tsx`: other blocks use it\n- One FAQPage script per page when a page has two FAQ blocks: decided with the default: one per block\n"; + +const TASKS: &str = "- [ ] apps/web/src/components/blocks/faq.tsx: [modify] Render each answer in `
`, and the `FAQPage` script on the server\n- [ ] apps/web/src/test/components/faq.test.tsx: [create] The `FAQPage` script is in the server HTML\n- [ ] e2e/pages/faq.ts: [create] Read the `FAQPage` script from the raw HTML\n- [ ] e2e/tests/site/faq.spec.ts: [create] With JavaScript off, every answer and the `FAQPage` script are there\n- [ ] e2e/specs/site.md: [modify] Document the `FAQPage` check\n"; + +fn plan() -> PlanResult { + PlanResult { + proposal: "## Problem\nThe block needs JavaScript.\n".into(), + tasks: TASKS.into(), + spec: String::new(), + design: DESIGN.into(), + repo_tasks: vec![], + fix: None, + } +} + +#[test] +fn the_plan_check_reads_items_not_evidence_and_says_each_gap_once() { + let gaps = plan_shape::plan_gaps(&plan(), TICKET, true, &[]); + let all = gaps.join("\n"); + // The ticket's own ask is never an out-of-scope mark, and a lookup's + // record is never an item. + assert!(!all.contains("A task names `FAQPage`"), "{all}"); + assert!(!all.contains("(\"Looked up\")"), "{all}"); + assert!(!all.contains("\"No lookup settles"), "{all}"); + // "when" and "page" tell no item apart from a criterion. + assert!(!all.contains("acceptance criterion asks for it"), "{all}"); + // Each gap once. + for g in &gaps { + assert_eq!(gaps.iter().filter(|x| *x == g).count(), 1, "{g}"); + } +} + +#[test] +fn the_ledger_kept_on_the_run_holds_the_items_and_the_ticket_names_stay_in() { + let mut l = Ledger::from_ticket_and_plan(&[], "", DESIGN, TASKS); + l.named_by_ticket(TICKET); + let items: Vec<&str> = l.entries.iter().map(|e| e.item.as_str()).collect(); + assert!( + !items.iter().any(|i| i.starts_with("Looked up")), + "{items:?}" + ); + assert!( + !items.iter().any(|i| i.starts_with("No lookup")), + "{items:?}" + ); + assert!(!items.iter().any(|i| i.contains("**")), "{items:?}"); + assert!( + items.contains(&"Merging the structured data of several blocks on one page"), + "{items:?}" + ); + for e in l.outs() { + assert!( + !e.marks.iter().any(|m| m.eq_ignore_ascii_case("FAQPage")), + "{e:?}" + ); + } +} + +#[test] +fn a_gap_found_on_five_task_lines_is_one_open_gap() { + let mut d = FixDecision::default(); + let line = "A task names `X`, which `## Out of scope` leaves out (\"Y\").".to_string(); + d.add_gaps(vec![line.clone(); 5]); + d.add_gaps(vec![line.clone(), "Another gap.".to_string()]); + assert_eq!(d.open_gaps, vec![line, "Another gap.".to_string()]); +} + +/// The plan check's assembly takes its gaps through the one place that +/// says each once. +#[test] +fn the_plan_check_adds_its_gaps_through_the_one_place() { + let src = include_str!("../plan.rs"); + assert!( + !src.contains("d.open_gaps.extend("), + "every gap goes through add_gaps" + ); + assert!(src.contains("common::scope_ledger::unique(left)")); + let habits = include_str!("../habits.rs"); + assert!(!habits.contains("d.open_gaps.extend(")); +} diff --git a/services/worker/src/passes/incidents/df_working_alternative_is_code.rs b/services/worker/src/passes/incidents/df_working_alternative_is_code.rs new file mode 100644 index 000000000..1d9cb8635 --- /dev/null +++ b/services/worker/src/passes/incidents/df_working_alternative_is_code.rs @@ -0,0 +1,178 @@ +//! df. A ticket said a camp card showed a broken image: the page used an +//! older image address that returned an error, while the address the +//! reporter expected was stored in our database. The trace found it all: +//! the camp's class record in the source system holds the broken address, +//! a second source record of the same kind (its league) holds a working +//! one, and our pipeline gives the class's own image priority, so the +//! broken one is stored on the class and rendered. A thousand other +//! classes carried addresses of the same kind. The run decided the fix is +//! outside the code (edit the one source record), and a later run of the +//! unchanged ticket stopped on that earlier verdict: "No new pull request: +//! the ticket is unchanged since CoderHelm learned the fix is outside the +//! code". A careful engineer makes the pipeline fall back to the working +//! image, for every record. +//! +//! Guarantee: a broken source value that our code chooses over a working +//! one in its reach is a code fix. When a decision says `outside_code` and +//! its own trace shows a layer holding a working value of the same kind as +//! a wrong layer, and a layer that is code in one of our repositories, the +//! decision goes back to the planner to fix that code +//! (`fix_location::working_alternative`, read by `fix_location::gaps`), +//! and the planner's guidance says so. An earlier "outside the code" +//! conclusion is judged again under the same rule before it can stop a +//! plan (`TicketHistory::guard`). + +use crate::passes::fix_location::{ + self, FixDecision, FixEvidence, FixLocation, Layer, OutsideChange, Producer, Route, +}; +use crate::passes::ticket_history::{Guard, PriorRun, TicketHistory}; +use crate::passes::triage::TicketIntent; + +fn layer(layer: &str, where_: &str, shows: &str, state: &str) -> Layer { + Layer { + layer: layer.into(), + where_: where_.into(), + shows: shows.into(), + state: state.into(), + } +} + +/// The decision the run reached, as its trace recorded it. +fn outside_decision() -> FixDecision { + FixDecision { + fix_location: FixLocation::OutsideCode, + cause: "The class record's own image address returns an error, and the pipeline gives \ + the class's image priority over its league's." + .into(), + intent: TicketIntent::Bug, + evidence: FixEvidence { + looked_up: vec!["[prod database] the class and its group".into()], + data_shows: "The class holds the broken address; the league holds a working one." + .into(), + basis: "data".into(), + producer: Producer { + kind: "source".into(), + where_: "booking system, class record 1001: image address returns 502".into(), + }, + scope: "One class confirmed; 1013 active classes carry addresses of that kind.".into(), + layers: vec![ + layer( + "source (class record)", + "booking system, raw copy in the warehouse", + "image = old-bucket/a.jpg (the image proxy returns 502)", + "wrong", + ), + layer( + "source (league record)", + "booking system, raw copy in the warehouse", + "image = files-bucket/b.jpg (200)", + "ok", + ), + layer( + "pipeline", + "acme/pipelines:dags/schedule_pipeline.py:1919", + "copies the class's own image when set, per its rule", + "ok", + ), + layer( + "app database", + "class table", + "group files-bucket/b.jpg; class old-bucket/a.jpg", + "wrong", + ), + layer( + "page", + "acme/web via the schedule API", + "renders old-bucket/a.jpg", + "wrong", + ), + ], + ..Default::default() + }, + outside_change: Some(OutsideChange { + system: "the booking system".into(), + change: "Replace the class record's image with a working one".into(), + ..Default::default() + }), + ..Default::default() + } +} + +#[test] +fn a_broken_source_value_with_a_working_one_in_reach_goes_back_as_a_code_fix() { + let d = outside_decision(); + let gaps = fix_location::gaps(Some(&d), true, 6, &[]); + let all = gaps.join("\n"); + assert!(all.contains("working value in reach"), "{all}"); + assert!( + all.contains("acme/pipelines:dags/schedule_pipeline.py:1919"), + "{all}" + ); + assert!(all.contains("fall back to"), "{all}"); + // The same trace decided as a code fix stands. + let mut code = d.clone(); + code.fix_location = FixLocation::Code; + assert!(fix_location::working_alternative(&code).is_some()); + assert!(!fix_location::gaps(Some(&code), true, 6, &[]) + .join("\n") + .contains("working value in reach")); +} + +#[test] +fn a_wrong_source_with_no_working_value_in_reach_stays_outside() { + let mut d = outside_decision(); + // No other record of that kind holds a working value: the source + // record is the only place to fix. + d.evidence.layers.remove(1); + assert!(fix_location::working_alternative(&d).is_none()); + assert!(fix_location::gaps(Some(&d), true, 6, &[]).is_empty()); +} + +#[test] +fn the_planner_is_told_a_working_alternative_is_a_code_fix() { + let g = fix_location::planner_guidance(TicketIntent::Bug); + assert!( + g.contains("prefer or fall back to the working value"), + "{g}" + ); +} + +/// The later run of the unchanged ticket: the earlier verdict is judged +/// again and no longer stops the plan. +#[test] +fn an_earlier_outside_verdict_is_judged_again_before_it_stops_a_plan() { + let earlier = PriorRun { + run_id: "r1".into(), + status: fix_location::STATUS_OUTSIDE.into(), + fix_location: "outside_code".into(), + fix_decision: Some(outside_decision()), + context_hash: "h1".into(), + ..Default::default() + }; + let history = TicketHistory { + runs: vec![earlier.clone()], + ..Default::default() + }; + let mut now = outside_decision(); + now.fix_location = FixLocation::Code; + now.outside_change = None; + assert_eq!(fix_location::route(Some(&now)), Route::Code); + assert!( + matches!(history.guard(Some(&now), "h1"), Guard::Proceed), + "an earlier verdict whose trace shows a working value stops nothing" + ); + // A verdict with no working value in reach still holds an unchanged + // ticket. + let mut held = earlier; + let mut d = outside_decision(); + d.evidence.layers.remove(1); + held.fix_decision = Some(d); + let history = TicketHistory { + runs: vec![held], + ..Default::default() + }; + assert!(matches!( + history.guard(Some(&now), "h1"), + Guard::Stop { .. } + )); +} diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 8b3a4ab68..554a38f1c 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -1463,7 +1463,7 @@ Then the ```fix_location.json block described above."#, ) .await; if let Some(d) = files.fix.as_mut() { - d.open_gaps.extend(left); + d.add_gaps(left); } } } @@ -1479,7 +1479,7 @@ Then the ```fix_location.json block described above."#, ) .await; if let Some(d) = files.fix.as_mut() { - d.open_gaps.extend(left); + d.add_gaps(left); } } } @@ -1508,7 +1508,7 @@ Then the ```fix_location.json block described above."#, ) .await; if let Some(d) = files.fix.as_mut() { - d.open_gaps.extend(left); + d.add_gaps(left); } } } @@ -1534,6 +1534,8 @@ Then the ```fix_location.json block described above."#, reproducer.can_run(), can_look_up, )); + // Each check reads line by line: one finding is said once. + let left = common::scope_ledger::unique(left); 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( @@ -1544,7 +1546,7 @@ Then the ```fix_location.json block described above."#, ) .await; if let Some(d) = files.fix.as_mut() { - d.open_gaps.extend(left); + d.add_gaps(left); } } } @@ -1608,7 +1610,7 @@ Then the ```fix_location.json block described above."#, ) .await; if let Some(d) = files.fix.as_mut() { - d.open_gaps.extend(lines); + d.add_gaps(lines); } } } diff --git a/services/worker/src/passes/plan_shape.rs b/services/worker/src/passes/plan_shape.rs index a188a1fa4..055dbea9a 100644 --- a/services/worker/src/passes/plan_shape.rs +++ b/services/worker/src/passes/plan_shape.rs @@ -351,13 +351,14 @@ pub fn plan_gaps( } // Scope decided once: no question left open, a reason for each item, no // task naming an item left out, no open-ended task. - out.extend(common::scope_ledger::decision_gaps( + out.extend(common::scope_ledger::decision_gaps_for( &files.proposal, &files.design, &files.tasks, &super::stop_judge::acceptance(ticket), + ticket, )); - out + common::scope_ledger::unique(out) } /// What the plan's criteria map misses (`common::e2e_proof::map_gaps`): diff --git a/services/worker/src/passes/scope_ledger.rs b/services/worker/src/passes/scope_ledger.rs index 02c9fe86e..39218e054 100644 --- a/services/worker/src/passes/scope_ledger.rs +++ b/services/worker/src/passes/scope_ledger.rs @@ -82,9 +82,11 @@ pub(crate) async fn load_or_seed( &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); + // What the ticket names, and what people already answered or + // commented, is in scope from the start: the plan never writes the + // ticket's own ask or a person's as out of scope. + let mut moved = l.named_by_ticket(&format!("{}\n{}", msg.title, msg.body)); + moved.extend(l.take_people(people)); save(state, team_id, run_id, &l).await; if !moved.is_empty() { super::add_progress_note( diff --git a/services/worker/src/passes/ticket_history.rs b/services/worker/src/passes/ticket_history.rs index e6de4055c..bae80e7af 100644 --- a/services/worker/src/passes/ticket_history.rs +++ b/services/worker/src/passes/ticket_history.rs @@ -494,7 +494,13 @@ impl TicketHistory { return Guard::Proceed; } let closed = self.closed_unmerged(); - if let Some(c) = self.outside_conclusion() { + // An earlier "outside the code" conclusion is judged again under + // today's rules: one whose own trace shows a working value our code + // passes over was a code fix all along, and never stops a plan. + let conclusion = self + .outside_conclusion() + .filter(|c| fix_location::working_alternative(&c.decision).is_none()); + if let Some(c) = conclusion { let unchanged = c.context_hash.is_empty() || c.context_hash == current_hash; if unchanged || !answered { let mut d = c.decision;