diff --git a/docs/incidents.md b/docs/incidents.md index ba67f7d9e..21ae72a02 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -94,6 +94,7 @@ pipeline still calls it there. | bn. `bn_infra_list_follows_aws` | Security, Infrastructure kept ten rows while AWS had moved on: an RDS instance deleted two days before still showed two pending actions, a Lambda function on a retired runtime came from a Terraform module nothing called, five rows already fixed kept their Runbook and Fix PR buttons, an older CVE row and the engine patch to the same version stood as two rows, and a serverless platform update and an operating system update on each instance AWS listed never appeared. The read kept every resource for three days and the match took them all as running. | Each read says which kinds it saw in full; what a full read no longer lists is dropped and its findings close as removed, with the time; a failed or partial read drops and closes nothing. The same move on one database is one item. Every pending action is an item, applied by CoderHelm after one approval when it has no code change, and a version change on a resource in code is a pull request whichever source raised it. Closed items offer nothing to do. Opening the page refreshes a read older than five minutes, at most once per team in that time. | | bp. `bp_repo_traced_not_asked` | A secrets finding on a production API's log group posted "Which repo should this fix go to?" with the right repo as its best guess, two others as "also possible", no fix started, and "there is no direct AWS pointer" as its reason. The task definition's image came from an ECR repository named for the app plus its environment word, tagged with the app's name and the commit it was built from, and pushed by the app repo's workflow; none of it counted, and the hedged answer was cached for a week. | The repo is traced (`common::log_repo`): the running image's commit is looked up in every repo's history, a workflow or build file that ships the image counts as shipping it while Terraform that only defines it is context, image repository and tag names count without their environment word, and the classes and text of the error's own lines are looked for in the code. Evidence for one repo starts the fix there, saves the repo and says why in one line; split evidence still starts on the best guess with one card offering "Wrong repo? Move it"; only a log group nothing ties to any repo asks. An older resolver's or an unsure answer is not served from the cache for long. | | bq. `bq_upstream_read_not_guessed` | A card said "1 new log finding: Seen again: Request failed with 503 in AUTH GUARD" for two lines of an error the API logs most days, with "the evidence does not show which upstream service returned the 503", an AWS account id line and a generic link; nothing had read the guard's code, which names the service it calls, and each analysis sent every line of a burst to the model. | A sighting is judged against its own week first (`common::log_triage`, the analyzer's same cases): at its usual rate it is counted with no card and no fix, rising is act, new or back after a quiet week is said once. A failed call's code is read: the card names the upstream (host and setting), its timeout and retries, the lines, tasks and the week's rate, with the decision on the first line and no account id. A burst is one entry before any model call, known errors are counted without the model, and an hourly budget caps analyses. | +| br. `br_description_writer_upgrade` | After the description writer was upgraded (a final review in the one save, the repository's template as the structure), a pull request opened the day before kept its old text: six checks "Not run: still running when this was written", the file to read first and the way back said twice, filler and a raw page id. Its head had not moved and its checked text was unchanged, so its stamp said current and nothing rebuilt it. | The stamp names the writer version (`description::WRITER`, raised with every change to what a description says or how it is laid out); a description built by another writer, or before the version, is not current. The pull request watch's sweep catches up open pull requests CoderHelm opened, whatever the age of their run: a few per team each sweep (`pr_watch::CATCH_UP_PER_TEAM`), inside its GitHub budget, each rebuilt once and marked on its run. A description still wholly CoderHelm's is built again from the facts of the head alone: nothing of the old text is kept, not even in a fold, except a line that closes an issue. A description with no CoderHelm stamp, or whose checked text a person changed, is left as it is. | ## Adding a case diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 399cc4ade..bfc8d7475 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -669,12 +669,15 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe // Finished runs' pull requests: a conflict with a moved base, // checks that went red later, a reviewer verdict missing on the // head, a merge whose deploy nobody watches. Each is picked - // back up by the mechanism it already has. + // back up by the mechanism it already has. Then a few open pull + // requests per team whose description an earlier writer built + // are rebuilt by this one. let watch = as_sweep(who::SWEEP_PR_WATCH, passes::pr_watch::sweep(&state)).await; info!( candidates = watch.candidates, looked_at = watch.looked_at, acted = ?watch.acted, + descriptions_rebuilt = ?watch.caught_up, "Pull request watch sweep done" ); // Deploy counts that stopped between passes carry on without diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index efda5d367..35dd5fe27 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -249,6 +249,7 @@ pub async fn head_moved( m.number, m.ticket_id, true, + false, Some(Reader { provider, usage }), ) .await; @@ -286,24 +287,63 @@ pub fn stamp_of(body: &str) -> Option<&str> { /// The stamp's head and, when it carries one, the digest of the text the /// fact check read. fn stamp_parts(body: &str) -> Option<(&str, Option<&str>)> { - stamp_all(body).map(|(h, d, _)| (h, d)) + stamp_all(body).map(|s| (s.head, s.digest)) } +/// The version of the description writer: what builds, lays out and reviews +/// a description (`description_facts`, `common::pr_layout`, +/// `common::pr_template`, `common::pr_review`). Raise it whenever any of +/// them changes what a description says or how it is laid out: every +/// description stamped by an earlier writer is then not current, and is +/// rebuilt (by the pull request watch's catch-up, [`catch_up`]) even when +/// its head has not moved. +pub const WRITER: u32 = 2; + +/// The stamp's word for the writer version: `writer-`. +const WRITER_WORD: &str = "writer-"; + /// The stamp's word for a description built while checks on its head were /// still running: it is not current until they end and it is rebuilt. const CHECKS_RUNNING: &str = "checks-running"; -/// The stamp's head, digest, and whether checks were running when it was -/// built. -fn stamp_all(body: &str) -> Option<(&str, Option<&str>, bool)> { +/// What a stamp says. +struct Stamp<'a> { + head: &'a str, + /// The digest of the text the fact check read (none on the oldest + /// stamps). + digest: Option<&'a str>, + /// Checks on the head were running when it was built. + running: bool, + /// The writer version that built it (none on stamps from before the + /// version was kept). + writer: Option, +} + +/// The stamp's head, digest, whether checks were running when it was +/// built, and the writer version. A stamp from before any of these parses +/// with that part missing. +fn stamp_all(body: &str) -> Option> { let at = body.rfind(STAMP_START)? + STAMP_START.len(); let rest = &body[at..]; let inner = rest[..rest.find(STAMP_END)?].trim(); let mut parts = inner.split_whitespace(); let head = parts.next().filter(|h| !h.is_empty())?; - let digest = parts.next(); - let running = parts.any(|p| p == CHECKS_RUNNING); - Some((head, digest, running)) + let mut stamp = Stamp { + head, + digest: None, + running: false, + writer: None, + }; + for (i, p) in parts.enumerate() { + if p == CHECKS_RUNNING { + stamp.running = true; + } else if let Some(n) = p.strip_prefix(WRITER_WORD) { + stamp.writer = n.parse().ok(); + } else if i == 0 { + stamp.digest = Some(p); + } + } + Some(stamp) } /// Whether the description shows a check on its head as still running. @@ -353,7 +393,7 @@ pub fn with_stamp(body: &str, head: &str) -> String { String::new() }; format!( - "{}\n\n{STAMP_START}{head} {digest}{running}{STAMP_END}", + "{}\n\n{STAMP_START}{head} {digest} {WRITER_WORD}{WRITER}{running}{STAMP_END}", body.trim_end() ) } @@ -363,22 +403,56 @@ fn same_head(stamped: &str, head: &str) -> bool { stamped == head || (stamped.len() >= 7 && head.starts_with(stamped)) } -/// Whether the description was built for `head`, the text the fact check -/// read is still the text that is there, and no check was running when it -/// was built (a description showing running checks is rebuilt until they -/// end). A stamp from before the digest answers for its head alone. +/// Whether the description was built for `head` by this writer +/// ([`WRITER`]), the text the fact check read is still the text that is +/// there, and no check was running when it was built (a description +/// showing running checks is rebuilt until they end). A stamp from before +/// the writer version is never current: an upgrade rebuilds it. A stamp +/// from before the digest answers for its head and writer alone. pub fn is_current(body: &str, head: &str) -> bool { match stamp_all(body) { - Some((h, digest, running)) => { + Some(s) => { !head.is_empty() - && !running - && same_head(h, head) - && digest.is_none_or(|d| d == checked_digest(body)) + && !s.running + && s.writer == Some(WRITER) + && same_head(s.head, head) + && s.digest.is_none_or(|d| d == checked_digest(body)) } None => false, } } +/// What the catch-up after an upgrade does with an open pull request's +/// description ([`catch_up`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CatchUp { + /// Built for its head by this writer: nothing to do. + Current, + /// CoderHelm's own text, built by an earlier writer or for another + /// head: rebuilt through the one rebuild ([`reconcile`]). + Rebuild, + /// Not CoderHelm's to rebuild here: no stamp (a description CoderHelm + /// never built), or a person changed the text the fact check read + /// since CoderHelm built it. Left as it is; the paths that move the + /// head still rebuild it. + Leave, +} + +/// Whether the catch-up rebuilds `body` on `head`. Only a description that +/// carries CoderHelm's stamp and whose checked text is still what +/// CoderHelm wrote is rebuilt; a person's edit is never written over by a +/// sweep. +pub fn catch_up(body: &str, head: &str) -> CatchUp { + if is_current(body, head) { + return CatchUp::Current; + } + match stamp_all(body) { + None => CatchUp::Leave, + Some(s) if s.digest.is_some_and(|d| d != checked_digest(body)) => CatchUp::Leave, + Some(_) => CatchUp::Rebuild, + } +} + /// How a reconcile ended. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Reconciled { @@ -406,7 +480,7 @@ pub async fn reconcile( ticket_id: &str, ) -> Reconciled { build( - state, github, team_id, owner, repo, number, ticket_id, false, None, + state, github, team_id, owner, repo, number, ticket_id, false, false, None, ) .await } @@ -433,6 +507,7 @@ pub async fn reconcile_read( number, ticket_id, true, + false, Some(reader), ) .await @@ -450,7 +525,7 @@ pub async fn rebuild( ticket_id: &str, ) -> Reconciled { build( - state, github, team_id, owner, repo, number, ticket_id, true, None, + state, github, team_id, owner, repo, number, ticket_id, true, false, None, ) .await } @@ -717,6 +792,9 @@ async fn build( number: u64, ticket_id: &str, force: bool, + // The catch-up's rebuild ([`catch_up_run`]): a description wholly + // CoderHelm's is built again from the facts alone. + fresh: bool, reader: Option>, ) -> Reconciled { if number == 0 { @@ -737,6 +815,11 @@ async fn build( if !force && is_current(&body, &head) { return Reconciled::Current; } + // Read again here, as it is now: a person who edited it since the sweep + // looked is never written over. + if fresh && catch_up(&body, &head) != CatchUp::Rebuild { + return Reconciled::Current; + } // Everything computed from the branch, for this head: a dependency // pull request's table, counts, "What to check" and Proof, and the // lockfile facts they are written from. @@ -756,6 +839,7 @@ async fn build( }; let (base, dependency) = match computed { Some((b, d)) => (b, Some(d)), + None if fresh => (fresh_base(&body), None), None => (body.clone(), None), }; // The facts of this head, and the description as a view of them: every @@ -817,6 +901,45 @@ async fn build( } } +/// The catch-up's rebuild of a run's pull request after an upgrade: when +/// the description is wholly CoderHelm's ([`catch_up`] says Rebuild), it is +/// built again from the facts of the head alone and nothing of the earlier +/// writer's text is kept ([`fresh_base`]), so no old line survives in a +/// fold. Anything else is left as it is. +pub async fn catch_up_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; + build( + state, github, team_id, owner, repo, number, &ticket, false, true, None, + ) + .await +} + +/// What a description wholly CoderHelm's keeps when the catch-up builds it +/// again: only the lines that close an issue (`Closes #12`), which GitHub +/// acts on at merge. Everything else an earlier writer wrote (its lead, +/// its reviewer block, its frozen check rows) is dropped, and the body is +/// rendered from the facts of the head. +pub fn fresh_base(body: &str) -> String { + body.lines() + .map(str::trim) + .filter(|l| { + let l = l.to_lowercase(); + ["closes #", "fixes #", "resolves #"] + .iter() + .any(|k| l.starts_with(k)) + }) + .collect::>() + .join("\n") +} + /// [`reconcile`] for a run's pull request, its ticket read from the run. pub async fn reconcile_run( state: &WorkerState, @@ -1142,6 +1265,52 @@ mod tests { ); } + /// The stamp names the writer that built the description: one from + /// before the version, or from another writer, is not current on an + /// unchanged head; this writer's is. + #[test] + fn a_stamp_names_its_writer_version() { + let body = "## Summary\n\nKept glob-walk on the 2 line.\n"; + let head = "aaa111bbb222ccc"; + let stamped = with_stamp(body, head); + assert!( + stamped.contains(&format!(" {WRITER_WORD}{WRITER} ")), + "{stamped}" + ); + assert!(is_current(&stamped, head)); + assert_eq!(catch_up(&stamped, head), CatchUp::Current); + // The stamp as the writer before the version wrote it: same head, + // same digest, no checks running, and no version. + let digest = checked_digest(body); + let old = format!( + "{}\n\n{STAMP_START}aaa111bbb222 {digest}{STAMP_END}", + body.trim_end() + ); + assert_eq!( + stamp_of(&old), + Some("aaa111bbb222"), + "an old stamp still parses" + ); + assert!(!is_current(&old, head), "no version: not current"); + assert_eq!(catch_up(&old, head), CatchUp::Rebuild); + // An old stamp built while checks ran parses the same way. + let old_running = old.replace(STAMP_END, &format!(" {CHECKS_RUNNING}{STAMP_END}")); + let s = stamp_all(&old_running).unwrap(); + assert!(s.running && s.writer.is_none() && s.digest == Some(digest.as_str())); + // Another writer version: not current either. + let other = stamped.replace( + &format!("{WRITER_WORD}{WRITER}"), + &format!("{WRITER_WORD}{}", WRITER - 1), + ); + assert!(!is_current(&other, head)); + assert_eq!(catch_up(&other, head), CatchUp::Rebuild); + // A body with no stamp is not CoderHelm's to rebuild in the + // catch-up, and one whose checked text a person changed is left. + assert_eq!(catch_up(body, head), CatchUp::Leave); + let edited = old.replace("Kept glob-walk", "We kept glob-walk, see the thread"); + assert_eq!(catch_up(&edited, head), CatchUp::Leave); + } + /// Every place that rests on the description reconciles it first, and /// a run never completes while stamp and head differ. #[test] diff --git a/services/worker/src/passes/incidents/br_description_writer_upgrade.rs b/services/worker/src/passes/incidents/br_description_writer_upgrade.rs new file mode 100644 index 000000000..0a6e544e1 --- /dev/null +++ b/services/worker/src/passes/incidents/br_description_writer_upgrade.rs @@ -0,0 +1,305 @@ +//! br. The description writer was upgraded (a final review in the one save, +//! the repository's template as the structure, a running check never a +//! result), and a pull request opened the day before kept its old text: +//! six check rows "Not run: still running when this was written", "Look +//! first" and "Roll back" said twice, filler and a raw page id. Its head had +//! not moved, its checked text was what CoderHelm wrote, and no check showed +//! as running in the new form, so its stamp said it was current and nothing +//! ever built it again. +//! +//! What let it through: the stamp named the head, the digest of the checked +//! text and running checks, never the writer that built it, so an upgrade +//! changed nothing for a description already written; and the pull request +//! watch rebuilt a description only on its way to another act. +//! +//! Guarantee: the stamp names the writer version (`description::WRITER`, +//! raised with every change to what a description says or how it is laid +//! out), and a description built by another writer, or by one from before +//! the version, is not current. The pull request watch's sweep catches up +//! open pull requests CoderHelm opened, whatever the age of their run: a few +//! per team each sweep, inside its GitHub budget, each rebuilt once and +//! marked on its run. A description still wholly CoderHelm's is built +//! again from the facts of the head alone (then the final review in the +//! save): nothing of the old text is kept, not even in a fold, except a +//! line that closes an issue. A description with no CoderHelm stamp, or +//! whose checked text a person changed, is left as it is. + +use super::fixture::*; +use crate::passes::description::{self, CatchUp}; +use crate::passes::description_facts::{self, Inputs}; +use crate::passes::pr_risk; +use crate::passes::pr_watch::{self, Candidate}; +use crate::passes::reviewer_guide::{Check, State}; + +const HEAD: &str = "5ab6c7d8e9f00112233445566778899aabbccdde"; +const PAGE_ID: &str = "7e1d2c3b-4a59-4687-b0a1-c2d3e4f5a6b7"; + +/// The description as the writer before the upgrade left it (names made +/// up): its lead with the checks frozen as running, the written prose, and +/// the older reviewer block beside the lead. +fn written_before() -> String { + format!( + " + +Adds a length warning to the banner block's caption in the Studio (OPS-12). + +### Review focus + +- Approach: decide whether this does what OPS-12 asks. CoderHelm's conclusion: nothing is out of the ordinary. +- Read first: `apps/studio/blocks/banner-validation.ts` (the largest change to code). +- See it: Studio: Home page ({PAGE_ID}), banner caption field. + +**Rollback:** Revert this pull request; nothing outside the code changes with it. + +### Verification + +On 5ab6c7d (head of this PR): + +| Check | Result | +|---|---| +| Lint (CI) | Not run: still running when this was written | +| Unit tests (CI) | Not run: still running when this was written | +| Type check (CI) | Not run: still running when this was written | +| Build (CI) | Not run: still running when this was written | +| Studio build (CI) | Not run: still running when this was written | +| Test Coverage Report (CI) | Not run: still running when this was written | + + + +## Summary + +Adds a length warning to the banner block's caption in the Studio. + +## Changes + +* `apps/studio/blocks/banner-validation.ts`: the length rule. + + +**For the reviewer** +* **Look first:** `apps/studio/blocks/banner-validation.ts`, the largest change to code. +* **Roll back:** revert this pull request; nothing outside the code changes with it. + +" + ) +} + +/// Stamped as the writer before the version stamped it: head and digest, +/// nothing else. +fn stamped_before(body: &str) -> String { + format!( + "{}\n\n{}{} {} -->", + body.trim_end(), + description::STAMP_START, + &HEAD[..12], + description::checked_digest(body) + ) +} + +/// The catch-up's rebuild on the same head, as `description::catch_up_run` +/// runs it: only a description wholly CoderHelm's is rebuilt, from the +/// facts of the head alone (the checks have passed) with nothing of its +/// old text kept, then stamped and written as the save writes. +fn rebuilt(body: &str) -> String { + if description::catch_up(body, HEAD) != CatchUp::Rebuild { + return body.to_string(); + } + let body = &description::fresh_base(body); + let files = vec![( + "apps/studio/blocks/banner-validation.ts".to_string(), + "added".to_string(), + format!("@@ -1 +1,18 @@\n{}", "+line\n".repeat(18)), + )]; + let floor = pr_risk::floor(&files, &std::collections::HashMap::new()); + let checks: Vec = ["Lint", "Unit tests", "Type check", "Build"] + .iter() + .map(|n| Check { + name: n.to_string(), + url: format!("https://ci.example.com/{}", n.replace(' ', "-")), + state: State::Passed, + }) + .collect(); + let facts = description_facts::facts(&Inputs { + head: HEAD, + body, + files: &files, + floor: &floor, + checks: Some(&checks), + why: None, + dependency: None, + outside: None, + run_url: "", + notes: vec![], + evidence: vec![], + repo_url: "https://github.com/acme/site", + }); + let shaped = + description_facts::shape_for(body, "Warn on long banner captions", facts, None, None); + let next = description::with_stamp(&shaped.body, HEAD); + // What `description::save` writes. + let reviewed = common::pr_review::review(&description::clean(&next)); + common::pr_layout::layout(&common::person_gate::sink(&reviewed.body).text) +} + +/// Before: everything the old stamp named still held on the unchanged +/// head, so it was current and left as it was. After: the missing writer +/// version makes it stale, the catch-up rebuilds it once, and the rebuilt +/// description is current and never picked again. +#[test] +fn an_old_layout_description_on_an_unchanged_head_is_rebuilt_once() { + let old = stamped_before(&written_before()); + // Before: same head, same checked text, no running check in the stamp: + // the three things the stamp used to name all say current. + assert_eq!(description::stamp_of(&old), Some(&HEAD[..12])); + assert!(old.contains(&description::checked_digest(&old))); + assert!(!old.contains("checks-running")); + assert!(!description::shows_running(&old)); + // After: the writer that built it is not this one. + assert!(!description::is_current(&old, HEAD)); + assert_eq!(description::catch_up(&old, HEAD), CatchUp::Rebuild); + + let new = rebuilt(&old); + let end = Ending { + status: "completed".into(), + pr: Some(12), + draft: false, + words: vec![new.clone()], + }; + end.never_says("still running when this was written"); + end.never_says("nothing is out of the ordinary"); + end.never_says(PAGE_ID); + end.never_says("Look first"); + assert!(end.says("| Lint (CI) | Passed |"), "{new}"); + assert_eq!( + new.matches("evert this pull request; nothing outside") + .count(), + 1, + "the way back once: {new}" + ); + // Rebuilt once: current on the head, nothing for the next sweep. + assert!(description::is_current(&new, HEAD), "{new}"); + assert_eq!(description::catch_up(&new, HEAD), CatchUp::Current); + assert_eq!(rebuilt(&new), new, "a second catch-up changes nothing"); +} + +/// An older description, from before the lead and the reviewer block had +/// markers: nothing tells its old lead from its prose. Wholly CoderHelm's +/// (the digest still matches), it is built again from the facts and no +/// old line survives anywhere, not even in a fold; the line that closes +/// its issue is kept. +#[test] +fn an_old_description_without_markers_keeps_no_old_line() { + let unmarked = format!( + "Adds a length warning to the banner block's caption in the Studio (OPS-12). + +### Review focus + +- Approach: decide whether this does what OPS-12 asks. CoderHelm's conclusion: nothing is out of the ordinary. +- Read first: `apps/studio/blocks/banner-validation.ts` (the largest change to code). +- See it: Studio: Home page ({PAGE_ID}), banner caption field. + +**For the reviewer** +* **Look first:** `apps/studio/blocks/banner-validation.ts`, the largest change to code. +* **Roll back:** revert this pull request; nothing outside the code changes with it. +* **Not verified on `5ab6c7d`:** `Lint` (still running); `Studio build` (did not run). + +**Rollback:** Revert this pull request; nothing outside the code changes with it. + +### Verification + +| Check | Result | +|---|---| +| Lint (CI) | Not run: still running when this was written | +| Unit tests (CI) | Not run: still running when this was written | +| Type check (CI) | Not run: still running when this was written | +| Build (CI) | Not run: still running when this was written | +| Studio build (CI) | Not run: still running when this was written | +| Test Coverage Report (CI) | Not run: still running when this was written | + +Closes #12 +" + ); + assert!(!unmarked.contains("")); + assert!(!unmarked.contains("")); + let old = stamped_before(&unmarked); + assert_eq!(description::catch_up(&old, HEAD), CatchUp::Rebuild); + let new = rebuilt(&old); + for line in [ + "still running when this was written", + "Look first", + "Roll back", + "For the reviewer", + "nothing is out of the ordinary", + "(still running)", + "Test Coverage Report", + PAGE_ID, + ] { + assert!(!new.contains(line), "{line:?} is still in: {new}"); + } + assert!(new.contains("| Lint (CI) | Passed |"), "{new}"); + assert!(new.contains("Closes #12"), "the issue still closes: {new}"); + assert!(description::is_current(&new, HEAD), "{new}"); + assert_eq!(rebuilt(&new), new, "rebuilt once"); + // The catch-up runs this path, and the build drops the old body. + let src = include_str!("../description.rs"); + let run = fn_src(src, "\npub async fn catch_up_run("); + assert!(run.contains("false, true, None"), "{run}"); + let build = fn_src(src, "\nasync fn build("); + assert!(build.contains("None if fresh => (fresh_base(&body), None)")); + assert!(build.contains("fresh && catch_up(&body, &head) != CatchUp::Rebuild")); +} + +/// The catch-up never writes over a person: a description with no stamp, +/// or whose checked text a person changed, is left. +#[test] +fn a_persons_description_is_left_as_it_is() { + assert_eq!( + description::catch_up(&written_before(), HEAD), + CatchUp::Leave, + "no CoderHelm stamp" + ); + let edited = stamped_before(&written_before()).replace( + "Adds a length warning", + "Adds a length warning (we agreed 120 characters on the call)", + ); + assert_eq!(description::catch_up(&edited, HEAD), CatchUp::Leave); +} + +/// The sweep reaches every open pull request CoderHelm opened, a few per +/// team each time, and the rebuild runs through the one rebuild. +#[test] +fn the_watch_sweep_catches_up_a_few_per_team() { + let run = |team: &str, n: u32| Candidate { + team_id: team.into(), + run_id: format!("run-{team}-{n}"), + status: "completed".into(), + pr: n as u64 + 1, + installation_id: 1, + updated_at: format!("2026-10-{:02}", n + 1), + ..Default::default() + }; + let mut all: Vec = (0..10).map(|n| run("t1", n)).collect(); + all.push(run("t2", 0)); + let picks = pr_watch::catch_up_picks(all, pr_watch::CATCH_UP_PER_TEAM, pr_watch::CATCH_UP_MAX); + assert_eq!( + picks.iter().filter(|c| c.team_id == "t1").count(), + pr_watch::CATCH_UP_PER_TEAM + ); + assert!(picks.iter().any(|c| c.team_id == "t2")); + + let src = include_str!("../pr_watch.rs"); + let sweep = fn_src(src, "\npub async fn sweep("); + assert!( + sweep.contains("catch_up(state, &mut budget"), + "inside the sweep's budget" + ); + let one = fn_src(src, "\nasync fn catch_up_one("); + assert!(one.contains("description::catch_up(")); + assert!( + one.contains("description::catch_up_run("), + "the rebuild from the facts alone" + ); + let all = fn_src(src, "\nasync fn catch_up("); + assert!(all.contains("budget\n .allows(") || all.contains("budget.allows(")); + // No age window: an old run's open pull request is reached too. + assert!(!all.contains(":cut")); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 9e222ef45..0c6d4782c 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -56,6 +56,7 @@ mod bm_teams_never_cross; mod bn_infra_list_follows_aws; mod bp_repo_traced_not_asked; mod bq_upstream_read_not_guessed; +mod br_description_writer_upgrade; mod c_codegen_egress; mod d_echoed_markers; mod e_large_generated_output; diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 4e98844c1..1904ca260 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -49,6 +49,22 @@ pub const SWEEP_MAX_LOOKS: usize = 40; /// that didn't change costs none (see [`Probe`]). pub const LOOK_REQUESTS: u64 = 8; +/// Open pull requests one sweep rebuilds for each team when their +/// description was built by an earlier writer ([`catch_up_picks`]): a team +/// with many open pull requests is caught up over several sweeps, never in +/// one burst. +pub const CATCH_UP_PER_TEAM: usize = 3; +/// The most descriptions one sweep rebuilds, all teams together. +pub const CATCH_UP_MAX: usize = 15; +/// GitHub requests one catch-up may make (the pull request, then the +/// rebuild: the pull request again, its diff, its checks, the template, +/// the save, CoderHelm's own review threads): one isn't started with less +/// than this left of the sweep's budget. +pub const CATCH_UP_REQUESTS: u64 = 10; +/// The run attribute naming the description writer version +/// (`description::WRITER`) the catch-up last brought its pull request to. +pub const DESCRIPTION_WRITER: &str = "description_writer"; + /// What a look read of the pull request. #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(default)] @@ -294,6 +310,11 @@ pub struct Candidate { /// When the run's last round stopped, if GitHub's rate limit is why /// (`round::ended_by_limit`); "" otherwise. pub limit_ended: String, + /// The description writer version the catch-up last brought the pull + /// request to ("" when never). + pub writer: String, + /// When the run last changed (RFC 3339). + pub updated_at: String, } pub fn candidate_of(item: &HashMap) -> Option { @@ -335,6 +356,8 @@ pub fn candidate_of(item: &HashMap) -> Option .filter(|inc| !inc.held && super::round::ended_by_limit(&inc.reason)) .map(|inc| inc.at) .unwrap_or_default(), + writer: s(DESCRIPTION_WRITER), + updated_at: s("updated_at"), }; (pr > 0 && c.installation_id > 0 && !c.team_id.is_empty() && !c.run_id.is_empty()).then_some(c) } @@ -350,6 +373,46 @@ pub fn order(mut all: Vec, max: usize) -> Vec { all } +/// Whether a run's open pull request is the catch-up's to rebuild: a run +/// that ended with its pull request still CoderHelm's (whatever the age of +/// the run), and not yet brought to this writer. A run in flight rebuilds +/// its own description at every step; one a person cancelled or closed, or +/// one retried or archived, is left; a merged one has nothing to rebuild. +pub fn needs_catch_up(c: &Candidate) -> bool { + use common::run_status as rs; + let left = rs::IN_FLIGHT.contains(&c.status.as_str()) + || rs::ENDED_BY_PERSON.contains(&c.status.as_str()) + || [rs::MERGED, rs::RETRIED, rs::ARCHIVED].contains(&c.status.as_str()); + !left && c.writer != super::description::WRITER.to_string() +} + +/// The pull requests one sweep's catch-up reads: at most `per_team` for +/// each team and `max` in all, the most recently changed run first (the +/// pull requests people are reading now). The rest are reached by the next +/// sweeps, as each one done is marked ([`DESCRIPTION_WRITER`]). +pub fn catch_up_picks(all: Vec, per_team: usize, max: usize) -> Vec { + let mut all: Vec = all.into_iter().filter(needs_catch_up).collect(); + all.sort_by(|a, b| { + b.updated_at + .cmp(&a.updated_at) + .then_with(|| a.run_id.cmp(&b.run_id)) + }); + let mut per: HashMap = HashMap::new(); + let mut picks = Vec::new(); + for c in all { + if picks.len() >= max { + break; + } + let n = per.entry(c.team_id.clone()).or_default(); + if *n >= per_team { + continue; + } + *n += 1; + picks.push(c); + } + picks +} + /// Names of checks failing in a listing (the newest run of each name). fn failing_names(listing: &serde_json::Value) -> (Vec, bool) { let checks = super::reviewer_guide::checks_of(listing); @@ -865,6 +928,9 @@ pub struct SweepReport { pub skipped_installations: usize, /// `owner/repo#pr: act` for each pull request picked back up. pub acted: Vec, + /// `owner/repo#pr` for each description the catch-up rebuilt by this + /// writer (`description::WRITER`). + pub caught_up: Vec, } /// Finished runs with a pull request, changed inside the watch window: each @@ -938,10 +1004,159 @@ pub async fn sweep(state: &WorkerState) -> SweepReport { .push(format!("{}/{}#{}: {act:?}", c.owner, c.repo, c.pr)); } } + report.caught_up = catch_up(state, &mut budget, &mut clients).await; report.skipped_installations = budget.skipped(); report } +/// How one catch-up of a description ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum CaughtUp { + /// Rebuilt by this writer, or already was, or not CoderHelm's to + /// rebuild (no stamp, a person's edit, closed): marked done. + Done(bool), + /// GitHub refused for a while: the next sweep tries again. Any other + /// failure (a pull request gone, a write refused) is a real answer and + /// marks it done, so one pull request never holds its team's turn; the + /// paths that move its head still rebuild it. + Again, +} + +/// Brings the descriptions of open pull requests CoderHelm opened to this +/// writer: one built by an earlier writer on a head that has not moved is +/// otherwise never rebuilt, and keeps the old layout and wording for good. +/// A few per team each sweep, inside the sweep's GitHub budget; each one +/// done is marked on its run, so it is read once per writer version. +/// Returns `owner/repo#pr` for each rebuilt. +async fn catch_up( + state: &WorkerState, + budget: &mut crate::clients::github_budget::SweepGate, + clients: &mut HashMap, +) -> Vec { + let mut all = Vec::new(); + let mut start: Option> = None; + for _ in 0..200 { + let res = state + .dynamo + .scan() + .table_name(&state.config.runs_table_name) + .filter_expression( + "pr_number > :zero AND attribute_not_exists(pr_outcome) \ + AND (attribute_not_exists(#w) OR #w <> :w)", + ) + .expression_attribute_names("#w", DESCRIPTION_WRITER) + .expression_attribute_values(":zero", attr_n(0)) + .expression_attribute_values(":w", attr_s(&super::description::WRITER.to_string())) + .set_exclusive_start_key(start.take()) + .send() + .await; + let page = match res { + Ok(p) => p, + Err(e) => { + warn!(error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Description catch-up: scan failed"); + break; + } + }; + all.extend(page.items().iter().filter_map(candidate_of)); + match page.last_evaluated_key { + Some(k) if !k.is_empty() => start = Some(k), + _ => break, + } + } + let mut rebuilt = Vec::new(); + for c in catch_up_picks(all, CATCH_UP_PER_TEAM, CATCH_UP_MAX) { + if !budget + .allows(state, c.installation_id, CATCH_UP_REQUESTS) + .await + { + continue; + } + if let std::collections::hash_map::Entry::Vacant(v) = clients.entry(c.installation_id) { + match client(state, c.installation_id) { + Some(g) => { + v.insert(g); + } + None => continue, + } + } + let github = &clients[&c.installation_id]; + match catch_up_one(state, github, &c).await { + CaughtUp::Done(was_rebuilt) => { + mark_writer(state, &c).await; + if was_rebuilt { + rebuilt.push(format!("{}/{}#{}", c.owner, c.repo, c.pr)); + } + } + CaughtUp::Again => {} + } + } + if !rebuilt.is_empty() { + info!(prs = ?rebuilt, writer = super::description::WRITER, "Description catch-up: rebuilt by this writer"); + } + rebuilt +} + +async fn catch_up_one(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> CaughtUp { + use super::description::{self, CatchUp, Reconciled}; + let pr = match github.get_pull_request(&c.owner, &c.repo, c.pr).await { + Ok(p) => p, + Err(e) => { + warn!(run_id = %c.run_id, pr = c.pr, error = %e, "Description catch-up: could not read the pull request"); + return again_or_done(github); + } + }; + if pr["state"].as_str() != Some("open") { + return CaughtUp::Done(false); + } + let body = pr["body"].as_str().unwrap_or(""); + let head = pr["head"]["sha"].as_str().unwrap_or(""); + match description::catch_up(body, head) { + CatchUp::Current => CaughtUp::Done(false), + CatchUp::Leave => { + info!(run_id = %c.run_id, pr = c.pr, "Description catch-up: no CoderHelm stamp, or a person edited it; left as it is"); + CaughtUp::Done(false) + } + // Wholly CoderHelm's: built again from the facts of the head alone, + // nothing of the old text kept; its save runs the final review. + CatchUp::Rebuild => match description::catch_up_run( + state, github, &c.team_id, &c.run_id, &c.owner, &c.repo, c.pr, + ) + .await + { + Reconciled::Rebuilt => CaughtUp::Done(true), + Reconciled::Current => CaughtUp::Done(false), + Reconciled::Failed(why) => { + warn!(run_id = %c.run_id, pr = c.pr, why, "Description catch-up: not rebuilt"); + again_or_done(github) + } + }, + } +} + +fn again_or_done(github: &GitHubClient) -> CaughtUp { + if github.outside().is_some() { + CaughtUp::Again + } else { + CaughtUp::Done(false) + } +} + +/// Marks the run's pull request as brought to this writer. +async fn mark_writer(state: &WorkerState, c: &Candidate) { + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&c.team_id)) + .key("run_id", attr_s(&c.run_id)) + .update_expression("SET #w = :w") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_names("#w", DESCRIPTION_WRITER) + .expression_attribute_values(":w", attr_s(&super::description::WRITER.to_string())) + .send() + .await; +} + #[cfg(test)] mod tests { use super::*; @@ -1109,4 +1324,60 @@ mod tests { let ids: Vec<&str> = picked.iter().map(|c| c.run_id.as_str()).collect(); assert_eq!(ids, vec!["r1", "r2"]); } + + /// The catch-up picks open pull requests whose description an earlier + /// writer built, a few per team, the most recently changed first, and + /// never one already brought to this writer or a run still working. + #[test] + fn the_catch_up_picks_a_few_stale_descriptions_per_team() { + let now = crate::passes::description::WRITER.to_string(); + let c = |team: &str, run: &str, status: &str, writer: &str, at: &str| Candidate { + team_id: team.into(), + run_id: run.into(), + status: status.into(), + writer: writer.into(), + updated_at: at.into(), + pr: 1, + installation_id: 1, + ..Default::default() + }; + let mut all = vec![]; + for i in 0..6 { + all.push(c( + "t1", + &format!("a{i}"), + "completed", + "", + &format!("2026-11-0{}", i + 1), + )); + } + all.push(c("t2", "b0", "needs_input", "1", "2026-10-01")); + all.push(c("t2", "b1", "completed", &now, "2026-11-09")); + all.push(c("t2", "b2", "running", "", "2026-11-09")); + all.push(c("t2", "b3", "cancelled", "", "2026-11-09")); + all.push(c("t2", "b4", "merged", "", "2026-11-09")); + all.push(c("t3", "c0", "failed", "", "2026-01-01")); + let ids = |v: Vec| v.into_iter().map(|c| c.run_id).collect::>(); + assert_eq!( + ids(catch_up_picks(all.clone(), CATCH_UP_PER_TEAM, CATCH_UP_MAX)), + vec!["a5", "a4", "a3", "b0", "c0"], + "three of t1's six, newest first; t2's stale one; t3's old one" + ); + // The overall limit holds across teams. + assert_eq!(catch_up_picks(all.clone(), 3, 2).len(), 2); + // Once marked, the next sweep reaches the rest of t1. + let marked: Vec = all + .into_iter() + .map(|mut x| { + if ["a5", "a4", "a3", "b0", "c0"].contains(&x.run_id.as_str()) { + x.writer = now.clone(); + } + x + }) + .collect(); + assert_eq!( + ids(catch_up_picks(marked, CATCH_UP_PER_TEAM, CATCH_UP_MAX)), + vec!["a2", "a1", "a0"] + ); + } }