From 63c8bec26cc00b97ceafb54f080f070e0baca4b6 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 13 Nov 2026 18:19:45 -0500 Subject: [PATCH 1/5] A description names the head it was built for and is rebuilt whenever the head differs A dependency run's description was built on the commit that changed the manifest, where the lockfile still resolved the old version. The lockfile was regenerated in later commits and the run completed with a description that still said "not moved on the head", still counted the advisory as not fixed and still listed items of the earlier head. - description: a hidden stamp names the head the description was built for. reconcile rebuilds it when the stamp is not the pull request's head: after every message in which CoderHelm moved the branch, in the checks and settle step, before a review of its own pull request, in the pull request watch and at the end of the run, which returns an error instead of completing on another head's description. - GitHub client: every request leaves through send_tracked, which notes the branch a successful ref update, contents write or merge moved. No caller has to remember to ask for a rebuild. - review: its open findings are written on the description as it is now and only while the reviewed head is still the head. It used to write back the copy it read when it started. - settle: an item that says a lockfile is out of sync is checked on the head by the repository's checks, never carried as CoderHelm's own. - own review: a finding that the description is behind the code triggers the rebuild and is dropped when the rebuild settles it. Every finding that is not pure style is CoderHelm's to act on. - dep_head: tests for suffixed versions, exact-version override keys and a package moved on a later head. - Incident case ar and its row in docs/incidents.md. --- docs/incidents.md | 1 + services/common/src/dep_head.rs | 130 +++++++ services/worker/src/clients/github.rs | 202 ++++++++++ services/worker/src/main.rs | 15 + services/worker/src/passes/description.rs | 351 +++++++++++++++++- .../incidents/am_description_from_the_head.rs | 5 +- .../ar_description_stamped_to_the_head.rs | 298 +++++++++++++++ services/worker/src/passes/incidents/mod.rs | 1 + services/worker/src/passes/own_review.rs | 100 ++++- services/worker/src/passes/pr.rs | 24 ++ services/worker/src/passes/pr_watch.rs | 5 + services/worker/src/passes/resume.rs | 28 ++ services/worker/src/passes/review_pr.rs | 120 +++++- services/worker/src/passes/review_severity.rs | 11 +- services/worker/src/passes/security_fixes.rs | 46 +-- services/worker/src/passes/settle.rs | 107 ++++++ 16 files changed, 1372 insertions(+), 72 deletions(-) create mode 100644 services/worker/src/passes/incidents/ar_description_stamped_to_the_head.rs diff --git a/docs/incidents.md b/docs/incidents.md index 22df5085b..9c9de9c63 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -69,6 +69,7 @@ pipeline still calls it there. | am. `am_description_from_the_head` | A dependency security run's pull request had the right code after a review round and the wrong description. Its table still showed the plan (five packages as major version jumps the final manifest no longer makes, a headline counting twenty major versions), its count of fixed advisories had never been compared with the final lockfile, the round that fixed the code wrote that it could not edit the description and left the corrections to a person, and the repository's second app (a CMS studio no CI job builds) took a package an override moved to a new major and was never built. | The description is a function of the head. A dependency pull request's table and headline are what the lockfile on the head resolves compared with the base branch; an advisory counts as fixed only at or past its patched version; what can't be read is said as not known and the plan is marked as a plan. Every write of a description goes through `description::save`, every path that moves the head rebuilds it through `description::head_moved`, and a round's sentence that hands the description to a person is taken out and becomes the rebuild. A sentence a run writes into a file that says a check passes needs that check's recorded passing result, or it is taken out. Every workspace project that takes a changed package line is built when its manifest declares a build, CI job or not; a project that can't be proven in the sandbox is named with why, and a build only the bumps break feeds the take-out. | | an. `an_six_database_findings` | Security, Infrastructure showed six database findings, every one a one-command runbook with no pull request although the databases were in the team's code. The same CVE stood on an operating system update, an Aurora PostgreSQL patch and a MySQL upgrade. A database with a Terraform-generated identifier and an Aurora cluster defined through a module were "not found in code". A patch and an upgrade pending on one cluster were unrelated rows, an update on a second instance was dropped, and the account was read one page deep. | An advisory is attached only where it applies (service, engine, version range, kind of action, date); an action AWS publishes with no CVE list gets none. An action is named for what it means on its ARN. One database's pending actions are one ordered set of rows. The defining code is found from stack records, resource type and attributes, module calls and variable files, graded, and a guess never becomes a pull request. An update with a code equivalent is a pull request on the line that sets the value; one that cannot be expressed in code stays a complete runbook and says why. A change that would replace a database is refused. | | ao. `ao_stopped_log_finding` | Two log findings of one production service stayed on the Logs page as Critical and New, each with "Create fix PR" and "Not started automatically: not sure the repo is ...; check it and start the fix", a day and a half after their error had stopped: 735 matching lines in one six-hour window, then none while the service wrote its usual volume. The team had fixed the cause the day before. Only time closed a finding (three days without a line), so a problem that was over read as a live emergency that needed a person. | Every analysis counts each open finding's own lines on its own log group and keeps the count with the lines the group wrote. Two analyses in a row with no matching line at the service's usual volume make the finding stopped: shown and counted as stopped, never New or a live critical, with no automatic fix and no stale "choose a repo" reason. When the service itself went quiet nobody can tell, and it stays as it was. A burst that stopped after a change in its repo resolves after one day instead of three, with that evidence in the reason; an error that keeps coming back keeps its longer period. Seen again, it is live again and its fix may start. Evidence for the repo that couldn't be weighed is weighed again next sweep and never put to a person. | +| ar. `ar_description_stamped_to_the_head` | A dependency run's pull request was described from a head, and the head then moved on without it. A feedback round changed an override in the manifest and the description was rebuilt on that commit, where the lockfile still resolved the old version ("not moved on the head"); the lockfile was regenerated in the commits after it and the run completed. The description still said not moved, still counted the advisory as not fixed, still listed the package under open findings and "the lockfile is out of sync" under Open items, and CoderHelm's own review of the final head left that as a note. The checks step on an open pull request never rebuilt the computed sections, a regenerated lockfile was pushed with nothing after it, a review wrote its findings into the copy of the description it had read when it started (undoing a rebuild made meanwhile), and nits on CoderHelm's own pull request ended the loop. | The description names the head it was built for, and whenever that is not the pull request's head it is rebuilt: after every message in which CoderHelm moved the branch (seen in the one place every request leaves the GitHub client), in the checks and settle step, before a review of its own pull request, in the pull request watch, and at the end of the run, which never completes while the two differ. A review writes on the description as it is now and only for the head it reviewed. An item that says a lockfile is out of sync is checked on the head, never carried. A finding that the description is behind the code is settled by the rebuild, and every finding on CoderHelm's own pull request that is not pure style is its own to act on. | | ba. `ba_verdict_on_old_commit` | A run finished as Done with its pull request ready while its own reviewer stood at "Changes requested" on a commit older than the head, and the run page said a person was needed and that merging was the team's call. The last fix was pushed, and the wake-up that found CI green with no event to read completed the run through an ending that skips the review step, so the new head was never reviewed. | Every completion and the sweep look at the finished run's pull request (`pr_watch`): no reviewer verdict on the head asks for the review of that commit, once per head; changes requested on the head get their fix round, and when the run's rounds are over the findings are deferred on the pull request with the reason. The run page names the one true reason the pull request is where it is (`common::merge_standing`) and names a person only for the team's own rule, with where it is set. | | bb. `bb_flaky_not_broken` | An end-to-end workflow failed on a timeout in a spec the change never touched, as it had on unrelated pull requests that week. The run spent fix rounds editing the spec's timeout and a retry helper. Where the GitHub App may not write Actions, the re-run tried first was refused and the same fix round followed. | Before a CI fix round the failure is judged (`common::flaky_checks`): a failure naming a changed file is the change's; a check with a record of failing and then passing on one commit of other pull requests, naming no changed file, is re-run once and no code changes for it, and the pull request says which check, the evidence and what was done. A refused re-run is said with the permission by name and still changes no code. The record is per repository and learns only from a commit that failed and then passed unchanged. | | bc. `bc_stays_through_merge_and_deploy` | Pull requests were left as they were after their runs finished: one conflicted after its base moved, one went red a day later on a commit status no event carries, and one merged by a person had its production deploy fail with nothing watching. | A finished run's pull request is looked at on completion and by the sweep: a conflict starts the conflict round once per base commit, red checks not red on the base go to the fix loop once per head, and a merge by anyone gets its merge commit's deploy watched once. A deploy of CoderHelm's own change that fails on checks passing before the merge gets a revert pull request with the failing jobs as evidence, ready for the team's approval and never merged by CoderHelm; files changed again since are never overwritten. | diff --git a/services/common/src/dep_head.rs b/services/common/src/dep_head.rs index 1eca2fffb..e54eb8ff9 100644 --- a/services/common/src/dep_head.rs +++ b/services/common/src/dep_head.rs @@ -626,4 +626,134 @@ mod tests { Resolved::Unknown { .. } )); } + + // ── Suffixed versions, exact-version overrides, a later head ──────── + + #[test] + fn a_version_with_a_suffix_is_read_on_its_line() { + let unit = FixUnit { + bumps: vec![bump("xml-kit", "1.4.4-lts.1", "2.0.3")], + ..Default::default() + }; + let f = finding("GHSA-s", "xml-kit", "1.4.4-lts.1", Some("2.0.3")); + // An override keyed on the exact version moved every copy to 2.0.3. + let moved = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[("xml-kit", "1.4.4-lts.1")]), + head: copies(&[("xml-kit", "2.0.3")]), + why: String::new(), + }; + let facts = resolve(&unit, "h2", &[moved]); + assert_eq!(facts.version_cell(0), "1.4.4-lts.1 to 2.0.3 (major)"); + assert_eq!(facts.fixed(&unit, &f), Fixed::Yes); + // A patched build on the same line, also suffixed. + let unit_lts = FixUnit { + bumps: vec![bump("xml-kit", "1.4.4-lts.1", "1.4.4-lts.2")], + ..Default::default() + }; + let f_lts = finding("GHSA-s", "xml-kit", "1.4.4-lts.1", Some("1.4.4-lts.2")); + let same_line = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[("xml-kit", "1.4.4-lts.1")]), + head: copies(&[("xml-kit", "1.4.4-lts.2")]), + why: String::new(), + }; + let facts = resolve(&unit_lts, "h2", &[same_line]); + assert_eq!(facts.version_cell(0), "1.4.4-lts.1 to 1.4.4-lts.2"); + assert_eq!(facts.fixed(&unit_lts, &f_lts), Fixed::Yes); + // The suffixed build is not mistaken for the plain release. + let not_yet = LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[("xml-kit", "1.4.4-lts.1")]), + head: copies(&[("xml-kit", "1.4.4-lts.1")]), + why: String::new(), + }; + let facts = resolve(&unit_lts, "h1", &[not_yet]); + assert_eq!(facts.version_cell(0), "1.4.4-lts.1, not moved on the head"); + assert_eq!(facts.fixed(&unit_lts, &f_lts), Fixed::No); + } + + /// The lockfiles as the package managers write them, with an override + /// keyed on the exact suffixed version. + #[test] + fn an_exact_version_override_is_read_from_real_lockfile_text() { + use crate::reachability::lock_copies; + let pnpm = |v: &str| { + format!( + "lockfileVersion: '9.0'\noverrides:\n xml-kit@1.4.4-lts.1: 2.0.3\nimporters:\n .:\n dependencies:\n feed-reader:\n specifier: ^3.0.0\n version: 3.1.0\npackages:\n feed-reader@3.1.0: {{}}\n xml-kit@{v}: {{}}\nsnapshots:\n feed-reader@3.1.0:\n dependencies:\n xml-kit: {v}\n xml-kit@{v}: {{}}\n" + ) + }; + let npm = |v: &str| { + format!( + r#"{{"lockfileVersion":3,"packages":{{"":{{"dependencies":{{"feed-reader":"^3.0.0"}},"overrides":{{"xml-kit@1.4.4-lts.1":"2.0.3"}}}},"node_modules/feed-reader":{{"version":"3.1.0","dependencies":{{"xml-kit":"1.4.4-lts.1"}}}},"node_modules/xml-kit":{{"version":"{v}"}}}}}}"# + ) + }; + let yarn = |v: &str| { + format!( + "# yarn lockfile v1\n\nfeed-reader@^3.0.0:\n version \"3.1.0\"\n dependencies:\n xml-kit \"1.4.4-lts.1\"\n\nxml-kit@1.4.4-lts.1:\n version \"{v}\"\n" + ) + }; + for (path, lock) in [ + ("pnpm-lock.yaml", &pnpm as &dyn Fn(&str) -> String), + ("package-lock.json", &npm), + ("yarn.lock", &yarn), + ] { + let mut b = bump("xml-kit", "1.4.4-lts.1", "2.0.3"); + b.manifest = path.into(); + let unit = FixUnit { + bumps: vec![b], + ..Default::default() + }; + let at = LockAt { + path: path.into(), + base: lock_copies(path, &lock("1.4.4-lts.1")), + head: lock_copies(path, &lock("2.0.3")), + why: String::new(), + }; + assert!( + at.base + .as_ref() + .unwrap() + .contains(&("xml-kit".into(), "1.4.4-lts.1".into())), + "{path}: {:?}", + at.base + ); + let facts = resolve(&unit, "h2", &[at]); + assert_eq!( + facts.version_cell(0), + "1.4.4-lts.1 to 2.0.3 (major)", + "{path}" + ); + } + } + + /// The manifest got its override on one head; the lockfile was written + /// on a later one. The first head's answer is right for that head and + /// wrong for the next, so it is never carried over. + #[test] + fn a_package_an_override_moves_on_a_later_head_is_read_again() { + let unit = FixUnit { + bumps: vec![bump("xml-kit", "1.4.4-lts.1", "2.0.3")], + ..Default::default() + }; + let f = finding("GHSA-s", "xml-kit", "1.4.4-lts.1", Some("2.0.3")); + let st = FindingState::default(); + let at = |head: &str| LockAt { + path: "pnpm-lock.yaml".into(), + base: copies(&[("xml-kit", "1.4.4-lts.1")]), + head: copies(&[("xml-kit", head)]), + why: String::new(), + }; + let first = resolve(&unit, "h1", &[at("1.4.4-lts.1")]); + assert_eq!(first.version_cell(0), "1.4.4-lts.1, not moved on the head"); + assert!(first + .headline(&unit, &[(&f, &st)]) + .contains("Not fixed on the head: GHSA-s")); + let second = resolve(&unit, "h2", &[at("2.0.3")]); + assert_eq!(second.version_cell(0), "1.4.4-lts.1 to 2.0.3 (major)"); + let h = second.headline(&unit, &[(&f, &st)]); + assert!(h.starts_with("Fixes 1 of 1 advisory"), "{h}"); + assert!(!h.contains("Not fixed"), "{h}"); + assert_ne!(first, second); + } } diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index df747d03c..026cc5980 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -188,6 +188,67 @@ pub struct Budget { } /// The last budget each installation's responses reported, in this process. +/// A branch CoderHelm moved in this process and has not yet reconciled. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct MovedBranch { + pub installation_id: u64, + pub owner: String, + pub repo: String, + pub branch: String, +} + +static MOVED: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| Mutex::new(Vec::new())); + +fn note_branch_moved(installation_id: u64, owner: &str, repo: &str, branch: &str) { + let m = MovedBranch { + installation_id, + owner: owner.to_string(), + repo: repo.to_string(), + branch: branch.to_string(), + }; + if let Ok(mut moved) = MOVED.lock() { + if !moved.contains(&m) { + moved.push(m); + } + } +} + +/// The branches moved since the last call, each once. +pub fn take_moved_branches() -> Vec { + MOVED + .lock() + .map(|mut m| std::mem::take(&mut *m)) + .unwrap_or_default() +} + +/// The branch a request moves when it succeeds, as (owner, repo, branch): +/// a ref update or creation, a file written or deleted through the +/// contents API, or a merge into a branch. `None` for every other request. +pub fn branch_moved_by(method: &str, path: &str, body: &[u8]) -> Option<(String, String, String)> { + if !matches!(method, "POST" | "PATCH" | "PUT" | "DELETE") { + return None; + } + let rest = path.strip_prefix("/repos/")?; + let mut parts = rest.splitn(3, '/'); + let (owner, repo, tail) = (parts.next()?, parts.next()?, parts.next()?); + let json = || serde_json::from_slice::(body).ok(); + let field = |k: &str| json().and_then(|v| v[k].as_str().map(String::from)); + let branch = if let Some(b) = tail.strip_prefix("git/refs/heads/") { + // A deleted branch has no head to describe. + (method == "PATCH").then(|| b.to_string())? + } else if tail == "git/refs" && method == "POST" { + field("ref")?.strip_prefix("refs/heads/")?.to_string() + } else if tail.starts_with("contents/") && matches!(method, "PUT" | "DELETE") { + field("branch")? + } else if tail == "merges" && method == "POST" { + field("base")? + } else { + return None; + }; + (!branch.is_empty()).then(|| (owner.to_string(), repo.to_string(), branch)) +} + static BUDGETS: std::sync::LazyLock>> = std::sync::LazyLock::new(|| Mutex::new(HashMap::new())); @@ -859,6 +920,14 @@ impl GitHubClient { &self, req: reqwest::RequestBuilder, ) -> Result { + // Every request goes out here, so this is the one place a write that + // moves a branch is seen: whoever made it, the branch is noted, and + // the description of its pull request is rebuilt for the new head + // (`passes::description::reconcile_moved`). + let moving = req.try_clone().and_then(|r| r.build().ok()).and_then(|r| { + let body = r.body().and_then(|b| b.as_bytes()).unwrap_or_default(); + branch_moved_by(r.method().as_str(), r.url().path(), body) + }); let resp = match req.send().await { Ok(r) => r, Err(e) => { @@ -875,6 +944,9 @@ impl GitHubClient { }; observe_budget(self.installation_id, resp.headers()); note_limited(self.installation_id, resp.headers(), resp.status().as_u16()); + if let (Some((owner, repo, branch)), true) = (moving, resp.status().is_success()) { + note_branch_moved(self.installation_id, &owner, &repo, &branch); + } Ok(resp) } @@ -5657,6 +5729,136 @@ mod body_limit_tests { assert_eq!(bounded_payload(&p), p); } + /// Every request leaves through `send_tracked`, which notes a branch a + /// successful write moved: a new method that pushes cannot pass it by. + #[test] + fn every_push_is_seen_in_one_place() { + let src = include_str!("github.rs"); + let code = &src[..src.find("#[cfg(test)]\nmod ").unwrap_or(src.len())]; + // Three sends in all: `send_tracked`, and two reads that mint the + // installation's token and name the app. A fourth is a request that + // could move a branch unseen. + assert_eq!(code.matches(".send()").count(), 3); + for raw in [ + "self.http.put(", + "self.http.delete(", + "self.http.post(", + "self.http.patch(", + ] { + for (i, _) in code.match_indices(raw) { + // To the end of the method that builds it. + let rest = &code[i..]; + let after = &rest[..rest.find("\n }\n").unwrap_or(rest.len())]; + assert!( + after.contains("self.send_tracked(req)"), + "a write is built and not sent through send_tracked: {}", + after.lines().next().unwrap_or("") + ); + } + } + let tracked = &code[code.find("async fn send_tracked(").unwrap()..]; + let tracked = &tracked[..tracked.find("\n }\n").unwrap()]; + assert!(tracked.contains("branch_moved_by(")); + assert!(tracked.contains("note_branch_moved(")); + // No pass talks to the refs, contents or merges endpoints itself. + fn walk(dir: &std::path::Path, out: &mut Vec) { + for e in std::fs::read_dir(dir).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + walk(&p, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } + } + } + let mut files = vec![]; + walk( + &std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/passes"), + &mut files, + ); + for f in files { + if f.to_string_lossy().contains("/incidents/") { + continue; + } + let text = std::fs::read_to_string(&f).unwrap(); + // The code, without the file's own tests (which quote GitHub's + // error messages, URLs and all). + let text = &text[..text.find("#[cfg(test)]").unwrap_or(text.len())]; + for l in text.lines().filter(|l| !l.trim_start().starts_with("//")) { + assert!( + !(l.contains("api.github.com") + && (l.contains("git/refs") || l.contains("/merges"))), + "{} moves a branch past the client: {l}", + f.display() + ); + } + } + } + + #[test] + fn a_request_that_moves_a_branch_names_it() { + let moved = |m: &str, p: &str, b: &str| branch_moved_by(m, p, b.as_bytes()); + let on = |b: &str| Some(("acme".to_string(), "site".to_string(), b.to_string())); + assert_eq!( + moved( + "PATCH", + "/repos/acme/site/git/refs/heads/coderhelm/sec-1", + r#"{"sha":"a"}"# + ), + on("coderhelm/sec-1") + ); + assert_eq!( + moved( + "POST", + "/repos/acme/site/git/refs", + r#"{"ref":"refs/heads/wip/x","sha":"a"}"# + ), + on("wip/x") + ); + assert_eq!( + moved( + "PUT", + "/repos/acme/site/contents/package.json", + r#"{"branch":"fix","content":""}"# + ), + on("fix") + ); + assert_eq!( + moved( + "POST", + "/repos/acme/site/merges", + r#"{"base":"fix","head":"main"}"# + ), + on("fix") + ); + // Reads, a deleted branch, a tag, a pull request's body, a commit + // object: none moves a branch. + for (m, p, b) in [ + ("GET", "/repos/acme/site/git/refs/heads/fix", ""), + ("DELETE", "/repos/acme/site/git/refs/heads/fix", ""), + ( + "POST", + "/repos/acme/site/git/refs", + r#"{"ref":"refs/tags/v1","sha":"a"}"#, + ), + ("PATCH", "/repos/acme/site/pulls/7", r#"{"body":"x"}"#), + ("POST", "/repos/acme/site/git/commits", r#"{"message":"x"}"#), + ("POST", "/app/installations/1/access_tokens", ""), + ] { + assert_eq!(moved(m, p, b), None, "{m} {p}"); + } + note_branch_moved(7, "acme", "site", "fix"); + note_branch_moved(7, "acme", "site", "fix"); + let taken = take_moved_branches(); + assert_eq!( + taken + .iter() + .filter(|m| m.branch == "fix" && m.installation_id == 7) + .count(), + 1 + ); + } + /// Every method that writes a body sends it through `post`, `patch` or /// `post_empty`, which bound it: none builds its own request around it. #[test] diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 77a3ba9fb..b68d6af6e 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -314,7 +314,22 @@ async fn installation_is_teams_own( } } +/// Handles one message, then rebuilds the description of every pull +/// request whose branch CoderHelm moved while handling it: the one place a +/// push is followed up, whichever code made it. async fn handle_message(state: Arc, message: models::WorkerMessage) { + let team = serde_json::to_value(&message).ok().and_then(|raw| { + let (_, teams) = team_installation::claims(&raw); + team_installation::single_team(&teams) + .ok() + .flatten() + .map(str::to_string) + }); + handle_message_inner(Arc::clone(&state), message).await; + passes::description::reconcile_moved(&state, team.as_deref()).await; +} + +async fn handle_message_inner(state: Arc, message: models::WorkerMessage) { match message { models::WorkerMessage::Ticket(msg) => { info!(team_id = %msg.team_id, ticket_id = %msg.ticket_id, "Starting ticket run"); diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index aa442a826..c4c13cb8c 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -114,8 +114,8 @@ pub async fn head_moved( ) .await; // After the rewrite, so what the lockfile resolves is the last word on - // every version and count. - dependency_sections( + // every version and count, and the description names the head it is of. + rebuild( m.state, m.github, m.team_id, @@ -129,8 +129,8 @@ pub async fn head_moved( } /// A dependency pull request's table, headline, "What to check" and Proof, -/// rebuilt from what the lockfile on its head resolves. Costs no model -/// call. Nothing for any other pull request. +/// rebuilt from what the lockfile on its head resolves, and the stamp of +/// the head they are of. Costs no model call. pub async fn dependency_sections( state: &WorkerState, github: &GitHubClient, @@ -140,18 +140,260 @@ pub async fn dependency_sections( number: u64, ticket_id: &str, ) { - if !common::security_fixes::is_ticket(ticket_id) { - return; + rebuild(state, github, team_id, owner, repo, number, ticket_id).await; +} + +// ── The head a description was built for ─────────────────────────────── + +/// A hidden line naming the head commit the description's computed +/// sections were built for. A description with no stamp, or another +/// head's, is rebuilt before anything rests on it. +pub const STAMP_START: &str = ""; + +/// The head the description says it was built for. +pub fn stamp_of(body: &str) -> Option<&str> { + let at = body.rfind(STAMP_START)? + STAMP_START.len(); + let rest = &body[at..]; + Some(rest[..rest.find(STAMP_END)?].trim()).filter(|h| !h.is_empty()) +} + +/// `body` stamped as built for `head` (one stamp, on its own last line). +pub fn with_stamp(body: &str, head: &str) -> String { + let kept: Vec<&str> = body + .lines() + .filter(|l| !l.trim_start().starts_with(STAMP_START)) + .collect(); + let body = kept.join("\n"); + if head.is_empty() { + return body.trim_end().to_string(); } - super::security_fixes::rebuild_at_head( - state, - github, - team_id, - &format!("{owner}/{repo}"), - number, - ticket_id, + format!("{}\n\n{STAMP_START}{head}{STAMP_END}", body.trim_end()) +} + +/// Whether the description was built for `head`. +pub fn is_current(body: &str, head: &str) -> bool { + !head.is_empty() && stamp_of(body) == Some(head) +} + +/// How a reconcile ended. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Reconciled { + /// The description was already built for the head (or the pull request + /// is closed). + Current, + /// It was rebuilt and stamped for the head. + Rebuilt, + /// It could not be read or written: it may still be of another head. + Failed(String), +} + +/// Rebuilds the description when its stamp is not the pull request's head. +/// Every place that rests on the description calls this first: each step +/// that pushed (`reconcile_moved`), the checks and settle step, a review of +/// CoderHelm's own pull request, the pull request watch, and the end of the +/// run, which never completes while the two differ. +pub async fn reconcile( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + number: u64, + ticket_id: &str, +) -> Reconciled { + build( + state, github, team_id, owner, repo, number, ticket_id, false, ) - .await; + .await +} + +/// [`reconcile`] whatever the stamp says: something the description shows +/// changed on the same head (its CI ended, the model rewrote its prose). +pub async fn rebuild( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + number: u64, + ticket_id: &str, +) -> Reconciled { + build(state, github, team_id, owner, repo, number, ticket_id, true).await +} + +#[allow(clippy::too_many_arguments)] +async fn build( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + number: u64, + ticket_id: &str, + force: bool, +) -> Reconciled { + if number == 0 { + return Reconciled::Current; + } + let pr = match github.get_pull_request(owner, repo, number).await { + Ok(p) => p, + Err(e) => return Reconciled::Failed(format!("the pull request could not be read: {e}")), + }; + if pr["state"].as_str().is_some_and(|s| s != "open") { + return Reconciled::Current; + } + let body = pr["body"].as_str().unwrap_or(""); + let head = pr["head"]["sha"].as_str().unwrap_or(""); + if head.is_empty() { + return Reconciled::Failed("the pull request names no head".into()); + } + if !force && is_current(body, head) { + return Reconciled::Current; + } + // Everything computed from the branch, for this head: a dependency + // pull request's table, counts, "What to check" and Proof. + let computed = if common::security_fixes::is_ticket(ticket_id) { + super::security_fixes::at_head( + state, + github, + team_id, + &format!("{owner}/{repo}"), + number, + ticket_id, + &pr, + ) + .await + } else { + None + }; + let next = with_stamp(computed.as_deref().unwrap_or(body), head); + if next == body { + return Reconciled::Current; + } + match save(github, owner, repo, number, &next).await { + Ok(()) => { + tracing::info!(pr_number = number, %head, was = stamp_of(body).unwrap_or("none"), "Description rebuilt for the head"); + Reconciled::Rebuilt + } + Err(e) => Reconciled::Failed(format!("the description could not be saved: {e}")), + } +} + +/// [`reconcile`] for a run's pull request, its ticket read from the run. +pub async fn reconcile_run( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + run_id: &str, + owner: &str, + repo: &str, + number: u64, +) -> Reconciled { + let ticket = run_ticket(state, team_id, run_id).await; + reconcile(state, github, team_id, owner, repo, number, &ticket).await +} + +async fn run_ticket(state: &WorkerState, team_id: &str, run_id: &str) -> String { + use aws_sdk_dynamodb::types::AttributeValue as A; + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", A::S(team_id.to_string())) + .key("run_id", A::S(run_id.to_string())) + .projection_expression("ticket_id") + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get("ticket_id").and_then(|v| v.as_s().ok()).cloned()) + .unwrap_or_default() +} + +/// Every branch CoderHelm moved while handling a message gets its pull +/// request's description rebuilt for the new head. Called once, where +/// every message ends (`main::handle_message`); the branches come from the +/// one place every request leaves the GitHub client, so no code path that +/// pushes has to remember anything. +pub async fn reconcile_moved(state: &WorkerState, team_id: Option<&str>) { + let moved = crate::clients::github::take_moved_branches(); + let Some(team_id) = team_id else { + return; + }; + for m in moved { + let Ok(github) = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + m.installation_id, + &state.http, + ) else { + continue; + }; + let Ok(Some(pr)) = github + .find_open_pr_for_branch(&m.owner, &m.repo, &m.branch) + .await + else { + continue; + }; + let Some(number) = pr["number"].as_u64() else { + continue; + }; + // Only a run's own pull request: its run names its ticket. + let Some(run_id) = + super::review_pr::lookup_run_by_pr(state, team_id, &m.owner, &m.repo, number).await + else { + continue; + }; + if let Reconciled::Failed(why) = + reconcile_run(state, &github, team_id, &run_id, &m.owner, &m.repo, number).await + { + warn!(pr_number = number, why, "The description could not be rebuilt after a push; the next step that reads it rebuilds it"); + } + } +} + +/// How an [`edit`] ended. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Edited { + Saved(String), + Unchanged, + /// The pull request's head is no longer the one the edit is about. + HeadMoved, + Failed(String), +} + +/// Changes one part of a description on the description as GitHub has it +/// now, never on a copy read earlier: a review that ran for minutes once +/// wrote back the copy it had read at its start, with its own section +/// added, and undid every write made in between. `of_head`: the head the +/// change is about; when the pull request has moved past it, nothing is +/// written (a review of a superseded head says nothing about this one). +pub async fn edit( + github: &GitHubClient, + owner: &str, + repo: &str, + number: u64, + of_head: Option<&str>, + change: impl FnOnce(&str) -> String, +) -> Edited { + let pr = match github.get_pull_request(owner, repo, number).await { + Ok(p) => p, + Err(e) => return Edited::Failed(e.to_string()), + }; + let body = pr["body"].as_str().unwrap_or(""); + let head = pr["head"]["sha"].as_str().unwrap_or(""); + if of_head.is_some_and(|h| !h.is_empty() && !head.is_empty() && h != head) { + return Edited::HeadMoved; + } + let next = change(body); + if next == body { + return Edited::Unchanged; + } + match save(github, owner, repo, number, &next).await { + Ok(()) => Edited::Saved(next), + Err(e) => Edited::Failed(e.to_string()), + } } /// A round's account, checked: `(the account without any sentence that @@ -285,6 +527,87 @@ mod tests { assert!(sec.matches("sec::pr_body_at_head(").count() >= 3); } + #[test] + fn a_description_names_the_head_it_was_built_for() { + let body = "## Summary\n\nKept glob-walk on the 2 line.\n"; + assert_eq!(stamp_of(body), None); + assert!(!is_current(body, "aaa111")); + let stamped = with_stamp(body, "aaa111"); + assert_eq!(stamp_of(&stamped), Some("aaa111")); + assert!(is_current(&stamped, "aaa111")); + assert!(!is_current(&stamped, "bbb222"), "another head: rebuilt"); + // One stamp, replaced in place, wherever a writer left the old one. + let moved = format!("{stamped}\n\n## Open items\n- One thing.\n"); + let again = with_stamp(&moved, "bbb222"); + assert_eq!(again.matches(STAMP_START).count(), 1); + assert_eq!(stamp_of(&again), Some("bbb222")); + assert!(again.contains("- One thing.")); + assert_eq!( + with_stamp(&again, "bbb222"), + again, + "stamping is idempotent" + ); + } + + /// Every place that rests on the description reconciles it first, and + /// a run never completes while stamp and head differ. + #[test] + fn everything_that_rests_on_the_description_reconciles_it_first() { + let main = include_str!("../main.rs"); + let handle = &main[main.find("\nasync fn handle_message(").unwrap()..]; + let handle = &handle[..handle.find("\nasync fn handle_message_inner(").unwrap()]; + assert!(handle.contains("description::reconcile_moved(")); + let pr = include_str!("pr.rs"); + let checks = &pr[pr.find("pub async fn apply_checks(").unwrap()..]; + let checks = &checks[..checks.find("\n}\n").unwrap()]; + assert!( + checks.contains("description::reconcile("), + "the checks and settle step" + ); + let run = &pr[pr.find("\npub async fn run(").unwrap()..]; + let run = &run[..run.find("\nasync fn notify_alert_pr(").unwrap()]; + assert!( + run.contains("description::reconcile("), + "the first description" + ); + let review = include_str!("review_pr.rs"); + assert!( + review.contains("description::reconcile_run("), + "before a review of its own pull request" + ); + assert!( + review.contains("description::edit("), + "a review writes on the description as it is now" + ); + let watch = include_str!("pr_watch.rs"); + assert!( + watch.contains("description::reconcile_run("), + "the pull request watch" + ); + let resume = include_str!("resume.rs"); + let done = &resume[resume.find("\nasync fn complete_run_with_status(").unwrap()..]; + let gate = done + .find("description::reconcile(") + .expect("the end of the run"); + let redrive = done.find("redrive_stale_items(").unwrap(); + assert!(gate < redrive, "before anything else at completion"); + assert!( + done[gate..redrive].contains("return Err("), + "a run never completes on another head's description" + ); + // The dependency sections are computed in one function, called only + // from here. + for (path, text) in sources() { + if path == "passes/description.rs" || path.starts_with("passes/incidents/") { + continue; + } + assert!( + !code(&text).contains("security_fixes::at_head("), + "{path} builds the dependency sections past description::reconcile" + ); + } + } + #[test] fn a_description_never_says_it_cannot_be_edited() { let body = "## Summary\n\nKept glob-walk on the 2 line.\n\n## Open items\n- I can't edit the PR description from here.\n- The studio build was not run.\n"; diff --git a/services/worker/src/passes/incidents/am_description_from_the_head.rs b/services/worker/src/passes/incidents/am_description_from_the_head.rs index 5c46c357a..028b9ea45 100644 --- a/services/worker/src/passes/incidents/am_description_from_the_head.rs +++ b/services/worker/src/passes/incidents/am_description_from_the_head.rs @@ -189,7 +189,7 @@ fn a_rebuild_replaces_the_stale_sections_in_place() { ); // The pipeline rebuilds those sections from the head, in one place. let src = include_str!("../security_fixes.rs"); - let rebuild = fn_src(src, "pub(crate) async fn rebuild_at_head("); + let rebuild = fn_src(src, "pub(crate) async fn at_head("); assert!(rebuild.contains("head_facts(")); assert!(rebuild.contains("sec::pr_body_at_head(")); assert!(rebuild.contains("rebuilt_body(body, &fresh)")); @@ -197,7 +197,8 @@ fn a_rebuild_replaces_the_stale_sections_in_place() { for heading in ["\"## Summary\"", "\"## What to check\"", "\"## Proof\""] { assert!(pure.contains(heading), "{heading}"); } - assert!(rebuild.contains("description::save(")); + let reconcile = include_str!("../description.rs"); + assert!(reconcile.contains("security_fixes::at_head(")); } /// Every section CoderHelm owns elsewhere survives a rebuild word for diff --git a/services/worker/src/passes/incidents/ar_description_stamped_to_the_head.rs b/services/worker/src/passes/incidents/ar_description_stamped_to_the_head.rs new file mode 100644 index 000000000..06d6b125c --- /dev/null +++ b/services/worker/src/passes/incidents/ar_description_stamped_to_the_head.rs @@ -0,0 +1,298 @@ +//! ar. A dependency run's pull request was described from a head, and then +//! the head moved on without it. A feedback round changed an override in +//! the manifest and the description was rebuilt on that commit, where the +//! lockfile still resolved the old version ("1.4.4-lts.1, not moved on the +//! head"). The lockfile was regenerated in the commits after it, the run's +//! checks ran again and the run completed. The description still said not +//! moved, still counted the advisory as not fixed, still listed the package +//! under open findings and "the lockfile is out of sync" under Open items. +//! CoderHelm's own review of the final head saw it and left it as a note. +//! +//! What let it through: +//! +//! - the checks step on an open pull request wrote its own sections and +//! never the ones computed from the lockfile, and a regenerated lockfile +//! was pushed with nothing after it; +//! - a review wrote its findings into the copy of the description it had +//! read when it started, so a review that began before a rebuild and +//! ended after it put the older description back, and a review of a head +//! already replaced wrote that head's findings onto the new one; +//! - an item about the lockfile was CoderHelm's own and so was never +//! checked again; +//! - a finding that the description was behind the code was a wording nit, +//! and nits on CoderHelm's own pull request ended the loop. +//! +//! Guarantee: the description names the head it was built for, and +//! whenever that is not the pull request's head it is rebuilt: after every +//! message in which CoderHelm moved the branch (seen where every request +//! leaves the GitHub client), in the checks and settle step, before a +//! review of its own pull request, in the pull request watch, and at the +//! end of the run, which never completes while the two differ. A review +//! writes on the description as it is now and only for the head it +//! reviewed. A lockfile-out-of-sync item is checked on the head. A finding +//! that the description is behind is settled by the rebuild, and every +//! finding that is not pure style is CoderHelm's to act on. + +use super::fixture::*; +use crate::clients::github::branch_moved_by; +use crate::passes::completeness::{self, Section}; +use crate::passes::{description, own_review, security_fixes, settle}; +use common::dep_head::{self, LockAt}; +use common::security_fixes::{self as sec, Advisory, Bump, Finding, FindingState, FixUnit}; + +fn unit() -> FixUnit { + FixUnit { + repo: format!("{OWNER}/{REPO}"), + ecosystem: "npm".into(), + bundle: true, + bumps: vec![Bump { + package: "xml-kit".into(), + from: "1.4.4-lts.1".into(), + to: "2.0.3".into(), + major: true, + manifest: "pnpm-lock.yaml".into(), + }], + ..Default::default() + } +} + +fn finding() -> (Finding, FindingState) { + ( + Finding { + id: "f-1".into(), + package: "xml-kit".into(), + version: "1.4.4-lts.1".into(), + fixed_version: Some("2.0.3".into()), + manifest: "pnpm-lock.yaml".into(), + advisory: Advisory { + primary: "GHSA-xxxx-0009".into(), + ids: vec!["GHSA-xxxx-0009".into()], + ..Default::default() + }, + ..Default::default() + }, + FindingState::default(), + ) +} + +fn at(head_version: &str) -> LockAt { + let copies = |v: &str| Some(vec![("xml-kit".to_string(), v.to_string())]); + LockAt { + path: "pnpm-lock.yaml".into(), + base: copies("1.4.4-lts.1"), + head: copies(head_version), + why: String::new(), + } +} + +/// The description as it was built on `sha`, stamped for it. +fn described(sha: &str, resolved: &str) -> String { + let (unit, (f, st)) = (unit(), finding()); + let head = dep_head::resolve(&unit, sha, &[at(resolved)]); + let body = sec::pr_body_at_head( + &unit, + &[(&f, &st)], + "Bumped.", + &common::upgrade_notes::WhatToCheck::default(), + &sec::BodyLinks::default(), + &head, + ); + description::with_stamp(&body, sha) +} + +/// The manifest's head and the lockfile's head: the description built on +/// the first is not current on the second, and the rebuild leaves nothing +/// of the first. +#[test] +fn a_description_of_an_earlier_head_is_rebuilt_for_the_head() { + let (h1, h2) = ("1111111aaaa", "2222222bbbb"); + let on_manifest = described(h1, "1.4.4-lts.1"); + assert!(on_manifest.contains("1.4.4-lts.1, not moved on the head")); + assert!(on_manifest.contains("Not fixed on the head: GHSA-xxxx-0009")); + assert!(description::is_current(&on_manifest, h1)); + // The lockfile is regenerated: another head. + assert!(!description::is_current(&on_manifest, h2), "stale: rebuilt"); + let fresh = described(h2, "2.0.3"); + let rebuilt = description::with_stamp(&security_fixes::rebuilt_body(&on_manifest, &fresh), h2); + let mut end = Ending::default(); + end.said(rebuilt.clone()); + assert!( + end.says("| `xml-kit` | 1.4.4-lts.1 to 2.0.3 (major) |"), + "{rebuilt}" + ); + assert!(end.says("Fixes 1 of 1 advisory"), "{rebuilt}"); + end.never_says("not moved on the head"); + end.never_says("Not fixed on the head"); + assert!(description::is_current(&rebuilt, h2)); + assert_eq!(rebuilt.matches(description::STAMP_START).count(), 1); +} + +/// A review that started on the earlier description and ended after the +/// rebuild: written the old way it puts the earlier description back. +/// Written on the description as it is now, it adds only its section; and +/// for a head already replaced it writes nothing. +#[test] +fn a_review_never_writes_back_the_description_it_started_with() { + let read_at_start = described("1111111aaaa", "1.4.4-lts.1"); + let now = described("2222222bbbb", "2.0.3"); + let section = own_review::section(&["Scope the override (`package.json:12`)".to_string()]); + // The old way: the section added to the copy read at the start. + let clobbered = + completeness::with_section(&read_at_start, Section::OpenFindings, section.clone()); + assert!( + clobbered.contains("not moved on the head"), + "what the run shipped" + ); + // On the description as it is now. + let edited = completeness::with_section(&now, Section::OpenFindings, section); + assert!(!edited.contains("not moved on the head")); + assert!(edited.contains("1.4.4-lts.1 to 2.0.3 (major)")); + assert!(edited.contains("Scope the override")); + assert!( + description::is_current(&edited, "2222222bbbb"), + "the stamp survives a section write" + ); + let review = include_str!("../review_pr.rs"); + let write = &review[review + .find("let section = super::own_review::section(&own_open);") + .unwrap()..]; + let write = &write[..1800]; + assert!(write.contains("description::edit(")); + assert!( + write.contains("Some(&head_sha)"), + "only for the head it reviewed" + ); + assert!( + !write.contains("pr_body"), + "never the copy read when the review started" + ); + let edit = include_str!("../description.rs"); + let edit = fn_src(edit, "pub async fn edit("); + assert!(edit.find("get_pull_request(").unwrap() < edit.find("change(body)").unwrap()); + assert!(edit.contains("Edited::HeadMoved")); +} + +/// Every push is seen where requests leave the client, and the message +/// that made it ends with the rebuild. The run cannot complete on another +/// head's description. +#[test] +fn every_push_is_followed_by_the_rebuild_and_no_run_completes_stale() { + // The pushes of this run: a round's landing, a regenerated lockfile, a + // take-out. Each is a ref update, a contents write or a merge. + for (method, path, body) in [ + ( + "PATCH", + "/repos/acme/site/git/refs/heads/coderhelm/security-1", + r#"{"sha":"a","force":false}"#, + ), + ( + "POST", + "/repos/acme/site/git/refs", + r#"{"ref":"refs/heads/coderhelm/security-1","sha":"a"}"#, + ), + ( + "PUT", + "/repos/acme/site/contents/pnpm-lock.yaml", + r#"{"branch":"coderhelm/security-1"}"#, + ), + ( + "POST", + "/repos/acme/site/merges", + r#"{"base":"coderhelm/security-1","head":"main"}"#, + ), + ] { + assert_eq!( + branch_moved_by(method, path, body.as_bytes()), + Some(("acme".into(), "site".into(), "coderhelm/security-1".into())), + "{method} {path}" + ); + } + let client = include_str!("../../clients/github.rs"); + let tracked = fn_src(client, "async fn send_tracked("); + assert!(tracked.contains("branch_moved_by(") && tracked.contains("note_branch_moved(")); + let main = include_str!("../../main.rs"); + let handle = fn_src(main, "async fn handle_message("); + let inner = handle.find("handle_message_inner(").unwrap(); + assert!(handle[inner..].contains("description::reconcile_moved(")); + // The paths that pushed in this run and called nothing: all end in a + // reconcile now, without knowing about it. + let pr = include_str!("../pr.rs"); + assert!(fn_src(pr, "pub async fn apply_checks(").contains("description::reconcile(")); + let resume = include_str!("../resume.rs"); + let done = fn_src(resume, "async fn complete_run_with_status("); + let gate = done.find("description::reconcile(").unwrap(); + assert!(gate < done.find("redrive_stale_items(").unwrap()); + assert!(done[gate..].contains("return Err(")); +} + +/// "The lockfile is out of sync" was true of the manifest's head. On the +/// head with the regenerated lockfile the checks install and pass, and the +/// item goes. +#[test] +fn an_item_about_the_earlier_head_does_not_survive_the_checks_of_this_one() { + let item = crate::passes::proof::Finding { + point: "check_blocked".into(), + detail: "The lockfile is out of sync with the manifests this pull request changes.".into(), + ..Default::default() + }; + let facts = settle::Facts { + dep_change: true, + planned_by_rules: true, + ..Default::default() + }; + assert_eq!( + settle::classify(&item, &facts), + settle::Class::Run(vec![settle::Action::LockSync]) + ); + let mut rec = settle::Record::default(); + rec.for_head("2222222bbbb"); + rec.checked = true; + rec.ran = vec!["build".into()]; + rec.passed = vec!["build".into()]; + let settled = settle::apply(vec![item], &facts, &rec); + assert!(settled.open.is_empty(), "{:?}", settled.open); + let mut end = Ending::default(); + end.said(crate::passes::proof::gaps_section(&settled.open)); + end.never_says("out of sync"); +} + +/// The reviewer's note on the final head: the table still says not moved. +/// It is never optional, the rebuild settles it, and an optional +/// improvement is acted on too; only pure style is left. +#[test] +fn a_finding_on_coderhelms_own_pull_request_is_acted_on() { + let f = |v: serde_json::Value| -> crate::passes::review_agent::Finding { + let mut base = + serde_json::json!({"file": "package.json", "line": 12, "title": "t", "body": "b"}); + for (k, val) in v.as_object().unwrap() { + base[k] = val.clone(); + } + serde_json::from_value(base).unwrap() + }; + let stale = f(serde_json::json!({ + "title": "The PR description still says xml-kit was not moved", + "body": "pnpm-lock.yaml resolves xml-kit to 2.0.3; the description's table still lists `1.4.4-lts.1, not moved on the head` and counts its advisory as not fixed.", + "category": "wording", "severity": "low", "optional": true + })); + let improvement = f( + serde_json::json!({"title": "Drop the unused override", "category": "maintainability", "optional": true}), + ); + let style = f(serde_json::json!({"title": "Rename the script", "category": "naming"})); + assert!(own_review::about_description(&stale)); + let required = own_review::required(&[stale, improvement, style], &[]); + assert_eq!(required.len(), 2, "{required:?}"); + assert!(required[0].starts_with("The PR description still says")); + assert!(required[1].starts_with("Drop the unused override")); + // The review rebuilds the description for such a finding before it + // decides what is open, and drops the finding the rebuild settled. + let review = include_str!("../review_pr.rs"); + let at = review + .find("findings.iter().any(super::own_review::about_description)") + .unwrap(); + let after = &review[at..at + 1600]; + assert!(after.contains("description::rebuild(")); + assert!(after.contains("findings.retain(")); + assert!( + after.find("description::rebuild(").unwrap() < after.find("own_review::required(").unwrap() + ); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 09e07c6be..4fa021df0 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -30,6 +30,7 @@ mod al_learning_loop; mod am_description_from_the_head; mod an_six_database_findings; mod ao_stopped_log_finding; +mod ar_description_stamped_to_the_head; mod b_open_pr_retry; mod ba_verdict_on_old_commit; mod bb_flaky_not_broken; diff --git a/services/worker/src/passes/own_review.rs b/services/worker/src/passes/own_review.rs index 97598c4c2..7376e0b93 100644 --- a/services/worker/src/passes/own_review.rs +++ b/services/worker/src/passes/own_review.rs @@ -5,9 +5,9 @@ //! with the merge armed: a person was handed a PR with three known open //! issues. //! -//! On CoderHelm's own PRs every finding that isn't strictly optional (a -//! preference the reviewer inferred, or an optional improvement where the -//! code is correct, see [`super::review_severity::optional`]) is work the +//! 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: //! //! - The review lists them at the top of the description under "Open review @@ -45,7 +45,7 @@ pub const START: &str = ""; pub const END: &str = ""; /// The findings CoderHelm must fix on its own PR, one line each: every -/// finding but the strictly optional ones, questions the change doesn't +/// finding but pure style, questions the change doesn't /// rest on, and notes a policy made (a follow-up the PR tracks, a problem /// it didn't cause). `held_late` are blockers held as notes because they /// came late: they are still defects to fix. @@ -63,15 +63,58 @@ pub fn required(findings: &[Finding], held_late: &[Finding]) -> Vec { .iter() .filter(|f| { f.holds_merge() + || about_description(f) || (f.note_only.is_none() && f.evidence() != Evidence::Question - && !super::review_severity::optional(f)) + && !super::review_severity::pure_style(f)) }) .chain(held_late.iter()) .map(line) .collect() } +/// 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 +/// CoderHelm's to rebuild from the head (`description::rebuild`), which is +/// what settles it. +pub fn about_description(f: &Finding) -> bool { + let text = format!("{} {}", f.title, f.body).to_lowercase(); + let names = [ + "pr description", + "pull request description", + "pull request's description", + "pr body", + "the description", + ] + .iter() + .any(|n| text.contains(n)); + let behind = [ + "still says", + "still lists", + "still shows", + "still counts", + "still claims", + "still describes", + "stale", + "out of date", + "outdated", + "does not match", + "doesn't match", + "no longer", + "mismatch", + "inaccurate", + "contradicts", + "not updated", + "wasn't updated", + "was not updated", + "disagrees with", + ] + .iter() + .any(|b| text.contains(b)); + names && behind +} + /// One line for an earlier review thread still open: its title (the first /// line of the comment, without markdown emphasis) and where it is, as /// [`required`] writes a finding. @@ -425,7 +468,7 @@ mod tests { } #[test] - fn everything_but_the_strictly_optional_is_fixed() { + fn everything_but_pure_style_is_fixed() { let mut tracked = finding(json!({"title": "Tracked", "category": "bug"})); super::super::review_policy::demote(&mut tracked, "tracked"); let fs = vec![ @@ -447,10 +490,53 @@ mod tests { required(&fs, &late), vec![ "Watermark skips rows (`src/a.rs:3`)".to_string(), + // An optional improvement to working code is not style: it + // is acted on before the run finishes. + "Could cache this (`src/a.rs:3`)".to_string(), "Network might be slow (`src/a.rs:9`)".to_string(), "Late bug (`b.rs`)".to_string(), - ] + ], + "a rename is pure style and stays a note" + ); + } + + /// The description being behind the code is never a note left for a + /// person, whatever severity or category the reviewer gave it. + #[test] + fn a_finding_that_the_description_is_behind_is_never_optional() { + let stale = finding(json!({ + "title": "PR description still says the package was not moved", + "body": "The lockfile resolves path-match to 2.0.3, but the description's table still lists it as not moved on the head.", + "category": "wording", "severity": "low", "optional": true + })); + assert!(about_description(&stale)); + assert_eq!( + required(std::slice::from_ref(&stale), &[]), + vec!["PR description still says the package was not moved (`src/a.rs:3`)".to_string()] + ); + for (title, body) in [ + ("Rename x", "The name does not match the convention."), + ( + "Typo in the description", + "The description has a typo in the second paragraph.", + ), + ( + "Stale comment", + "The comment above the function is out of date.", + ), + ( + "Meta description missing", + "The page's meta description tag is no longer set.", + ), + ] { + let f = finding(json!({"title": title, "body": body, "category": "wording"})); + assert!(!about_description(&f), "{title}"); + } + let typo = finding( + json!({"title": "Typo in the description", "body": "The description has a typo.", "category": "naming"}), ); + assert!(!about_description(&typo)); + assert!(required(&[typo], &[]).is_empty()); } #[test] diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 591f0fa92..97c699e10 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -854,6 +854,17 @@ Return ONLY the markdown body text."#, usage, ) .await; + // The description names the head it was built for from the start. + crate::passes::description::reconcile( + state, + github, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + pr_number, + &msg.ticket_id, + ) + .await; Ok(PrResult { pr_number, @@ -1649,6 +1660,19 @@ pub async fn apply_checks( // What the reviewer reads first, from the diff and the head's recorded // check results as they stand now. super::reviewer_guide::refresh(github, &msg.repo_owner, &msg.repo_name, number).await; + // This step may have pushed (a settle check's take-out, a regenerated + // lockfile) since the description was built: everything computed from + // the branch is of this head before the step ends. + crate::passes::description::reconcile( + state, + github, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + number, + &msg.ticket_id, + ) + .await; } /// Heading over what only a person can check, when the checks found some. diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index a55d40ba9..219bdc66a 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -424,6 +424,11 @@ async fn perform( seen: &Seen, act: &Act, ) -> bool { + // Whatever the watch does next rests on a description of this head. + super::description::reconcile_run( + state, github, &c.team_id, &c.run_id, &c.owner, &c.repo, c.pr, + ) + .await; match act { Act::Nothing => true, Act::ResolveConflict => { diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 551e0c4a6..0f5b01eba 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -7130,6 +7130,34 @@ async fn complete_run_with_status( duration: u64, ) -> Result<(), Box> { debug_assert_ne!(status, "needs_input", "use wait_for_review"); + // A run never completes on a description built for another head: it is + // rebuilt for the head first, and when that cannot be done this step + // ends in an error and is tried again. + if status == common::run_status::COMPLETED && pr_number > 0 { + if let Ok(github) = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + msg.installation_id, + &state.http, + ) { + if let super::description::Reconciled::Failed(why) = super::description::reconcile( + state, + &github, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + pr_number, + &msg.ticket_id, + ) + .await + { + return Err(format!( + "the pull request's description is not of its head and could not be rebuilt: {why}" + ) + .into()); + } + } + } // Open items written on an earlier head are not this run's last word: a // later round may have settled one. The run goes back to its checks on // the head first, and finishes from there. diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index ec274bdc7..79dce3154 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -1586,6 +1586,43 @@ async fn run_once( let pr = github .get_pull_request(&msg.repo_owner, &msg.repo_name, msg.pr_number) .await?; + // CoderHelm's own pull request is reviewed against a description built + // for the head under review, never an earlier one. + let own_run = if pr["user"]["login"] + .as_str() + .is_some_and(|l| l.contains("coderhelm")) + { + lookup_run_by_pr( + state, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + ) + .await + } else { + None + }; + let pr = match &own_run { + Some(run_id) + if super::description::reconcile_run( + state, + &github, + &msg.team_id, + run_id, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + ) + .await + == super::description::Reconciled::Rebuilt => + { + github + .get_pull_request(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await? + } + _ => pr, + }; // Coalesce rapid commits: if a newer commit has landed since this verdict // review was enqueued, skip it — the newer commit's own review covers the @@ -3418,6 +3455,29 @@ async fn run_once( // every finding that isn't strictly optional is its own to fix before // the PR is marked ready or the merge armed: the review requests changes // and lists them at the top of the description (`own_review`). + // A finding that the description is behind the code is CoderHelm's to + // settle by rebuilding the description, never a note left for a person: + // the rebuild runs now, and a finding it settled is not raised. + if self_authored && findings.iter().any(super::own_review::about_description) { + let ticket = match &own_run { + Some(run_id) => run_ticket_id(state, &msg.team_id, run_id).await, + None => String::new(), + }; + let rebuilt = super::description::rebuild( + state, + &github, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + &ticket, + ) + .await; + info!(pr = msg.pr_number, head = %head_sha, ?rebuilt, "The review found the description behind the code: rebuilt from the head"); + if rebuilt == super::description::Reconciled::Rebuilt { + findings.retain(|f| f.holds_merge() || !super::own_review::about_description(f)); + } + } let mut own_open = if self_authored { super::own_review::required(&findings, &held_late) } else { @@ -3573,24 +3633,33 @@ async fn run_once( let mut description_after = pr_body.to_string(); if self_authored { let section = super::own_review::section(&own_open); - let updated = super::completeness::with_section( - pr_body, - super::completeness::Section::OpenFindings, - section, - ); - if updated != pr_body { - if let Err(e) = crate::passes::description::save( - &github, - &msg.repo_owner, - &msg.repo_name, - msg.pr_number, - &updated, - ) - .await - { + // On the description as it is now, and only while this review's + // head is still the pull request's: a copy read when the review + // started would undo every write made since, and a review of a + // head that has been replaced says nothing about the new one. + match crate::passes::description::edit( + &github, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + Some(&head_sha), + |now| { + super::completeness::with_section( + now, + super::completeness::Section::OpenFindings, + section, + ) + }, + ) + .await + { + crate::passes::description::Edited::Saved(updated) => description_after = updated, + crate::passes::description::Edited::Unchanged => {} + crate::passes::description::Edited::HeadMoved => { + info!(pr = msg.pr_number, head = %head_sha, "The head moved during this review: its findings are not written into the description of the new head"); + } + crate::passes::description::Edited::Failed(e) => { warn!(pr = msg.pr_number, error = %e, "Could not update the own PR's open review findings"); - } else { - description_after = updated; } } if !own_open.is_empty() { @@ -4969,6 +5038,23 @@ async fn plan_evidence_for_pr(state: &WorkerState, msg: &ReviewMessage) -> Strin .unwrap_or_default() } +/// The ticket of a run, from its record (empty when it has none). +async fn run_ticket_id(state: &WorkerState, team_id: &str, run_id: &str) -> String { + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("ticket_id") + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get("ticket_id").and_then(|v| v.as_s().ok()).cloned()) + .unwrap_or_default() +} + /// Newest run for a PR, via the runs-table repo-index GSI. None if untracked. pub(crate) async fn lookup_run_by_pr( state: &WorkerState, diff --git a/services/worker/src/passes/review_severity.rs b/services/worker/src/passes/review_severity.rs index 60537d7ee..a6576c74d 100644 --- a/services/worker/src/passes/review_severity.rs +++ b/services/worker/src/passes/review_severity.rs @@ -241,12 +241,11 @@ pub fn label(f: &Finding) -> Option