diff --git a/docs/incidents/rv_reviewer_reads_the_merge_base.md b/docs/incidents/rv_reviewer_reads_the_merge_base.md new file mode 100644 index 000000000..3e0cffbb1 --- /dev/null +++ b/docs/incidents/rv_reviewer_reads_the_merge_base.md @@ -0,0 +1,20 @@ +# rv. `rv_reviewer_reads_the_merge_base` + +**What happened:** The reviewer got four things wrong on a vendor-portal pull request and on a CI script's. + +- **The base merge:** after the base branch was merged into the pull request, the re-review read the diff from the commit it had approved. That diff carried a drawer component another pull request had already merged, and the review called it an unrelated change. Against the merge base the pull request changed 8 files, and the drawer wasn't one of them. +- **The passing run:** the preview's end-to-end run exercised the vendor's test ids against the live portal and passed. The review still blocked on "selectors no probe observed", because it only read probe records committed in the repository. +- **The red check:** the end-to-end check was red on the pull request and on the base branch. The review was told only the check's name, and it wrote that an unrelated phone-pricing test was "broken on main". The failing test was the camp-selection test in the spec the pull request changed. It failed because the vendor had opened next year's registration. +- **The missing test:** on the CI script's pull request the review rightly asked for a test, and the run handed it back. A stub of the cloud command on PATH and a fixture of its answer were all the test needed. + +**The guarantee:** + +- **What a pull request changes:** its merge-base diff. A re-review covers only the files whose own change moved since the reviewed commit. A finding that calls a file outside that diff unrelated or out of scope is dropped. +- **A passing run is a record:** a passing end-to-end run on the head, whose report shows the test ids, counts as a probe record of them. +- **The reviewer probes:** for ids nothing observed, the reviewer runs the probe itself. + - Ids the page has clear the gap. + - Ids the page lacks are a required finding that quotes the probe. + - A probe that couldn't run is a note with the reason, never a block. +- **Red checks, test by test:** a red end-to-end check is read test by test, from each failing test's own error. Tests in specs the change touches come first. A check is never the base branch's by its name. +- **Blame and reverts:** a sentence that blames the base branch for a test, or calls it flaky or pre-existing, is held unless that test fails on the base branch's head too. If it does and its spec is one the change touches, the fix belongs on this branch, and the sentence says so. Asking to revert part of the change is held unless the test passes on the base branch's head. +- **Tests are the coder's work:** on CoderHelm's own pull request, a request for a test always goes to the coder, whatever made it a note. A request about a script comes with how to test it: stub commands on PATH, fixtures, and running the script itself. diff --git a/services/worker/src/passes/e2e_reads.rs b/services/worker/src/passes/e2e_reads.rs index f3b60d950..24570ca10 100644 --- a/services/worker/src/passes/e2e_reads.rs +++ b/services/worker/src/passes/e2e_reads.rs @@ -252,6 +252,73 @@ pub async fn read(cx: &Ctx<'_>, head: &str) -> Option { None } +/// A passing end-to-end run on the head and the report it published. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PassingRun { + /// How it is known to have passed (check runs, the comment). + pub how: String, + /// The published report, when the end-to-end comment links one. + pub report: Option, +} + +/// Whether the head's end-to-end run passed, from its check runs (`checks`) +/// and the pull request's end-to-end comments (`comments`, oldest first): +/// none of its checks failed or is running, and a check or the comment on +/// the head says it passed. The comment's report link comes with it. +pub fn passing_run(checks: &[Value], comments: &[Value], head: &str) -> Option { + let by_checks = checks_verdict(checks); + if matches!(by_checks, Some(Verdict::Failed(_)) | Some(Verdict::Running)) { + return None; + } + let comment = comments + .iter() + .rev() + .filter_map(|c| comment_verdict(c["body"].as_str().unwrap_or(""))) + .find(|c| on_head(c, head)); + if comment.as_ref().and_then(|c| c.failed).unwrap_or(0) > 0 { + return None; + } + let report = comment.as_ref().and_then(|c| c.report.clone()); + match (by_checks, comment) { + (Some(Verdict::Passed(how)), _) => Some(PassingRun { how, report }), + (None, Some(c)) if c.passed.unwrap_or(0) > 0 => Some(PassingRun { + how: format!( + "{} end-to-end test(s) passed (the end-to-end comment on the pull request)", + c.passed.unwrap_or(0) + ), + report, + }), + _ => None, + } +} + +/// The test ids (`ids`) a passing run's published report shows: each one +/// the report's text holds was exercised by a test that passed. Read with +/// the page check, so only a host the team's sites allow. +pub async fn report_shows( + state: &crate::WorkerState, + github: &crate::clients::github::GitHubClient, + web: &super::web_check::WebCheck, + report: &str, + ids: &[String], +) -> Vec { + if ids.is_empty() { + return Vec::new(); + } + let Ok(ck) = web.verify_find(state, github, report, ids).await else { + return Vec::new(); + }; + if ck.status() != Some(200) { + return Vec::new(); + } + ck.found + .iter() + .filter(|(_, hits)| !hits.is_empty()) + .map(|(id, _)| id.clone()) + .filter(|id| ids.contains(id)) + .collect() +} + /// The published report's verdict, read with the page check (only a host /// the team's sites allow). async fn report(cx: &Ctx<'_>, url: &str) -> Option { diff --git a/services/worker/src/passes/incidents/rv_reviewer_reads_the_merge_base.rs b/services/worker/src/passes/incidents/rv_reviewer_reads_the_merge_base.rs new file mode 100644 index 000000000..982094470 --- /dev/null +++ b/services/worker/src/passes/incidents/rv_reviewer_reads_the_merge_base.rs @@ -0,0 +1,294 @@ +//! rv. A vendor-portal pull request, and a CI script's, as the reviewer saw +//! them. +//! +//! - After the base branch was merged into the portal pull request, the +//! review read the diff from the commit it had approved. That diff +//! carried a drawer component another pull request had already merged, +//! and the review called it "an unrelated change". Against the merge +//! base the pull request changed 8 files and the drawer wasn't one. +//! - The preview's end-to-end run exercised the vendor's test ids against +//! the live portal and passed. The review still blocked on "selectors no +//! probe observed", because it only read committed probe records. +//! - The end-to-end check was red on the pull request and on the base +//! branch. The review was told only the check's name, and wrote that an +//! unrelated phone-pricing test was "broken on main". The failing test was +//! the camp-selection test in the spec the pull request changed, red +//! because the vendor had opened next year's registration. +//! - On the CI script's pull request the review asked for a test of the +//! script and the run handed it back, though a stub of the cloud command +//! on PATH and a fixture of its answer were all it needed. +//! +//! Guarantee: a re-review covers only the pull request's own change since +//! the reviewed commit (`review_scope::own_files_moved`, `own_part_of`), and +//! a finding calling a file outside the merge-base diff unrelated is dropped +//! (`drop_outside_claims`). A passing end-to-end run whose report shows the +//! ids is a probe record (`e2e_reads::passing_run`, +//! `review_probe::from_report`), and what is still unobserved the reviewer +//! probes itself and decides from the record (`review_probe::decide`). A red +//! check is read test by test (`review_ci::CiCompare`), and a blame or +//! revert sentence it doesn't back is held (`review_ci::hold`). On +//! CoderHelm's own pull request a request for a test is the coder's work, +//! with how to test a script (`own_review::required`, `test_how`). + +use serde_json::{json, Value}; + +use crate::passes::review_agent::Finding; +use crate::passes::{e2e_reads, own_review, review_ci, review_probe, review_scope}; + +const PORTAL: &str = "https://portal.example-vendor.io/org/7/portal/42"; + +fn file(name: &str, patch: &str) -> Value { + json!({"filename": name, "status": "modified", "patch": patch}) +} + +/// The pull request's own change: the embed, its test and the portal spec. +fn own(embed_patch: &str) -> Vec { + vec![ + file( + "apps/web/src/components/blocks/portal-embed.tsx", + embed_patch, + ), + file( + "apps/web/src/test/components/portal-embed.test.tsx", + "@@ -3,1 +3,1 @@\n-expect(link).toBeVisible();\n+expect(link).toBeNull();", + ), + file( + "e2e/tests/browse/portal.spec.ts", + "@@ -20,1 +20,1 @@\n-await expect(newTab).toBeVisible();\n+await expect(newTab).toHaveCount(0);", + ), + ] +} + +const EMBED_AT_APPROVAL: &str = + "@@ -10,2 +10,1 @@\n-{linkLabel}\n-\n+"; +const EMBED_NOW: &str = "@@ -10,1 +10,0 @@\n-{linkLabel}"; + +#[test] +fn a_re_review_after_a_base_merge_covers_only_the_prs_own_change() { + let at_approval = json!({"status": "ahead", "files": own(EMBED_AT_APPROVAL)}); + let now = json!({"status": "ahead", "files": own(EMBED_NOW)}); + // From the approved commit to the head: the PR's own fix, and the + // drawer the base branch brought in with the merge. + let since = json!({"status": "ahead", "files": [ + file("apps/web/src/components/blocks/portal-embed.tsx", "@@ -10,1 +10,1 @@\n-\n+"), + file("apps/web/src/components/ui/drawer.tsx", "@@ -60,1 +60,2 @@\n \n+<span className=\"sr-only\">Drawer</span>"), + ]}); + assert!(!review_scope::same_own_change(&at_approval, &now)); + let moved = review_scope::own_files_moved(&at_approval, &now); + assert_eq!( + moved, + vec!["apps/web/src/components/blocks/portal-embed.tsx"] + ); + let reviewed = review_scope::own_part_of(&since, &moved); + let paths = review_scope::compare_paths(&reviewed); + assert_eq!( + paths, + vec!["apps/web/src/components/blocks/portal-embed.tsx"] + ); + assert!(!paths.iter().any(|p| p.ends_with("drawer.tsx"))); + assert_eq!(reviewed["status"], "ahead"); + + // And a finding that calls the drawer this PR's unrelated change is + // dropped; one about a caller the change breaks is kept. + let pr_files = review_scope::compare_paths(&now); + let mut findings = vec![ + Finding { + file: "apps/web/src/components/ui/drawer.tsx".into(), + title: "Unrelated change to the drawer's title".into(), + body: "This file is out of scope for the ticket; revert it.".into(), + severity: "high".into(), + ..Default::default() + }, + Finding { + file: "apps/web/src/lib/routing/content-renderers.tsx".into(), + title: "Still passes the removed linkLabel prop".into(), + body: "The renderer passes `linkLabel`, which the embed no longer takes.".into(), + severity: "high".into(), + ..Default::default() + }, + ]; + let dropped = review_scope::drop_outside_claims(&mut findings, &pr_files); + assert_eq!(dropped.len(), 1); + assert_eq!(findings.len(), 1); + assert!(findings[0].file.ends_with("content-renderers.tsx")); +} + +#[test] +fn the_reviewer_wires_the_merge_base_scope_in_both_re_review_paths() { + let src = include_str!("../review_pr.rs"); + assert_eq!( + src.matches("review_scope::own_part_of(&since, &moved)") + .count(), + 2 + ); + assert!(src.contains("review_scope::drop_outside_claims(&mut findings, &changed_list)")); +} + +const SPEC: &str = "import { test, expect } from '@playwright/test';\nconst PORTAL = 'https://portal.example-vendor.io/org/7/portal/42';\ntest('choosing a camp adds it to the cart', async ({ page }) => {\n const frame = page.frameLocator('iframe');\n await frame.getByTestId('segment-option').first().click();\n await expect(frame.getByTestId('cart-preview-subtotal')).not.toHaveText('$0');\n});\n"; + +fn gaps() -> Vec<common::e2e::probe::Unprobed> { + let files = vec![( + "e2e/tests/browse/portal.spec.ts".to_string(), + SPEC.to_string(), + SPEC.to_string(), + )]; + common::e2e::probe::unprobed(&files, &[], &["acme.example".into()]) +} + +#[test] +fn a_passing_end_to_end_run_on_the_head_is_a_record_of_the_ids_it_exercised() { + let g = gaps(); + assert_eq!(g.len(), 1, "no committed probe: the gate finds the ids"); + let head = "eb32df14230678e5c7c1ff2c0929020ae6181dd8"; + let checks = vec![ + json!({"name": "Lint", "status": "completed", "conclusion": "success"}), + json!({"name": "E2E:camps / Playwright", "status": "completed", "conclusion": "success"}), + ]; + let comments = vec![ + json!({"body": "## Playwright E2E results for eb32df1\n\n12 passed, 0 failed\n\n[Full report](https://reports.acme.example/pr-1/index.html)"}), + ]; + let run = e2e_reads::passing_run(&checks, &comments, head).expect("a passing run"); + assert_eq!( + run.report.as_deref(), + Some("https://reports.acme.example/pr-1/index.html") + ); + // The report's text shows both ids (`report_shows`): they are observed. + let found = vec![ + "cart-preview-subtotal".to_string(), + "segment-option".to_string(), + ]; + let record = + review_probe::from_report(&g[0].origin, run.report.as_deref().unwrap(), head, &found); + let files = vec![( + "e2e/tests/browse/portal.spec.ts".to_string(), + SPEC.to_string(), + SPEC.to_string(), + )]; + assert!(common::e2e::probe::unprobed(&files, &[record], &["acme.example".into()]).is_empty()); + // A red or running run is no record. + let red = vec![ + json!({"name": "E2E:camps / Playwright", "status": "completed", "conclusion": "failure"}), + ]; + assert_eq!(e2e_reads::passing_run(&red, &comments, head), None); +} + +#[test] +fn what_is_still_unobserved_the_reviewer_probes_and_decides_from_the_record() { + let g = &gaps()[0]; + assert_eq!( + review_probe::page_url(SPEC, &g.origin).as_deref(), + Some(PORTAL) + ); + // The page has the ids: no finding. + let seen = common::e2e::probe::ProbeRecord { + origin: g.origin.clone(), + url: PORTAL.into(), + testids: vec!["segment-option".into(), "cart-preview-subtotal".into()], + ..Default::default() + }; + assert!(review_probe::decide(g, SPEC, SPEC, &review_probe::Probed::Ran(seen)).is_none()); + // The page lacks one: a verified, required finding quoting the record. + let partial = common::e2e::probe::ProbeRecord { + origin: g.origin.clone(), + url: PORTAL.into(), + testids: vec!["segment-option".into()], + ..Default::default() + }; + let f = review_probe::decide(g, SPEC, SPEC, &review_probe::Probed::Ran(partial)).unwrap(); + assert!(f.required.is_some() && f.body.contains("`cart-preview-subtotal`")); + // The probe couldn't run: a note, never a block on the reviewer's own + // missing look; on CoderHelm's own PR it is still the coder's work. + let f = review_probe::decide( + g, + SPEC, + SPEC, + &review_probe::Probed::NotRun("the sandbox couldn't run the probe".into()), + ) + .unwrap(); + assert!(f.required.is_none() && !f.holds_merge()); + assert_eq!(own_review::required(&[f], &[]).len(), 1); +} + +#[test] +fn the_reviewer_settles_probe_gaps_before_they_are_findings() { + let src = include_str!("../review_pr.rs"); + let gate = src.find("async fn probe_gaps(").unwrap(); + let end = src.find("async fn smallest_change_gaps(").unwrap(); + let body = &src[gate..end]; + assert!(body.contains("e2e_reads::passing_run(")); + assert!(body.contains("super::web_check::PROBE_TOOL")); + assert!(body.contains("review_probe::decide(")); + assert!(!body.contains("review_rules::probe_findings(")); +} + +const HEAD_NOTES: &str = "\n--- E2E on preview / Playwright e2e (all tests) ---\nfailure: e2e/tests/browse/portal.spec.ts:120: 1) [chromium] › browse/portal.spec.ts:120:7 › Portal › selecting a camp adds it to the cart while registration is open ──\n\n Error: Choosing \"Mini-Camp (AM)\" did not add it to the order summary\n expect(locator).not.toHaveText(expected) failed\n Received: \"Subtotal$0\"\n"; + +#[test] +fn a_red_check_is_read_test_by_test_and_a_blame_it_doesnt_back_is_held() { + // Red on both heads, the same camp test (the vendor opened registration). + let base_notes = HEAD_NOTES.replace("portal.spec.ts:120", "portal.spec.ts:118"); + let base_runs = json!({"check_runs": [ + {"name": "E2E on preview / Playwright e2e (all tests)", "status": "completed", "conclusion": "failure"} + ]}); + let cmp = review_ci::CiCompare::read("eb32df1", "bd414b9", HEAD_NOTES, &base_notes, &base_runs) + .touching(vec!["e2e/tests/browse/portal.spec.ts".into()]); + let t = &cmp.head_failing[0]; + assert!(t.error.contains("did not add it to the order summary")); + assert!(cmp.on_base_too(t) && cmp.in_touched_spec(t)); + // The check is never the base's by its name: only the test is. + assert_eq!( + cmp.base_failing(), + vec!["Portal › selecting a camp adds it to the cart while registration is open"] + ); + let ctx = cmp.context(); + assert!(ctx.contains("(a spec this change touches)")); + assert!(ctx.contains("did not add it to the order summary")); + + let mut summary = + "The phone pricing test is broken on main, so the red e2e check isn't this change's. \ + Revert the portal spec to the last green head to get CI green." + .to_string(); + let mut findings = vec![Finding { + file: "e2e/tests/browse/portal.spec.ts".into(), + title: "Camp selection test fails".into(), + body: "selecting a camp adds it to the cart while registration is open fails, and it's pre-existing on main.".into(), + caused_by_diff: Some(false), + ..Default::default() + }]; + let held = review_ci::hold(&mut findings, &mut summary, &cmp); + assert_eq!(held, 3); + assert!(summary.starts_with(review_ci::BLAME_HELD)); + assert!(summary.contains(review_ci::REVERT_HELD)); + assert!(!summary.contains("phone pricing")); + // The camp test fails on the base too, but it is in the spec this PR + // changes: its fix belongs on this branch, never "pre-existing". + assert!(findings[0].body.contains(review_ci::TOUCHED_HELD)); + assert_eq!(findings[0].caused_by_diff, None); +} + +#[test] +fn the_reviewer_reads_red_checks_through_the_comparison() { + let src = include_str!("../review_pr.rs"); + assert!(src.contains("review_ci::CiCompare::read(")); + assert!(src.contains("let base_failing: Vec<String> = ci_compare.base_failing();")); + assert!(src.contains("review_ci::hold(&mut findings, &mut output.summary, &ci_compare)")); +} + +#[test] +fn a_request_for_a_test_of_a_ci_script_is_the_coders_work_with_how() { + let tracked = Finding { + file: ".github/scripts/check-waf-rules.sh".into(), + title: "No test covers the new rule-count check".into(), + body: "The script now fails when describe-rules returns no rules, but no test covers it." + .into(), + category: "tests".into(), + severity: "medium".into(), + tracked: Some(true), + note_only: Some("A note, not a block: the PR already tracks this as a follow-up.".into()), + ..Default::default() + }; + let items = own_review::required(&[tracked], &[]); + assert_eq!(items.len(), 1, "a tracked test ask still reaches the coder"); + assert!(items[0].contains("stub commands first on PATH")); + assert!(items[0].contains("fixture")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 7c319da6d..d3b152d2b 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1372,6 +1372,7 @@ mod review; pub mod review_actions; pub mod review_activity; pub mod review_agent; +pub mod review_ci; pub mod review_configs; #[cfg(test)] mod review_eval; @@ -1383,6 +1384,7 @@ pub mod review_policy; #[cfg(test)] mod review_policy_eval; pub mod review_pr; +pub mod review_probe; pub mod review_reminder; pub mod review_risk; pub mod review_rules; @@ -10060,6 +10062,10 @@ Every change that adds or changes behavior must ship with tests in this same bra - New behavior (a feature, endpoint, UI state, option, job): add tests that exercise it.\n\ - Changed or fixed behavior: update the existing tests that cover that code so they assert the \ new behavior. A bug fix gets a test that fails without the fix.\n\ +- Shell scripts, CI steps and workflow helpers are behavior too: test the script itself with \ +stub commands first on PATH (a fake `aws`, `gh` or `curl` that prints a fixture and records its \ +arguments) and fixtures beside the test, then assert on its output, exit code and the recorded \ +calls. Never hand such a test back as something only a person can run.\n\ - Follow the repo's own testing conventions exactly: framework, where tests live and how they're \ named, helpers and fixtures, how mocks are done, which command runs them. They are in AGENTS.md / \ CLAUDE.md and in nested ones next to the code (e.g. `e2e/CLAUDE.md`, a package's CLAUDE.md): read \ diff --git a/services/worker/src/passes/own_review.rs b/services/worker/src/passes/own_review.rs index 5177bc13a..90e196ce4 100644 --- a/services/worker/src/passes/own_review.rs +++ b/services/worker/src/passes/own_review.rs @@ -8,7 +8,9 @@ //! On CoderHelm's own PRs every finding that isn't pure style (a //! preference the reviewer inferred: wording, naming, layout, see //! [`super::review_severity::pure_style`]) is work the -//! run does itself: +//! run does itself. A finding that asks for a test is work whatever made it +//! a note (tracked, a question, the stop judge), and one about a script +//! carries how to test it ([`test_how`]): //! //! - The review lists them at the top of the description under "Open review //! findings" ([`section`]). While the section is there the PR stays a @@ -62,15 +64,45 @@ pub fn required(findings: &[Finding], held_late: &[Finding]) -> Vec<String> { .filter(|f| { f.holds_merge() || about_description(f) + || super::review_severity::asks_for_a_test(f) || (f.note_only.is_none() && f.evidence() != Evidence::Question && !super::review_severity::pure_style(f)) }) .chain(held_late.iter()) - .map(line) + .map(|f| match test_how(f) { + Some(how) if super::review_severity::asks_for_a_test(f) => { + format!("{} ({how})", line(f)) + } + _ => line(f), + }) .collect() } +/// How the coder tests a script CI or a person runs (a shell script, a +/// workflow, a CI helper), for a finding that asks for a test of one. A +/// review once asked for a test of a CI script that reads cloud rules, and +/// the run handed it back: the test needed only a stub of the cloud +/// command on PATH and a fixture of its answer. +pub fn test_how(f: &Finding) -> Option<&'static str> { + let path = f.file.trim().to_ascii_lowercase(); + let script = path.ends_with(".sh") + || path.ends_with(".bash") + || path.starts_with(".github/") + || path.starts_with("scripts/") + || path.contains("/scripts/") + || path.contains("/bin/") + || path.ends_with("makefile") + || path.ends_with("justfile"); + script.then_some(SCRIPT_TEST) +} + +/// [`test_how`]'s instruction. +pub const SCRIPT_TEST: &str = "test the script itself: put stub commands first on PATH (a \ + fake `aws`, `gh` or `curl` that prints a fixture and records its arguments), keep the \ + fixtures beside the test, run the script against them in the repository's test runner, \ + and assert on its output, exit code and the stub's recorded calls"; + /// A finding that says the pull request's description does not match the /// code: it names the description and says it is behind. Never optional /// and never a person's to fix, whatever its severity: the description is diff --git a/services/worker/src/passes/review_ci.rs b/services/worker/src/passes/review_ci.rs new file mode 100644 index 000000000..3a1ed408b --- /dev/null +++ b/services/worker/src/passes/review_ci.rs @@ -0,0 +1,573 @@ +//! The reviewer reads a red check test by test, from the failing test's own +//! error, before it says anything about whose failure it is. +//! +//! A vendor portal's end-to-end check was red on a pull request and on the +//! base branch. The reviewer was told only "this check fails on the base +//! branch too" by the check's name, and wrote that an unrelated +//! phone-pricing test was "broken on main". The test that failed was the +//! camp-selection test in the spec the pull request changed, and it failed +//! because the vendor had opened next year's registration: an outside +//! change, this branch's to fix. +//! +//! The rules: +//! +//! - [`CiCompare`] holds the failing tests on the head (name, spec, the +//! first line of their error, from the failing checks' annotations) and +//! the failing tests on the base branch's head. A check the base fails too +//! is the base's by name only when it isn't an end-to-end check; an +//! end-to-end check is compared test by test ([`CiCompare::base_failing`]). +//! - The prompt lists the failing tests, the ones in specs the change +//! touches first, each with its own error, and which also fail on the +//! base ([`CiCompare::context`]). +//! - [`hold`] replaces every sentence of a finding or the summary that +//! blames the base branch, flakiness or something outside the change for a +//! failing test, unless the test fails on the base's head too; and every +//! sentence that asks to revert part of the change to make a check pass, +//! unless the test passes on the base's head and fails on this one. It is +//! the reviewer's side of the coder's revert gate and blame hold +//! (`ci_repro`): the reviewer never asserts what those would refuse. + +use super::review_agent::Finding; + +/// One failing test, from a failing check's annotations. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FailingTest { + pub check: String, + /// The annotated file (the spec), when there is one. + pub spec: String, + /// The test's title (`describe › test`). + pub name: String, + /// The first line of its error. + pub error: String, +} + +impl FailingTest { + /// The last part of its title (the test itself, without its describe). + fn short(&self) -> &str { + self.name.rsplit(" › ").next().unwrap_or(&self.name).trim() + } + + /// Whether `text` names this test. + fn named_in(&self, text: &str) -> bool { + let t = text.to_ascii_lowercase(); + let short = self.short().to_ascii_lowercase(); + (short.len() >= 8 && t.contains(&short)) + || (!self.name.is_empty() && t.contains(&self.name.to_ascii_lowercase())) + } +} + +/// The failing tests in a GitHub annotations listing +/// (`GitHubClient::get_check_run_annotations`: `--- check ---` headers, then +/// `level: path:line: message` with the message's later lines after it). +pub fn parse_annotations(text: &str) -> Vec<FailingTest> { + let start = regex::Regex::new(r"^(failure|error|warning|notice): (\S*):(\d+): ?(.*)$").ok(); + let mut out: Vec<FailingTest> = Vec::new(); + let mut check = String::new(); + // The annotation being read: (check, path, level, message lines). + let mut open: Option<(String, String, String, Vec<String>)> = None; + let close = |open: &mut Option<(String, String, String, Vec<String>)>, + out: &mut Vec<FailingTest>| { + if let Some((check, path, level, lines)) = open.take() { + if level != "failure" && level != "error" { + return; + } + let message = lines.join("\n"); + let name = super::outside_exec::failing_tests(&message) + .into_iter() + .next() + .or_else(|| { + let first = lines.first().map(|l| l.trim()).unwrap_or(""); + first.contains(" › ").then(|| title_of(first)) + }); + let Some(name) = name else { + return; + }; + let name = title_of(&name); + let error = lines + .iter() + .map(|l| l.trim()) + .find(|l| { + l.starts_with("Error") + || l.starts_with("expect(") + || l.contains("Timeout") + || l.starts_with("TimeoutError") + }) + .or_else(|| { + lines + .iter() + .map(|l| l.trim()) + .find(|l| !l.is_empty() && !l.contains(" › ")) + }) + .unwrap_or("") + .to_string(); + if !out.iter().any(|t| t.name == name && t.check == check) { + out.push(FailingTest { + check, + spec: path, + name, + error: common::truncate_str(&error, 240).to_string(), + }); + } + } + }; + for line in text.lines() { + let t = line.trim(); + if let Some(name) = t.strip_prefix("--- ").and_then(|r| r.strip_suffix(" ---")) { + close(&mut open, &mut out); + check = name.to_string(); + continue; + } + if let Some(c) = start.as_ref().and_then(|re| re.captures(line)) { + close(&mut open, &mut out); + open = Some(( + check.clone(), + c[2].to_string(), + c[1].to_string(), + vec![c[4].to_string()], + )); + continue; + } + if let Some((_, _, _, lines)) = open.as_mut() { + lines.push(line.to_string()); + } + } + close(&mut open, &mut out); + out +} + +/// A Playwright line's test title: what follows the spec segment +/// (`[chromium] › a.spec.ts:12:5 › Suite › test` gives `Suite › test`), +/// without its retry note and trailing rule. +fn title_of(line: &str) -> String { + let line = line + .trim() + .trim_start_matches(|c: char| c.is_ascii_digit() || c == ')' || c == ' '); + let parts: Vec<&str> = line.split(" › ").map(str::trim).collect(); + let after_spec = parts + .iter() + .rposition(|p| p.contains(".spec.") || p.contains(".test.") || p.starts_with('[')) + .map(|i| &parts[i + 1..]) + .unwrap_or(&parts[..]); + let title = if after_spec.is_empty() { + parts.join(" › ") + } else { + after_spec.join(" › ") + }; + title + .split(" (retry #") + .next() + .unwrap_or("") + .trim_end_matches(['─', ' ']) + .trim() + .to_string() +} + +/// A red check, test by test, on the head and on the base branch's head. +#[derive(Debug, Clone, Default)] +pub struct CiCompare { + pub head: String, + pub base: String, + /// Failing tests on the head. + pub head_failing: Vec<FailingTest>, + /// Failing tests on the base branch's head. + pub base_failing_tests: Vec<FailingTest>, + /// The base head's failing checks, by name. + pub base_failing_checks: Vec<String>, + /// Whether the base head's end-to-end checks ran to the end (so a test + /// not failing there passed there). + pub base_e2e_ran: bool, + /// The paths the pull request changes (its merge-base diff). + pub touched: Vec<String>, +} + +impl CiCompare { + /// From the head's and the base's annotations and the base's check runs. + pub fn read( + head: &str, + base: &str, + head_notes: &str, + base_notes: &str, + base_runs: &serde_json::Value, + ) -> Self { + let runs = base_runs["check_runs"] + .as_array() + .cloned() + .unwrap_or_default(); + let e2e: Vec<&serde_json::Value> = runs + .iter() + .filter(|r| super::e2e_reads::is_e2e_name(r["name"].as_str().unwrap_or(""))) + .collect(); + CiCompare { + head: head.to_string(), + base: base.to_string(), + head_failing: parse_annotations(head_notes), + base_failing_tests: parse_annotations(base_notes), + base_failing_checks: super::review_policy::failing_checks(base_runs), + base_e2e_ran: !e2e.is_empty() + && e2e.iter().all(|r| { + r["status"].as_str() == Some("completed") + && r["conclusion"].as_str() != Some("skipped") + }), + touched: Vec::new(), + } + } + + /// With the paths the pull request changes. + pub fn touching(mut self, touched: Vec<String>) -> Self { + self.touched = touched; + self + } + + /// Whether `t` is in a spec the pull request changes. + pub fn in_touched_spec(&self, t: &FailingTest) -> bool { + touches(&self.touched, &t.spec) + } + + /// Whether the base's head fails `t` too. + pub fn on_base_too(&self, t: &FailingTest) -> bool { + self.base_failing_tests.iter().any(|b| b.name == t.name) + } + + /// Whether `t` passed on the base's head and fails on this one: the + /// change made it fail. + pub fn caused_here(&self, t: &FailingTest) -> bool { + self.base_e2e_ran && !self.on_base_too(t) + } + + /// What fails on the base branch too, for the blocking policy: a + /// failing check by name when it isn't an end-to-end check, and the + /// end-to-end tests that fail on both heads by name. An end-to-end check + /// red on both is never the base's by its name alone. + pub fn base_failing(&self) -> Vec<String> { + let mut out: Vec<String> = self + .base_failing_checks + .iter() + .filter(|c| !super::e2e_reads::is_e2e_name(c)) + .cloned() + .collect(); + for t in self.head_failing.iter().filter(|t| self.on_base_too(t)) { + if !out.contains(&t.name) { + out.push(t.name.clone()); + } + } + out + } + + /// The head's failing tests, the ones in a spec the change touches + /// first. + pub fn ordered(&self) -> Vec<(&FailingTest, bool)> { + let mut out: Vec<(&FailingTest, bool)> = self + .head_failing + .iter() + .map(|t| (t, self.in_touched_spec(t))) + .collect(); + out.sort_by_key(|(_, touched)| !*touched); + out + } + + /// The reviewer's section on the red checks. + pub fn context(&self) -> String { + let short = |s: &str| s[..s.len().min(7)].to_string(); + let mut s = String::new(); + let other: Vec<&String> = self + .base_failing_checks + .iter() + .filter(|c| !super::e2e_reads::is_e2e_name(c)) + .collect(); + if !other.is_empty() { + s.push_str(&format!( + "\n## Checks failing on the base branch too ({})\n{}\nThese fail without this \ + PR's change: never block on them. Mention one as a note at most, with \ + `caused_by_diff`: false.\n", + short(&self.base), + other + .iter() + .map(|n| format!("- {n}")) + .collect::<Vec<_>>() + .join("\n") + )); + } + if self.head_failing.is_empty() { + return s; + } + s.push_str(&format!( + "\n## Failing tests on this head ({}), from their own errors\n", + short(&self.head) + )); + for (t, touched) in self.ordered() { + let mark = if touched { + " (a spec this change touches)" + } else { + "" + }; + let base = if self.on_base_too(t) { + format!("fails on the base branch's head {} too", short(&self.base)) + } else if self.base_e2e_ran { + format!("passes on the base branch's head {}", short(&self.base)) + } else { + "not compared: the base branch's run didn't finish".to_string() + }; + s.push_str(&format!( + "- `{}` in `{}`{mark}: {} ({base})\n", + t.name, + if t.spec.is_empty() { &t.check } else { &t.spec }, + if t.error.is_empty() { + "no error line in its annotation" + } else { + &t.error + } + )); + } + s.push_str(TRIAGE_RULES); + s + } +} + +/// How the reviewer reads a red check. +pub const TRIAGE_RULES: &str = "Start from the tests in specs this change touches, and name a \ + failure by the failing test and its own error above, never another test. A test that \ + fails on the base branch's head too isn't caused by this change's code; before calling it \ + pre-existing or broken on the base branch, read its error for an outside change (another \ + company's page, data, a date): then the test or the code it checks is this branch's to fix, \ + and you say so. Never ask to revert part of the change to make a check pass unless the \ + test passes on the base branch's head and fails on this one.\n"; + +fn touches(touched: &[String], spec: &str) -> bool { + let spec = spec.trim_start_matches("./"); + !spec.is_empty() + && touched + .iter() + .any(|p| p == spec || p.ends_with(&format!("/{spec}")) || spec.ends_with(p.as_str())) +} + +/// Whether `sentence` is about a failing check or test. +fn about_a_failure(s: &str) -> bool { + regex::Regex::new(r"\b(tests?|checks?|ci|e2e|end-to-end|specs?|suite|fail\w*|red|green)\b") + .map(|re| re.is_match(s)) + .unwrap_or(false) +} + +/// Whether `sentence` says a failure is the base branch's, flaky, +/// pre-existing or outside the change. +pub fn blames(sentence: &str) -> bool { + let s = sentence.to_ascii_lowercase(); + const WORDS: &[&str] = &[ + "broken on main", + "broken on the base", + "fails on main", + "failing on main", + "red on main", + "on main too", + "on main as well", + "on the base branch too", + "on the base branch as well", + "pre-existing", + "preexisting", + "already failing", + "already broken", + "already red", + "flaky", + "flake", + "not caused by this", + "isn't caused by this", + "is not caused by this", + "not this change's", + "not this pr's", + "unrelated to this change", + "unrelated to this pr", + "unrelated to the change", + "unrelated test", + "unrelated failure", + "known failure", + ]; + WORDS.iter().any(|w| s.contains(w)) && about_a_failure(&s) +} + +/// Whether `sentence` asks to revert or take out part of the change to make +/// a check pass. +pub fn asks_revert(sentence: &str) -> bool { + let s = sentence.to_ascii_lowercase(); + let revert = [ + "revert", + "roll back", + "rollback", + "back out", + "put back", + "take out", + ] + .iter() + .any(|w| s.contains(w)); + revert && about_a_failure(&s) +} + +/// What replaces a blame with no test-level comparison behind it. +pub const BLAME_HELD: &str = "Whose failure this is isn't shown: the failing test doesn't fail \ + the same way on the base branch's head."; + +/// What replaces a blame of a test in a spec the pull request changes that +/// fails on the base branch too: an outside change broke it, and its fix +/// belongs on this branch. +pub const TOUCHED_HELD: &str = "That test fails on the base branch's head too and is in a spec \ + this change touches: something outside the code changed under it, and its fix (the test, or \ + the code it checks) belongs on this branch."; + +/// What replaces a revert asked for with no comparison behind it. +pub const REVERT_HELD: &str = "Reverting part of the change isn't shown to fix the check: the \ + failing test doesn't pass on the base branch's head."; + +/// The head's failing tests a sentence names by title. +fn named<'a>(cmp: &'a CiCompare, sentence: &str) -> Vec<&'a FailingTest> { + cmp.head_failing + .iter() + .filter(|t| t.named_in(sentence)) + .collect() +} + +/// What a blame sentence may say: `None` when it is backed (it names a +/// failing test, every one it names fails on the base's head too, and none +/// is in a spec the change touches), else what replaces it. A blame that +/// names no failing test (another test, or only a check's name) is never +/// backed. +fn blame_held(cmp: &CiCompare, sentence: &str) -> Option<&'static str> { + let tests = named(cmp, sentence); + if tests.is_empty() || !tests.iter().all(|t| cmp.on_base_too(t)) { + return Some(BLAME_HELD); + } + if tests.iter().any(|t| cmp.in_touched_spec(t)) { + return Some(TOUCHED_HELD); + } + None +} + +/// Whether a revert sentence is backed: a test it names (or, when it names +/// none, every failing test) passes on the base's head and fails on this +/// one. +fn revert_backed(cmp: &CiCompare, sentence: &str) -> bool { + let tests = named(cmp, sentence); + if tests.is_empty() { + !cmp.head_failing.is_empty() && cmp.head_failing.iter().all(|t| cmp.caused_here(t)) + } else { + tests.iter().any(|t| cmp.caused_here(t)) + } +} + +/// `text` with its unbacked blame and revert sentences replaced. Returns +/// how many were. +pub fn hold_text(text: &mut String, cmp: &CiCompare) -> usize { + let mut n = 0; + let mut out = String::with_capacity(text.len()); + for (i, line) in text.split('\n').enumerate() { + if i > 0 { + out.push('\n'); + } + for sentence in sentences(line) { + let held = if blames(sentence) { + blame_held(cmp, sentence) + } else if asks_revert(sentence) && !revert_backed(cmp, sentence) { + Some(REVERT_HELD) + } else { + None + }; + match held { + Some(h) => { + n += 1; + let lead: String = sentence + .chars() + .take_while(|c| c.is_whitespace() || matches!(c, '-' | '*')) + .collect(); + let trail = if sentence.ends_with(' ') { " " } else { "" }; + out.push_str(&format!("{lead}{h}{trail}")); + } + None => out.push_str(sentence), + } + } + } + if n > 0 { + *text = out; + } + n +} + +/// A line's sentences, each with its own end and trailing space. +fn sentences(line: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut start = 0; + let b = line.as_bytes(); + for (i, c) in b.iter().enumerate() { + if matches!(c, b'.' | b'!' | b'?') && (i + 1 == b.len() || b[i + 1] == b' ') { + let end = (i + 2).min(b.len()); + out.push(&line[start..end]); + start = end; + } + } + if start < line.len() { + out.push(&line[start..]); + } + out +} + +/// Holds the findings' and the summary's unbacked blame and revert +/// sentences ([`hold_text`]). A finding that rests on such a claim (it says +/// the failure isn't the change's) no longer says it isn't the diff's. +/// Returns how many sentences were held. +pub fn hold(findings: &mut [Finding], summary: &mut String, cmp: &CiCompare) -> usize { + let mut n = hold_text(summary, cmp); + for f in findings.iter_mut() { + let title = hold_text(&mut f.title, cmp); + let body = hold_text(&mut f.body, cmp); + if title + body > 0 && f.caused_by_diff == Some(false) { + f.caused_by_diff = None; + } + n += title + body; + } + n +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const HEAD: &str = "\n--- Playwright e2e (all tests) ---\nfailure: e2e/tests/browse/portal.spec.ts:120: 1) [chromium] › browse/portal.spec.ts:120:7 › Portal › choosing a camp adds it to the cart while registration is open ──\n\n Error: Choosing a camp did not add it to the order summary\n expect(locator).not.toHaveText(expected) failed\n"; + + #[test] + fn annotations_give_each_failing_test_with_its_own_error() { + let t = parse_annotations(HEAD); + assert_eq!(t.len(), 1); + assert_eq!( + t[0].name, + "Portal › choosing a camp adds it to the cart while registration is open" + ); + assert_eq!(t[0].spec, "e2e/tests/browse/portal.spec.ts"); + assert!(t[0].error.starts_with("Error: Choosing a camp")); + assert_eq!(t[0].check, "Playwright e2e (all tests)"); + } + + #[test] + fn an_end_to_end_check_red_on_both_is_compared_test_by_test() { + let base_runs = json!({"check_runs": [ + {"name": "Playwright e2e (all tests)", "status": "completed", "conclusion": "failure"}, + {"name": "Lint", "status": "completed", "conclusion": "failure"} + ]}); + let base_notes = "\n--- Playwright e2e (all tests) ---\nfailure: e2e/tests/browse/pricing.spec.ts:40: 1) [chromium] › browse/pricing.spec.ts:40:3 › Pricing › phone pricing shows both rates\n Error: timeout\n"; + let cmp = CiCompare::read("h1", "b1", HEAD, base_notes, &base_runs) + .touching(vec!["e2e/tests/browse/portal.spec.ts".into()]); + // The check's name is not the base's; the lint check still is. + assert_eq!(cmp.base_failing(), vec!["Lint".to_string()]); + assert!(cmp.caused_here(&cmp.head_failing[0])); + // A blame of a test that isn't failing here is held; so is one that + // only names the check. + let mut s = "The phone pricing shows both rates test is broken on main. Fixed the copy." + .to_string(); + assert_eq!(hold_text(&mut s, &cmp), 1); + assert_eq!(s, format!("{BLAME_HELD} Fixed the copy.")); + let mut c = "Playwright e2e fails on main too, so it's pre-existing.".to_string(); + assert_eq!(hold_text(&mut c, &cmp), 1); + // A revert of the change the failing test passes without is backed. + let mut r = "Revert the cart step: choosing a camp adds it to the cart while registration is open fails only here.".to_string(); + assert_eq!(hold_text(&mut r, &cmp), 0); + // Code words alone are no blame. + let mut code = "This guards a pre-existing hole in the parser.".to_string(); + assert_eq!(hold_text(&mut code, &cmp), 0); + } +} diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 8432275a8..5097a1e1d 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -173,10 +173,16 @@ pub(crate) async fn named_labels( /// The review's findings for changed end-to-end files that drive another /// company's page with test ids or JSON fields no probe recorded in the /// repository (`common::e2e::probe`) observed. +/// +/// What is unobserved is settled before it is a finding +/// (`review_probe`): a passing end-to-end run on the head whose report +/// shows the ids observes them, and for the rest the reviewer runs the +/// probe itself and decides from its record. async fn probe_gaps( state: &WorkerState, github: &GitHubClient, - (team_id, owner, repo): (&str, &str, &str), + (team_id, owner, repo, pr_number): (&str, &str, &str, u64), + web: &super::web_check::WebCheck, head_sha: &str, compare: &serde_json::Value, tree: &[String], @@ -212,7 +218,7 @@ async fn probe_gaps( if files.is_empty() { return Vec::new(); } - let mut probes = Vec::new(); + let mut probes: Vec<common::e2e::probe::ProbeRecord> = Vec::new(); for p in tree .iter() .filter(|p| common::e2e::probe::is_record(p)) @@ -225,7 +231,74 @@ async fn probe_gaps( } } let own = super::web_check::team_domains(state, team_id).await; - super::review_rules::probe_findings(&common::e2e::probe::unprobed(&files, &probes, &own)) + let gaps = common::e2e::probe::unprobed(&files, &probes, &own); + if gaps.is_empty() { + return Vec::new(); + } + // A passing end-to-end run on the head: what its report shows was + // exercised against the live page, the same as a probe's record. + let checks = github + .list_check_runs_for_ref(owner, repo, head_sha) + .await + .ok() + .and_then(|v| v["check_runs"].as_array().cloned()) + .unwrap_or_default(); + let comments = github + .list_issue_comments(owner, repo, pr_number) + .await + .unwrap_or_default(); + if let Some(run) = super::e2e_reads::passing_run(&checks, &comments, head_sha) { + if let Some(report) = &run.report { + let mut ids: Vec<String> = gaps.iter().flat_map(|g| g.missing.clone()).collect(); + ids.sort(); + ids.dedup(); + let found = super::e2e_reads::report_shows(state, github, web, report, &ids).await; + info!(pr = pr_number, how = %run.how, report = %report, found = ?found, "End-to-end run on the head read for the selectors no probe observed"); + if !found.is_empty() { + for origin in gaps.iter().map(|g| g.origin.clone()) { + probes.push(super::review_probe::from_report( + &origin, report, head_sha, &found, + )); + } + } + } + } + let gaps = common::e2e::probe::unprobed(&files, &probes, &own); + // What is still unobserved: the reviewer probes the page itself. + let mut out = Vec::new(); + for gap in &gaps { + let (full, added) = files + .iter() + .find(|(p, _, _)| *p == gap.path) + .map(|(_, f, a)| (f.as_str(), a.as_str())) + .unwrap_or(("", "")); + let probed = match super::review_probe::page_url(full, &gap.origin) { + None => super::review_probe::Probed::NotRun(format!( + "the spec names no https page on `{}`", + gap.origin + )), + Some(url) => { + let answer = web + .handle( + state, + github, + super::web_check::PROBE_TOOL, + &serde_json::json!({ "url": url }), + ) + .await + .unwrap_or_default(); + match super::review_probe::record_in_answer(&answer) { + Some(r) => super::review_probe::Probed::Ran(r), + None => super::review_probe::Probed::NotRun( + common::truncate_str(answer.trim(), 200).to_string(), + ), + } + } + }; + info!(pr = pr_number, file = %gap.path, origin = %gap.origin, probed = ?matches!(probed, super::review_probe::Probed::Ran(_)), "Reviewer probed the page for selectors no probe observed"); + out.extend(super::review_probe::decide(gap, full, added, &probed)); + } + out } /// The review's findings for a change wider than its ticket @@ -2663,16 +2736,19 @@ async fn run_once( // and a rebase onto it leaves the approved commit off the // branch: compare the PR's own change now with the one // approved, whichever happened. - own_change_unchanged = match github + let at_approval = match github .get_diff(&msg.repo_owner, &msg.repo_name, base, &approved) .await { - Ok(at_approval) => super::review_scope::same_own_change(&at_approval, &compare), + Ok(v) => Some(v), Err(e) => { warn!(pr = msg.pr_number, error = %e, "Could not read the PR's change at the approval — reviewing what changed since"); - false + None } }; + own_change_unchanged = at_approval + .as_ref() + .is_some_and(|a| super::review_scope::same_own_change(a, &compare)); let nothing_new = (ahead && !super::review_scope::touches_code(&since)) || own_change_unchanged; if nothing_new && unconfirmed_in_body.is_empty() { @@ -2734,15 +2810,21 @@ async fn run_once( nothing new in it; triage the facts the description marks \ unconfirmed.)\n{diff}" ); - } else if ahead { - info!(pr = msg.pr_number, approved = %approved, head = %head_sha, files = ?super::review_scope::code_files(&since), "Reviewing only what changed since the approval"); + } else if let (true, Some(at_approval)) = (ahead, at_approval.as_ref()) { + // Only the PR's own change since the approval: a merge of + // the base branch brings in files this PR doesn't change. + let moved = super::review_scope::own_files_moved(at_approval, &compare); + let own = super::review_scope::own_part_of(&since, &moved); + info!(pr = msg.pr_number, approved = %approved, head = %head_sha, files = ?super::review_scope::code_files(&own), left_out = ?super::review_scope::compare_paths(&since).len().saturating_sub(super::review_scope::compare_paths(&own).len()), "Reviewing only the PR's own change since the approval"); review_diff = format!( - "(CoderHelm approved {short} earlier. This review covers only what \ - changed since then; the rest of the PR was reviewed and approved.)\n{}", - review_agent::format_diff(&since, 40_000) + "(CoderHelm approved {short} earlier. This review covers only what the \ + PR's own change (its diff with the merge base) changed since then; the \ + rest of the PR was reviewed and approved. Files the base branch \ + brought in are not this PR's change and are left out.)\n{}", + review_agent::format_diff(&own, 40_000) ); } else { - info!(pr = msg.pr_number, approved = %approved, "Approved commit isn't an ancestor of the head (rebased) and the change differs — full review"); + info!(pr = msg.pr_number, approved = %approved, "Approved commit isn't an ancestor of the head (rebased), or its change couldn't be read, and the change differs — full review"); } } Err(e) => { @@ -2757,13 +2839,13 @@ async fn run_once( &head_sha, ) { let short = reviewed[..reviewed.len().min(7)].to_string(); - own_change_unchanged = match github + let at_review = github .get_diff(&msg.repo_owner, &msg.repo_name, base, &reviewed) .await - { - Ok(at_review) => super::review_scope::same_own_change(&at_review, &compare), - Err(_) => false, - }; + .ok(); + own_change_unchanged = at_review + .as_ref() + .is_some_and(|a| super::review_scope::same_own_change(a, &compare)); if own_change_unchanged && unconfirmed_in_body.is_empty() { let verdict = records .iter() @@ -2793,12 +2875,19 @@ async fn run_once( .get_diff(&msg.repo_owner, &msg.repo_name, &reviewed, &head_sha) .await { - Ok(since) if super::review_scope::builds_on(&since) => { - info!(pr = msg.pr_number, reviewed = %reviewed, head = %head_sha, files = ?super::review_scope::code_files(&since), "Reviewing only the hunks changed since the previous review"); + Ok(since) if super::review_scope::builds_on(&since) && at_review.is_some() => { + // Only the PR's own change since that review: a merge of + // the base branch brings in files this PR doesn't change. + let moved = super::review_scope::own_files_moved( + at_review.as_ref().unwrap_or(&serde_json::Value::Null), + &compare, + ); + let own = super::review_scope::own_part_of(&since, &moved); + info!(pr = msg.pr_number, reviewed = %reviewed, head = %head_sha, files = ?super::review_scope::code_files(&own), "Reviewing only the hunks of the PR's own change since the previous review"); review_diff = format!( "{}\n{}", super::review_scope::since_review_note(&reviewed), - review_agent::format_diff(&since, 40_000) + review_agent::format_diff(&own, 40_000) ); since_review = Some(reviewed.clone()); } @@ -2957,36 +3046,48 @@ async fn run_once( } }; // Checks that fail on the base branch too were not caused by this PR: - // the reviewer is told, and a finding resting on one is a note. - let base_failing: Vec<String> = if base.is_empty() { - Vec::new() + // the reviewer is told, and a finding resting on one is a note. An + // end-to-end check is compared test by test, from each failing test's + // own error (`review_ci`), never by the check's name. + let base_runs = if base.is_empty() { + serde_json::Value::Null } else { match github .list_ci_for_ref(&msg.repo_owner, &msg.repo_name, base) .await { - Ok(v) => super::review_policy::failing_checks(&v), + Ok(v) => v, Err(e) => { warn!(pr = msg.pr_number, error = %e, "Could not fetch the base branch's check runs"); - Vec::new() + serde_json::Value::Null } } }; - let ci_context = if base_failing.is_empty() { - ci_context - } else { - format!( - "{ci_context}\n## Checks failing on the base branch too ({})\n{}\nThese fail without \ - this PR's change: never block on them. Mention one as a note at most, with \ - `caused_by_diff`: false.\n", - &base[..base.len().min(7)], - base_failing - .iter() - .map(|n| format!("- {n}")) - .collect::<Vec<_>>() - .join("\n") - ) + let ci_compare = { + let failing = |v: &serde_json::Value| !super::review_policy::failing_checks(v).is_empty(); + let head_notes = match github + .list_ci_for_ref(&msg.repo_owner, &msg.repo_name, &head_sha) + .await + { + Ok(v) if failing(&v) => github + .get_check_run_annotations(&msg.repo_owner, &msg.repo_name, &head_sha) + .await + .unwrap_or_default(), + _ => String::new(), + }; + let base_notes = if !head_notes.is_empty() && failing(&base_runs) { + github + .get_check_run_annotations(&msg.repo_owner, &msg.repo_name, base) + .await + .unwrap_or_default() + } else { + String::new() + }; + super::review_ci::CiCompare::read(&head_sha, base, &head_notes, &base_notes, &base_runs) + .touching(changed_files(&compare).into_iter().collect()) }; + let base_failing: Vec<String> = ci_compare.base_failing(); + let ci_context = format!("{ci_context}{}", ci_compare.context()); // For CoderHelm's own PR: what its planner looked up and found about // where the fix belongs, so a diff that overrides source data can be // judged against it. @@ -3280,7 +3381,7 @@ async fn run_once( .await; // A review that didn't finish has no verdict: the job is retried (see // `run`), and nothing is posted for it. Its tokens still count. - let output = match output { + let mut output = match output { Ok(o) => o, Err(reason) => { return Err(reason.into()); @@ -3502,14 +3603,15 @@ async fn run_once( for f in probe_gaps( state, &github, - (&msg.team_id, &msg.repo_owner, &msg.repo_name), + (&msg.team_id, &msg.repo_owner, &msg.repo_name, msg.pr_number), + &web, &head_sha, &compare, &tree, ) .await { - info!(pr = msg.pr_number, file = %f.file, "End-to-end selectors no probe observed: must fix"); + info!(pr = msg.pr_number, file = %f.file, blocks = f.required.is_some(), "End-to-end selectors no probe, run or reviewer's probe observed"); findings.retain(|x| x.title != f.title || x.file != f.file); findings.push(f); } @@ -3534,6 +3636,21 @@ async fn run_once( review_agent::enforce_source_data_override(&mut findings); // A request to test something by hand is a note, never a block. review_agent::enforce_manual_checks_are_notes(&mut findings); + // What the PR changes is its merge-base diff: a file it doesn't change + // is never "an unrelated change" of this PR. + let outside = super::review_scope::drop_outside_claims(&mut findings, &changed_list); + if !outside.is_empty() { + info!(pr = msg.pr_number, dropped = ?outside, "Findings calling a file this PR doesn't change an unrelated change dropped"); + } + // A failing check is blamed on the base branch, or a revert asked for, + // only from the failing test's own runs on both heads. + let held_blame = super::review_ci::hold(&mut findings, &mut output.summary, &ci_compare); + if held_blame > 0 { + info!( + pr = msg.pr_number, + held_blame, "Blame or revert sentences without a test-level comparison held" + ); + } // Rule 3: only a high-severity defect caused by the diff holds the merge. let made_notes = super::review_policy::apply_blocking_policy(&mut findings, &base_failing); if made_notes > 0 { diff --git a/services/worker/src/passes/review_probe.rs b/services/worker/src/passes/review_probe.rs new file mode 100644 index 000000000..e35c8f9e7 --- /dev/null +++ b/services/worker/src/passes/review_probe.rs @@ -0,0 +1,180 @@ +//! The reviewer settles "no probe observed" itself, from what it can read +//! or run, instead of blocking on it. +//! +//! A pull request's end-to-end spec drove a vendor portal by its test ids. +//! The preview's end-to-end run exercised those ids against the live portal +//! and passed, and the review still blocked on "selectors no probe +//! observed": the probe gate (`common::e2e::probe::unprobed`) only read +//! probe records committed in the repository. The rules: +//! +//! - A passing end-to-end run on the head whose published report shows a +//! test id is a record of that id ([`from_report`]): the same +//! [`ProbeRecord`] the gate reads, so the gate decides as it does for a +//! committed probe. +//! - For what is still unobserved, the reviewer runs the probe itself +//! (the coder's `probe_page`, through the review's own page check) on the +//! outside page the spec names, and decides from its record +//! ([`decide`]): seen ids clear the gap, ids the page doesn't have are a +//! verified defect quoted from the record, and a probe that couldn't run +//! is a note with the reason and the probe to run, never a block on the +//! reviewer's own missing look. On CoderHelm's own pull request that note +//! is still work for the coder (`own_review::required`). + +use common::e2e::probe::{ProbeRecord, Unprobed}; + +use super::review_agent::Finding; + +/// A record of the test ids a passing end-to-end run's report showed, for +/// `origin`. `found` are the ids the report's text holds. +pub fn from_report(origin: &str, report: &str, head: &str, found: &[String]) -> ProbeRecord { + ProbeRecord { + origin: origin.to_string(), + url: report.to_string(), + at: format!("a passing end-to-end run on {}", &head[..head.len().min(7)]), + testids: found.to_vec(), + ..Default::default() + } +} + +/// The first https URL on `origin` in `code` (the page the spec drives). +pub fn page_url(code: &str, origin: &str) -> Option<String> { + let want = format!("https://{}", origin.to_ascii_lowercase()); + for (i, _) in code.match_indices("https://") { + let rest = &code[i..]; + let end = rest + .find(|c: char| c.is_whitespace() || matches!(c, '\'' | '"' | '`' | ')' | '>' | ',')) + .unwrap_or(rest.len()); + let url = &rest[..end]; + let low = url.to_ascii_lowercase(); + if low == want + || low.starts_with(&format!("{want}/")) + || low.starts_with(&format!("{want}?")) + { + // A template's placeholder can't be loaded. + if url.contains("${") { + continue; + } + return Some(url.to_string()); + } + } + None +} + +/// The record in the probe tool's answer: the JSON object after the +/// answer's first line (or after its record mark). +pub fn record_in_answer(answer: &str) -> Option<ProbeRecord> { + let from = answer + .find("Probe record:") + .map(|i| i + "Probe record:".len()) + .or_else(|| answer.find('\n'))?; + let rest = &answer[from..]; + let start = rest.find('{')?; + serde_json::Deserializer::from_str(&rest[start..]) + .into_iter::<ProbeRecord>() + .next()? + .ok() +} + +/// What the reviewer's own probe settled for one gap. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Probed { + /// The probe ran; its record. + Ran(ProbeRecord), + /// It couldn't run (no page named, a refused host, the sandbox): why. + NotRun(String), +} + +/// The review's finding for a gap after the reviewer's own probe, if any. +/// The gate (`unprobed`) is asked again with the probe's record: ids it saw +/// clear the gap. +pub fn decide(gap: &Unprobed, full: &str, added: &str, probed: &Probed) -> Option<Finding> { + match probed { + Probed::Ran(record) => { + let still = common::e2e::probe::unprobed( + &[(gap.path.clone(), full.to_string(), added.to_string())], + std::slice::from_ref(record), + &[], + ); + let missing: Vec<String> = still + .iter() + .filter(|g| g.origin.eq_ignore_ascii_case(&gap.origin)) + .flat_map(|g| g.missing.clone()) + .filter(|m| gap.missing.contains(m)) + .collect(); + if missing.is_empty() { + return None; + } + let seen: Vec<String> = record.testids.iter().take(30).cloned().collect(); + let gap = Unprobed { + missing: missing.clone(), + ..gap.clone() + }; + let mut f = super::review_rules::probe_findings(std::slice::from_ref(&gap)) + .into_iter() + .next()?; + f.title = format!("Test ids `{}` doesn't have", gap.origin); + f.basis = Some("external".into()); + f.body = format!( + "The reviewer probed {} ({}): {} {} not on the page. The page's test ids: {}.\n\n{}", + record.url, + record.at, + missing + .iter() + .map(|m| format!("`{m}`")) + .collect::<Vec<_>>() + .join(", "), + if missing.len() == 1 { "is" } else { "are" }, + if seen.is_empty() { + "none".to_string() + } else { + seen.iter() + .map(|t| format!("`{t}`")) + .collect::<Vec<_>>() + .join(", ") + }, + f.body, + ); + Some(f) + } + Probed::NotRun(why) => Some(Finding { + file: gap.path.clone(), + severity: "medium".into(), + category: "tests".into(), + title: format!("Selectors on `{}` not yet observed", gap.origin), + body: format!( + "{} The reviewer's own probe couldn't run ({why}), and no passing end-to-end run \ + on this head shows them. Run `probe_page` on the page the spec drives, or a \ + passing end-to-end run that exercises them.", + gap.body() + ), + evidence: Some("unverified-concern".into()), + basis: Some("external".into()), + caused_by_diff: Some(true), + ..Default::default() + }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_page_a_spec_drives_is_read_from_its_code() { + let code = "const P = 'https://portal.example-vendor.io/org/1/portal/2';\nawait page.goto(`https://portal.example-vendor.io/${id}`)"; + assert_eq!( + page_url(code, "portal.example-vendor.io").as_deref(), + Some("https://portal.example-vendor.io/org/1/portal/2") + ); + assert_eq!(page_url(code, "other.io"), None); + } + + #[test] + fn the_record_is_read_from_the_probe_tools_answer() { + let main = "Probe of https://v.io/p. Commit this record at `.coderhelm/probes/v.io.json`:\n{\"origin\":\"v.io\",\"url\":\"https://v.io/p\",\"testids\":[\"a\"]}"; + assert_eq!(record_in_answer(main).unwrap().testids, vec!["a"]); + let marked = "Probe of https://v.io/p. It is committed.\nseen: a\nProbe record:\n{\"origin\":\"v.io\",\"testids\":[\"b\"]}\n"; + assert_eq!(record_in_answer(marked).unwrap().testids, vec!["b"]); + assert_eq!(record_in_answer("https://v.io/p: refused: no"), None); + } +} diff --git a/services/worker/src/passes/review_scope.rs b/services/worker/src/passes/review_scope.rs index 2ef6817ae..dc3430a41 100644 --- a/services/worker/src/passes/review_scope.rs +++ b/services/worker/src/passes/review_scope.rs @@ -5,6 +5,16 @@ //! changed no code or data since then (docs, comments, whitespace) isn't //! reviewed at all; the approval stands. A push after a request for changes //! still gets a full review, so the whole change is checked again. +//! +//! What a pull request changes is always its merge-base diff with the base +//! branch, never the diff from a commit CoderHelm reviewed. A pull request +//! once had the base branch merged in after an approval; the diff from the +//! approved commit then carried another pull request's file (already on the +//! base branch, not in this one's change), and the review called it an +//! unrelated change. A re-review covers only the files whose own change +//! moved ([`own_files_moved`], [`own_part_of`]), and a finding that calls a +//! file the pull request doesn't change unrelated or out of scope is +//! dropped ([`drop_outside_claims`]). use serde_json::Value; @@ -159,17 +169,8 @@ pub fn same_own_change(at_approval: &Value, now: &Value) -> bool { fn changes(compare: &Value) -> Option<Vec<(String, String, Vec<String>)>> { let mut out = Vec::new(); for f in compare["files"].as_array()? { - let patch = f["patch"].as_str()?; - let lines: Vec<String> = patch - .lines() - .filter(|l| l.starts_with('+') || l.starts_with('-')) - .map(str::to_string) - .collect(); - out.push(( - f["filename"].as_str()?.to_string(), - f["status"].as_str().unwrap_or("").to_string(), - lines, - )); + let (name, status, lines) = own_file_change(f); + out.push((name?, status, lines?)); } out.sort(); Some(out) @@ -180,6 +181,137 @@ pub fn same_own_change(at_approval: &Value, now: &Value) -> bool { } } +/// One file of a merge-base compare: its path, status and added and +/// removed lines (`None` when GitHub sent no patch). +fn own_file_change(f: &Value) -> (Option<String>, String, Option<Vec<String>>) { + let lines = f["patch"].as_str().map(|patch| { + patch + .lines() + .filter(|l| l.starts_with('+') || l.starts_with('-')) + .map(str::to_string) + .collect() + }); + ( + f["filename"].as_str().map(str::to_string), + f["status"].as_str().unwrap_or("").to_string(), + lines, + ) +} + +/// The paths a compare lists. +pub fn compare_paths(compare: &Value) -> Vec<String> { + compare["files"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|f| f["filename"].as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default() +} + +/// The files of the pull request's own change now (its merge-base compare, +/// `now`) whose change differs from the one at an earlier reviewed commit +/// (`at_review`, that commit's merge-base compare): new to the pull +/// request, or with other added or removed lines. A file only the base +/// branch changed in between is in neither compare, so it is never here. A +/// file whose patch GitHub didn't send counts as moved. +pub fn own_files_moved(at_review: &Value, now: &Value) -> Vec<String> { + let before: Vec<(Option<String>, String, Option<Vec<String>>)> = at_review["files"] + .as_array() + .map(|a| a.iter().map(own_file_change).collect()) + .unwrap_or_default(); + let mut out = Vec::new(); + for f in now["files"].as_array().into_iter().flatten() { + let (Some(name), status, lines) = own_file_change(f) else { + continue; + }; + let same = lines.is_some() + && before.iter().any(|(n, s, l)| { + n.as_deref() == Some(name.as_str()) && *s == status && *l == lines + }); + if !same { + out.push(name); + } + } + out +} + +/// The part of `since` (the compare from a reviewed commit to the head) +/// that is the pull request's own: only the files in `moved` +/// ([`own_files_moved`]). Everything a merge of the base branch brought in +/// is left out. The compare keeps its status and commits. +pub fn own_part_of(since: &Value, moved: &[String]) -> Value { + let mut out = since.clone(); + let kept: Vec<Value> = since["files"] + .as_array() + .map(|a| { + a.iter() + .filter(|f| { + f["filename"] + .as_str() + .is_some_and(|n| moved.iter().any(|m| m == n)) + }) + .cloned() + .collect() + }) + .unwrap_or_default(); + out["files"] = Value::Array(kept); + out +} + +/// Words that say a file's change doesn't belong in the pull request. +const OUTSIDE_WORDS: &[&str] = &[ + "unrelated", + "out of scope", + "outside the scope", + "outside this ticket", + "not part of this", + "doesn't belong", + "does not belong", + "not related to", + "another pull request", + "another pr", + "scope creep", + "drive-by", + "revert this file", + "revert the change to", +]; + +/// Drops the findings on a file the pull request doesn't change (`pr_files`, +/// its merge-base compare's paths) that call the file's change unrelated, +/// out of scope or another pull request's: there is no such change in this +/// one. A finding about a file outside the diff that the change breaks (a +/// caller, a config) is kept. Returns the dropped findings' titles. +pub fn drop_outside_claims( + findings: &mut Vec<super::review_agent::Finding>, + pr_files: &[String], +) -> Vec<String> { + let mut dropped = Vec::new(); + findings.retain(|f| { + let holds = holds_on_diff(f, pr_files); + if !holds { + dropped.push(format!("{} ({})", f.title, f.file)); + } + holds + }); + dropped +} + +/// Whether a finding still holds against a pull request's merge-base diff +/// at a head (`pr_files`, [`compare_paths`] of its base...head compare): +/// false for one that calls a file the pull request doesn't change +/// unrelated, out of scope or another pull request's. Pure, so the thread +/// cleanup can ask it of an earlier finding at a later head. +pub fn holds_on_diff(f: &super::review_agent::Finding, pr_files: &[String]) -> bool { + let file = f.file.trim().trim_start_matches("./"); + if file.is_empty() || pr_files.iter().any(|p| p == file) { + return true; + } + let text = format!("{} {}", f.title, f.body).to_ascii_lowercase(); + !(OUTSIDE_WORDS.iter().any(|w| text.contains(w)) || f.category.eq_ignore_ascii_case("scope")) +} + fn file_touches_code(f: &Value) -> bool { let name = f["filename"].as_str().unwrap_or(""); if name.is_empty() || is_lockfile(name) { diff --git a/services/worker/src/passes/review_severity.rs b/services/worker/src/passes/review_severity.rs index a6576c74d..431f817a6 100644 --- a/services/worker/src/passes/review_severity.rs +++ b/services/worker/src/passes/review_severity.rs @@ -285,7 +285,7 @@ const MISSING_TEST_PHRASES: &[&str] = &[ /// A tests finding that asks for a test (a Suggestion), not one that shows /// a test fails or proves nothing (a correctness problem). -fn asks_for_a_test(f: &Finding) -> bool { +pub fn asks_for_a_test(f: &Finding) -> bool { let text = format!("{} {}", f.title, f.body).to_ascii_lowercase(); MISSING_TEST_PHRASES.iter().any(|p| text.contains(p)) }