From 071b46b82980615d6febb7e2e2767f19dc838cfd Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 21 Nov 2026 01:19:45 -0500 Subject: [PATCH 1/8] A stacked run's reused pull request targets the branch it is built on Two tickets asked for the same change, and two runs built it from the default branch with one commit per file written. Several of their commits had the same patch id, so the first ticket's kept branch read as copying the sibling's open pull request. Its retries continued the same kept branch and stopped before the pull request step on old code. Today the change is rebuilt on the other branch and the run stacks on it, but two gaps were left: - A pull request the run reuses (its own open one, or a reopened one) never moved off its old base. Its diff showed the other pull request's whole change beside this one, while its description said it was stacked and showed only this change. It now moves onto the run's base when that base is another open pull request's branch of the repository; any other base is left alone. - On the next attempt, whose base starts again from the default branch, the other pull request's own commits on the branch (the same hashes) read as copies and the change was rebuilt and force pushed again. A branch whose shared commits are all the other pull request's own is built on it: the run takes that branch as its base and rebuilds nothing. Incident case fa_stacked_pr_targets_its_base. --- .../fa_stacked_pr_targets_its_base.md | 5 + services/worker/src/clients/github.rs | 13 ++ .../fa_stacked_pr_targets_its_base.rs | 139 ++++++++++++++++++ services/worker/src/passes/pr.rs | 65 ++++++++ services/worker/src/passes/stack.rs | 57 +++++++ 5 files changed, 279 insertions(+) create mode 100644 docs/incidents/fa_stacked_pr_targets_its_base.md create mode 100644 services/worker/src/passes/incidents/fa_stacked_pr_targets_its_base.rs diff --git a/docs/incidents/fa_stacked_pr_targets_its_base.md b/docs/incidents/fa_stacked_pr_targets_its_base.md new file mode 100644 index 000000000..cae3e94de --- /dev/null +++ b/docs/incidents/fa_stacked_pr_targets_its_base.md @@ -0,0 +1,5 @@ +# fa. `fa_stacked_pr_targets_its_base` + +**What happened:** Two tickets asked for the same change (one for the work, a sibling to merge and deploy it), and two runs built it from the default branch an hour apart. Their one-commit-per-file histories had several commits with the same patch id, so the first ticket's kept branch read as copying the sibling's open pull request. Five retries continued that same kept branch, which still held the same four commits, and stopped before the pull request step each time: the rebase didn't apply, there were too many commits to replay, and the merge failed. A person had to step in. + +**The guarantee:** A pull request a run reuses (its own open one, or a reopened one) moves onto the branch the run is stacked on, so its diff shows only this change and matches its description. A base that isn't another open pull request's branch is left alone. A branch that holds another open pull request's own commits (the same hashes) is already built on it: the run takes that branch as its base and doesn't rebuild or force push it again. diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 4e0e8eb8e..b886d6a8a 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -5419,6 +5419,19 @@ impl GitHubClient { Ok(()) } + /// Move an open pull request onto another base branch. + pub async fn set_pull_base( + &self, + owner: &str, + repo: &str, + pr_number: u64, + base: &str, + ) -> Result<(), Box> { + let url = format!("{API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}"); + self.patch(&url, &serde_json::json!({"base": base})).await?; + Ok(()) + } + /// Reopen a closed pull request. pub async fn reopen_pull_request( &self, diff --git a/services/worker/src/passes/incidents/fa_stacked_pr_targets_its_base.rs b/services/worker/src/passes/incidents/fa_stacked_pr_targets_its_base.rs new file mode 100644 index 000000000..210258bc4 --- /dev/null +++ b/services/worker/src/passes/incidents/fa_stacked_pr_targets_its_base.rs @@ -0,0 +1,139 @@ +//! fa. Two tickets asked for the same change: one for the work, and a +//! sibling titled "Merge and deploy" the first, whose body restated it. Two +//! runs built it from the default branch an hour apart, each with one +//! commit per file written. Both made the same small edits (the same query +//! line, the same import) and their code generator committed the same +//! generated files, so several commits of the two branches had the same +//! patch id. The first ticket's run had already opened its own pull request +//! (#41, onto the default branch). Every retry of that ticket continued #41 +//! on its kept branch, whose old commits read as copies of the sibling's +//! open pull request (#40) "under new hashes", and stopped before the pull +//! request step: first "rebasing onto that branch didn't apply cleanly", +//! then "too many commits to replay", then "neither did merging #40's +//! branch in". Five runs over three days stopped the same way, each on the +//! same kept branch with the same four commits, until a person stepped in. +//! +//! Today the branch's own change is rebuilt on #40's branch and the run +//! stacks on it. Two gaps were left. #41 already existed with the default +//! branch as its base, and a reused pull request never moved: its diff +//! showed all of #40 beside this change while its description said it was +//! stacked and showed only this change. And on the next attempt, whose base +//! starts again from the default branch, #40's own commits on the branch +//! (the same hashes) read as copies again: the change was rebuilt and force +//! pushed on every retry. +//! +//! Guarantee: a pull request a run reuses (its own open one, or a reopened +//! one) targets the branch the run is stacked on, so its diff is only this +//! change; a base that isn't another open pull request's branch (one a +//! person chose) is left alone. A branch that holds another open pull +//! request's own commits (the same hashes) is built on it: the run takes +//! that branch as its base and rebuilds nothing. + +use std::collections::BTreeMap; + +use serde_json::{json, Value}; + +use super::fixture::*; +use crate::passes::pr::stack_base; +use crate::passes::stack::{self, Copy, Dependency}; + +const SIBLING: &str = "coderhelm/harbor-40"; +const OWN: &str = "coderhelm/harbor-41"; + +fn open_pr(n: u64, head: &str, base: &str) -> Value { + json!({ + "number": n, + "title": format!("HARBOR-{n}: dock card shows the slip photo"), + "head": {"ref": head, "repo": {"full_name": "harbor/web"}}, + "base": {"ref": base}, + }) +} + +#[test] +fn a_reused_pull_request_moves_onto_the_branch_the_run_is_stacked_on() { + let open = vec![open_pr(40, SIBLING, "main"), open_pr(41, OWN, "main")]; + let own = &open[1]; + // The run rebuilt its change on #40's branch: its base is that branch. + assert_eq!( + stack_base(own, SIBLING, &open, "harbor", "web").as_deref(), + Some(SIBLING), + "#41 kept the default branch as its base while its branch was stacked on #40" + ); + // Already there: nothing to move. + let moved = open_pr(41, OWN, SIBLING); + assert_eq!(stack_base(&moved, SIBLING, &open, "harbor", "web"), None); + // A base a person chose (a long-lived branch, no open pull request) is + // left alone, and so is the default branch. + assert_eq!(stack_base(own, "release-2", &open, "harbor", "web"), None); + let stacked = open_pr(41, OWN, SIBLING); + assert_eq!(stack_base(&stacked, "main", &open, "harbor", "web"), None); + // A fork's branch is never a base. + let fork = vec![json!({ + "number": 39, + "head": {"ref": "dock-photo", "repo": {"full_name": "someone/web"}}, + "base": {"ref": "main"}, + })]; + assert_eq!(stack_base(own, "dock-photo", &fork, "harbor", "web"), None); +} + +fn copy(commits: &[&str], shared: &[&str]) -> Copy { + Copy { + dep: Dependency { + number: 40, + branch: SIBLING.into(), + title: "HARBOR-40: merge and deploy HARBOR-41".into(), + ..Default::default() + }, + commits: commits.iter().map(|s| s.to_string()).collect(), + shared: shared.iter().map(|s| s.to_string()).collect(), + own: vec!["HARBOR-41: dock card shows the slip photo".into()], + files: BTreeMap::new(), + } +} + +#[test] +fn a_branch_built_on_the_other_pull_request_is_stacked_without_a_rebuild() { + // The retry's branch, already rebuilt on #40: #40's own commits (the + // same hashes) and then this change. Nothing was copied. + let their = ["a1a1a1a", "b2b2b2b", "c3c3c3c"].map(String::from); + let matched = vec!["a1a1a1a".to_string(), "b2b2b2b".to_string()]; + let shared = stack::shared(&matched, &their); + assert_eq!(shared, matched); + let c = copy(&["a1a1a1a", "b2b2b2b"], &["a1a1a1a", "b2b2b2b"]); + assert!(stack::built_on(&c), "the other pull request's own commits read as copies"); + let why = stack::built_on_why(&c); + assert!(why.contains("built on #40's branch `coderhelm/harbor-40`"), "{why}"); + assert!(!why.contains("under other hashes")); + assert!(!why.contains("re-created")); + // The kept branch of the incident: same changes under new hashes. These + // are copies, rebuilt as before. + let old = copy(&["e5e5e5e", "f6f6f6f", "d7d7d7d", "c8c8c8c"], &[]); + assert!(!stack::built_on(&old)); + // Some copied, some shared: still rebuilt. + let mixed = copy(&["a1a1a1a", "e5e5e5e"], &["a1a1a1a"]); + assert!(!stack::built_on(&mixed)); + assert!(!stack::built_on(©(&[], &[]))); +} + +#[test] +fn the_pipeline_moves_reused_pull_requests_and_skips_needless_rebuilds() { + let pr = include_str!("../pr.rs"); + let run = fn_src(pr, "pub async fn run("); + let reused = run.find("\"Using existing PR\"").expect("the existing pull request path"); + let reopened = run + .find("\"Reopened prior PR for branch\"") + .expect("the reopened pull request path"); + for at in [reused, reopened] { + assert!( + run[at..at + 200].contains("retarget(github, msg, &pr_data)"), + "a reused pull request keeps its old base" + ); + } + let stack_src = include_str!("../stack.rs"); + for head in ["pub async fn at_start(", "pub async fn before_pr("] { + let f = fn_src(stack_src, head); + let check = f.find("built_on(&c)").unwrap_or_else(|| panic!("{head} rebuilds a stacked branch")); + let rebuild = f.find("rebuild_on(").unwrap(); + assert!(check < rebuild, "{head} rebuilds before it asks whether the branch is built on it"); + } +} diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 9f67529ea..4fe615205 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -680,6 +680,7 @@ Return ONLY the markdown body text."#, .unwrap_or("") .to_string(); info!(pr_number = number, pr_url = %url, "Using existing PR"); + retarget(github, msg, &pr_data).await; // A re-run changed the code: the description is rewritten from this // diff, never left describing the earlier version. if let Err(e) = crate::passes::description::save( @@ -716,6 +717,7 @@ Return ONLY the markdown body text."#, .unwrap_or("") .to_string(); info!(pr_number = number, pr_url = %url, "Reopened prior PR for branch"); + retarget(github, msg, &pr_data).await; (number, url, nid) } else { // Squash the run's many per-tool-call commits into one clean commit @@ -1003,6 +1005,69 @@ async fn notify_alert_pr( /// PR ("all commits removed"); once the fresh implementation has pushed new /// commits, reopening keeps the PR number and its review history instead of /// creating a new PR every re-run. Failures fall back to PR creation. +/// The base a reused pull request (an open one of this branch, or a +/// reopened one) moves to: the branch this run is built on, when that is +/// another open pull request's branch of this repository (the run stacked +/// on it) and the pull request targets something else. A pull request +/// opened before the run stacked kept its old base: its diff showed the +/// other pull request's whole change beside this one, while its description +/// said it was stacked and showed only this change. Any other base (one a +/// person chose, a long-lived branch) is left alone. +pub fn stack_base( + pr: &serde_json::Value, + run_base: &str, + open: &[serde_json::Value], + owner: &str, + repo: &str, +) -> Option { + let current = pr["base"]["ref"].as_str().unwrap_or(""); + if current == run_base || run_base.is_empty() { + return None; + } + let full = format!("{owner}/{repo}"); + let own_head = pr["head"]["ref"].as_str().unwrap_or(""); + open.iter() + .any(|p| { + p["head"]["ref"].as_str() == Some(run_base) + && run_base != own_head + && p["head"]["repo"]["full_name"] + .as_str() + .is_some_and(|f| f.eq_ignore_ascii_case(&full)) + }) + .then(|| run_base.to_string()) +} + +/// Moves a reused pull request onto the run's stacked base ([`stack_base`]). +async fn retarget(github: &GitHubClient, msg: &TicketMessage, pr: &serde_json::Value) { + if pr["base"]["ref"].as_str() == Some(msg.base_branch.as_str()) { + return; + } + let Ok(open) = github + .list_open_pulls(&msg.repo_owner, &msg.repo_name) + .await + else { + return; + }; + let Some(open) = open.as_array() else { + return; + }; + let Some(base) = stack_base(pr, &msg.base_branch, open, &msg.repo_owner, &msg.repo_name) else { + return; + }; + let number = pr["number"].as_u64().unwrap_or(0); + match github + .set_pull_base(&msg.repo_owner, &msg.repo_name, number, &base) + .await + { + Ok(()) => { + info!(pr_number = number, base = %base, "Moved the pull request onto the branch it is stacked on") + } + Err(e) => { + warn!(pr_number = number, base = %base, error = %e, "Could not move the pull request onto the branch it is stacked on") + } + } +} + async fn reopen_prior_pr( github: &GitHubClient, msg: &TicketMessage, diff --git a/services/worker/src/passes/stack.rs b/services/worker/src/passes/stack.rs index 547d3a9e7..3f0354bb7 100644 --- a/services/worker/src/passes/stack.rs +++ b/services/worker/src/passes/stack.rs @@ -641,6 +641,18 @@ pub async fn at_start( return None; } let c = copied(github, &owner, &repo, &msg.base_branch, branch).await?; + if built_on(&c) { + tracing::info!( + branch, + dep = c.dep.number, + "The branch is built on an open pull request's branch: stacked on it, nothing rebuilt" + ); + msg.base_branch = c.dep.branch.clone(); + return Some(Dependency { + why: built_on_why(&c), + ..c.dep + }); + } tracing::info!( branch, dep = c.dep.number, @@ -727,6 +739,13 @@ pub async fn before_pr( let Some(c) = copied(github, &owner, &repo, &msg.base_branch, branch).await else { return Ok(from_ticket.filter(|d| d.branch == msg.base_branch)); }; + if built_on(&c) { + msg.base_branch = c.dep.branch.clone(); + return Ok(Some(Dependency { + why: built_on_why(&c), + ..c.dep + })); + } let mut merger = restack::ModelMerger { state, provider, @@ -925,6 +944,9 @@ pub struct Copy { pub dep: Dependency, /// The branch's commits whose change is one of that pull request's. pub commits: Vec, + /// Those of them that are that pull request's own commits, same hash: + /// the branch is built on its branch, they were never copied. + pub shared: Vec, /// The messages of the branch's other commits (merge commits aside): /// its own work. pub own: Vec, @@ -942,6 +964,39 @@ pub fn matches(ours: &[(String, u64)], theirs: &[(String, u64)]) -> Vec .collect() } +/// The branch's commits that are another pull request's own commits (the +/// same hash, so the branch was built on its branch), from `ours` (the +/// branch's commits matched by patch id) and `their_shas`. +pub fn shared(matched: &[String], their_shas: &[String]) -> Vec { + matched + .iter() + .filter(|s| their_shas.contains(s)) + .cloned() + .collect() +} + +/// Whether every commit the branch shares with the other pull request is +/// that pull request's own commit: the branch is already built on its +/// branch, nothing was copied, and nothing is to be rebuilt. The run only +/// takes that branch as its base (its pull request then shows only its own +/// change). A branch that started on the other pull request reads this way +/// on every later attempt, whose base starts again from the default branch. +pub fn built_on(c: &Copy) -> bool { + !c.commits.is_empty() && c.commits.iter().all(|s| c.shared.contains(s)) +} + +/// Why the run takes the other pull request's branch as its base, for the +/// stack section. +pub fn built_on_why(c: &Copy) -> String { + format!( + "This branch is built on #{n}'s branch `{b}` (it holds {k} of #{n}'s commits, the same \ + commits), so it is stacked on #{n} and nothing was rebuilt.", + n = c.dep.number, + b = c.dep.branch, + k = c.shared.len(), + ) +} + const MAX_PRS: usize = 40; /// Each commit's patch id, and its files as read. @@ -1036,6 +1091,7 @@ pub async fn copied( ..Default::default() }, own: own_messages(&listed, &m), + shared: shared(&m, &their_shas), commits: m, files: BTreeMap::new(), }); @@ -1391,6 +1447,7 @@ mod tests { }, own: own_messages(&listed, &commits), commits, + shared: Vec::new(), files: BTreeMap::new(), } } From 6a12e6082fd49d925e1ddb3df40f9af85a85e023 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 21 Nov 2026 01:20:17 -0500 Subject: [PATCH 2/8] New-feature rules: a registry is the list that grew with its kind, told by what the file is Two new-feature runs were blocked "new items aren't registered everywhere their siblings are" for places that register nothing: a one-off data migration that lists the document types it rewrote, and a package.json that names UI libraries as dependencies. The rule called a file a registry when it named most of a sample of eight siblings (the first eight by name), and told places apart by folder names (migrations/, docs/, fixtures/). So a backfill kept in any other folder, or a generated types file, still counted, and a real index of migrations never did. A registry is now told by what the file is: - it lists the kind: more than half of all the existing siblings (never a sample), by path or as whole strings; a kebab-case name such as `boat-index` no longer counts as naming `boat`; - it is part of the program: not prose, a test or its fixtures, a file the repository's own generators write (read from their config), or a file whose head says it is generated (it is regenerated, never edited); - it grew with the kind: its history on the default branch shows it naming fewer of the siblings when it was written than now. A file that lists them but never grew is noted for a person with why; one whose history can't be read isn't checked. Neither blocks. Only a checked registry blocks, and the coder is first told to add the entry itself. Incident case rg replays both runs' shapes; three of its checks fail on the code before this change. --- .../rg_registered_where_the_kind_grows.md | 5 + .../worker/src/passes/feature/registration.rs | 429 ++++++++++++++++-- .../rg_registered_where_the_kind_grows.rs | 404 +++++++++++++++++ 3 files changed, 793 insertions(+), 45 deletions(-) create mode 100644 docs/incidents/rg_registered_where_the_kind_grows.md create mode 100644 services/worker/src/passes/incidents/rg_registered_where_the_kind_grows.rs diff --git a/docs/incidents/rg_registered_where_the_kind_grows.md b/docs/incidents/rg_registered_where_the_kind_grows.md new file mode 100644 index 000000000..2e8028a56 --- /dev/null +++ b/docs/incidents/rg_registered_where_the_kind_grows.md @@ -0,0 +1,5 @@ +# rg. `rg_registered_where_the_kind_grows` + +**What happened:** Two new-feature runs drafted their pull requests and were blocked "new items aren't registered everywhere their siblings are" for places that register nothing. One run added a validation helper beside a studio's document schemas, and the rule wanted it in the documents index, the desk structure and a one-off data migration that lists, once, the types it rewrote. The other added a `heading` component beside the site's UI components, and the rule wanted it in the site's `package.json`, which only names packages such as `@radix-ui/react-accordion` as dependencies. People closed both drafts. The rule called a file a registry when it named most of a sample of eight siblings, and told places apart by folder names, so a backfill kept in another folder or a generated types file still counted, and a real index of migrations never did. + +**The guarantee:** A registry is told from a file that merely names the items by what the file is, never by its folder or a list of names. It lists the kind: more than half of all its existing siblings, by path or as whole strings. It is part of the program: not prose, a test or its fixtures, a file the repository's generators write, or a file whose head says it is generated. And it grew with the kind: when it was written it named fewer of the siblings than it does now. A file that lists them but never grew is noted for a person, and one whose history can't be read isn't checked, so neither blocks. Only a checked registry blocks, and the coder is first told to add the entry itself. diff --git a/services/worker/src/passes/feature/registration.rs b/services/worker/src/passes/feature/registration.rs index e19ce6cf3..02d458d0d 100644 --- a/services/worker/src/passes/feature/registration.rs +++ b/services/worker/src/passes/feature/registration.rs @@ -9,16 +9,26 @@ //! 1. its siblings are the existing items of the same kind: files with the //! same extension in the same folder, or, for an item that is a new //! folder (`blocks/Quote/index.tsx`), the other folders beside it; -//! 2. the places that register them are the files that name most of the -//! siblings (a registry names all of them; a page that uses two of them -//! is not a registration), found by code search on the default branch. -//! Comments never count. Docs, migrations, fixtures and tests are never -//! places. A manifest (`package.json` and other data files) counts only -//! where it names the siblings as paths or keys (`"./accordion"`), never -//! inside other names such as a dependency (`@radix-ui/react-accordion`); +//! 2. the places that register them are the files that list the kind: they +//! name more than half of all the existing siblings (a registry names all +//! of them; a page that uses two of them, or a one-off script that picks +//! the few it changes, is not a registration), found by code search on +//! the default branch. Comments never count. Prose (docs, notes), tests +//! and their fixtures are never places, and neither is a generated file: +//! one the repository's own generators write, or one whose head says it +//! is generated; it is regenerated, never edited by hand. A manifest +//! (`package.json` and other data files) counts only where it names the +//! siblings as paths or keys (`"./accordion"`), never inside other names +//! such as a dependency (`@radix-ui/react-accordion`); //! 3. a place is a registry when it names the siblings by path or as a -//! whole string (an import, an `exports` key, a list of ids); a code file -//! that only mentions them as words is a maybe; +//! whole string (an import, an `exports` key, a list of ids) and it grew +//! with the kind: its history shows it naming fewer of them when it was +//! written than it does now, so siblings added later were added to it. +//! A file that never changed as siblings were added (a data migration +//! that lists the types it rewrote, a snapshot) is a list of them, not +//! their registry, whatever folder it sits in; and one whose history +//! couldn't be read isn't checked, so it never blocks. A code file that +//! only mentions them as words is a maybe; //! 4. a new file is an item of the siblings' kind only when its structure //! says so, never because of the folder it sits in ([`kind_of`]): it has //! the export shape the siblings share (a default export, a call to the @@ -41,8 +51,9 @@ use std::collections::BTreeSet; use crate::clients::github::GitHubClient; use crate::passes::feature::reuse::name_words; -/// Most siblings sampled per item. -const MAX_SIBLINGS: usize = 8; +/// Most siblings read per item: a folder this large is the kind's whole +/// list in practice; the cap only bounds the work. +const MAX_SIBLINGS: usize = 400; /// Most candidate files read per item. const MAX_CANDIDATES: usize = 40; @@ -238,12 +249,15 @@ pub fn variants(id: &str) -> Vec { out } -/// Whether `text` names `word` on its own (not inside a longer name). +/// Whether `text` names `word` on its own (not inside a longer name: a +/// kebab-case name such as `boat-index` is one name, so it doesn't name +/// `boat`). fn names_word(text: &str, word: &str) -> bool { if word.is_empty() { return false; } - let ok = |c: Option| c.is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '_')); + let ok = + |c: Option| c.is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '_' || c == '-')); let mut from = 0; while let Some(i) = text[from..].find(word) { let at = from + i; @@ -264,20 +278,37 @@ pub fn names_item(text: &str, id: &str) -> bool { /// key, never by a word inside a longer name. const DATA_EXTS: &[&str] = &["json", "jsonc", "yaml", "yml", "toml"]; -/// Paths that are never registration places: docs, migrations, fixtures. +/// Files that are never registration places by what they are: prose (docs, +/// notes) and the test suite's own data (fixtures and mocks). Whether a file +/// of the program registers the kind is read from the file itself +/// ([`registration_places`]) and its history ([`grew_with_kind`]), never +/// from the folder it sits in. fn never_a_place(p: &str) -> bool { let l = p.to_lowercase(); let (_, f) = split_path(&l); let ext = f.rsplit_once('.').map(|(_, e)| e).unwrap_or(""); - matches!(ext, "md" | "mdx" | "rst" | "txt") - || l.starts_with("migrations/") - || l.contains("/migrations/") - || l.contains("/migration/") + matches!(ext, "md" | "mdx" | "rst" | "txt" | "adoc") || l.contains("/fixtures/") + || l.starts_with("fixtures/") || l.contains("/__fixtures__/") || l.contains("/__mocks__/") - || l.starts_with("docs/") - || l.contains("/docs/") +} + +/// Whether a file says, in its head, that a tool writes it (`@generated`, +/// "This file has been generated by ...", "Code generated ... DO NOT +/// EDIT"): it is regenerated, never a place to register by hand. +pub fn says_generated(text: &str) -> bool { + text.lines().take(15).any(|line| { + let l = line.to_lowercase(); + l.contains("@generated") + || l.contains("auto-generated") + || l.contains("autogenerated") + || l.contains("do not edit") + || l.contains("generated by") + || l.contains("code generated") + || l.contains("has been generated") + || l.contains("is generated") + }) } fn is_data_file(p: &str) -> bool { @@ -370,14 +401,24 @@ fn quoted(text: &str) -> Vec<&str> { /// with a path segment that is the item (`"./accordion"`, /// `"@/components/ui/accordion"`, `"accordion"`, `"./Hero.tsx"`), not a /// longer name that contains it (`"@radix-ui/react-accordion"`). +#[cfg(test)] pub fn names_as_path(text: &str, id: &str) -> bool { - let forms = variants(id); - quoted(text).into_iter().any(|q| { - q.split('/').any(|seg| { - let stem = seg.split('.').next().unwrap_or(seg); - !stem.is_empty() && forms.iter().any(|f| f == stem) - }) - }) + names_as_path_in(&path_stems(text), id) +} + +/// The path segments (without extensions) of every quoted value in `text`: +/// read once, then asked for each sibling ([`names_as_path_in`]). +fn path_stems(text: &str) -> BTreeSet<&str> { + quoted(text) + .into_iter() + .flat_map(|q| q.split('/')) + .map(|seg| seg.split('.').next().unwrap_or(seg)) + .filter(|s| !s.is_empty()) + .collect() +} + +fn names_as_path_in(stems: &BTreeSet<&str>, id: &str) -> bool { + variants(id).iter().any(|f| stems.contains(f.as_str())) } /// The bare packages a file imports (`from 'sanity'`, `require("x")`), not @@ -764,11 +805,32 @@ fn sibling_own(path: &str, item: &NewItem, sibs: &[String]) -> bool { }) } -/// The files that register items of this kind: those naming most sampled -/// siblings (all of them when there are three or fewer; otherwise at least -/// three and 60% of them), with comments left out. A place is a registry -/// (`true`) when it names them as paths or whole strings, else a maybe -/// (`false`, code files only). `files` are (path, default-branch text). +/// How many of `n` siblings a file must name to list the kind: all of them +/// when there are three or fewer, else more than half (and at least three). +fn listing_need(n: usize) -> usize { + if n <= 3 { + n + } else { + 3usize.max(n / 2 + 1) + } +} + +/// How many of the siblings `text` names as paths or whole strings +/// (comments left out). +pub fn named_as_paths(path: &str, text: &str, sibs: &[String]) -> usize { + let text = without_comments(path, text); + let stems = path_stems(&text); + sibs.iter().filter(|s| names_as_path_in(&stems, s)).count() +} + +/// The files that list items of this kind: those naming more than half of +/// all its siblings (all of them when there are three or fewer), with +/// comments left out. A place is a registry candidate (`true`) when it names +/// them as paths or whole strings, else a maybe (`false`, code files only); +/// a candidate is a registry only once its history shows it grew with the +/// kind ([`grew_with_kind`]). Generated files are never places. `files` are +/// (path, default-branch text); `sibs` are all the siblings, never a sample +/// (a sample's majority is not the kind's). pub fn registration_places( item: &NewItem, sibs: &[String], @@ -777,24 +839,22 @@ pub fn registration_places( if sibs.is_empty() { return Vec::new(); } - let n = sibs.len(); - let need = if n <= 3 { - n - } else { - 3usize.max((n * 3).div_ceil(5)) - }; + let need = listing_need(sibs.len()); files .iter() - .filter(|(p, _)| { + .filter(|(p, raw)| { !skipped(p) && !is_test(p) && !never_a_place(p) + && !is_generated_or_types(p) + && !says_generated(raw) && !sibling_own(p, item, sibs) && *p != item.path }) .filter_map(|(p, raw)| { let text = without_comments(p, raw); - let as_paths = sibs.iter().filter(|s| names_as_path(&text, s)).count(); + let stems = path_stems(&text); + let as_paths = sibs.iter().filter(|s| names_as_path_in(&stems, s)).count(); if as_paths >= need { return Some((p.clone(), true)); } @@ -807,6 +867,50 @@ pub fn registration_places( .collect() } +/// What a place's history says about it: the commits that changed it on the +/// default branch, and its text at the earliest of them that could be read. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum History { + /// It changed in `commits` commits; `earliest` is its text then. + Read { commits: usize, earliest: String }, + /// Its history couldn't be read. + Unknown, +} + +/// Whether a place that lists the kind grew with it: when it was written it +/// named fewer of today's siblings than it does now, so siblings added since +/// were added to it. That is what a registry is (each new item of the kind +/// is added there), whatever folder it sits in or whatever it is named; a +/// file written once with the list it needed (a data migration over the +/// types it rewrites, a one-off backfill, a snapshot) never grows, even when +/// it was edited since. A file never changed after it was written has not +/// grown. +pub fn grew_with_kind(path: &str, now: &str, sibs: &[String], history: &History) -> bool { + match history { + History::Read { commits, earliest } => { + *commits > 1 && named_as_paths(path, earliest, sibs) < named_as_paths(path, now, sibs) + } + History::Unknown => false, + } +} + +/// Why a candidate registry is only noted, when its history says it isn't +/// one (`None`: it grew with the kind, a registry). +pub fn not_a_registry(path: &str, now: &str, sibs: &[String], history: &History) -> Option { + if grew_with_kind(path, now, sibs, history) { + return None; + } + Some(match history { + History::Unknown => "its history couldn't be read to tell whether new items are added to it".to_string(), + History::Read { commits: 1, .. } => { + "it hasn't changed since it was written, so items added since weren't added to it: it lists them, it doesn't register them".to_string() + } + History::Read { .. } => { + "items added since it was written weren't added to it: it lists them, it doesn't register them".to_string() + } + }) +} + /// A place a new item is missing from. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Missing { @@ -820,6 +924,9 @@ pub struct Missing { /// Set when the structure couldn't tell whether the new file is the /// siblings' kind: why. Only noted. pub unsure: Option, + /// Set when the place lists the siblings but its history says it isn't + /// their registry ([`not_a_registry`]): why. Only noted. + pub listed_only: Option, } impl Missing { @@ -838,6 +945,12 @@ impl Missing { self.item, self.path ); } + if let Some(why) = &self.listed_only { + return format!( + "`{}` may belong in `{}`: it names {names}, but {why}; check by hand", + self.item, self.path + ); + } if self.registry { format!( "`{}` isn't registered in `{}` (it names {names})", @@ -878,12 +991,111 @@ pub fn missing( .collect(), registry: *registry, unsure: None, + listed_only: None, }); } } out } +/// The candidate registries settled by their history (`history`: a place's +/// [`History`] on the default branch): one that didn't grow with the kind +/// stays a place, only noted, with why (`listed`: path and why). +#[allow(clippy::type_complexity)] +pub fn settle_places( + places: Vec<(String, String, bool)>, + sibs: &[String], + history: &dyn Fn(&str) -> History, +) -> (Vec<(String, String, bool)>, Vec<(String, String)>) { + let mut listed = Vec::new(); + let places = places + .into_iter() + .map(|(p, t, registry)| { + if !registry { + return (p, t, false); + } + match not_a_registry(&p, &t, sibs, &history(&p)) { + None => (p, t, true), + Some(why) => { + listed.push((p.clone(), why)); + (p, t, false) + } + } + }) + .collect(); + (places, listed) +} + +/// Marks what a place that only lists the siblings is missing as a note. +pub fn mark_listed(missing: &mut [Missing], listed: &[(String, String)]) { + for m in missing.iter_mut() { + if let Some((_, why)) = listed.iter().find(|(p, _)| *p == m.path) { + m.registry = false; + if m.unsure.is_none() { + m.listed_only = Some(why.clone()); + } + } + } +} + +/// Files the repository's own generators write (`outputs`: their globs from +/// the repository root, [`crate::passes::generators::Generator::outputs`]): +/// regenerated, never a place to register by hand. +pub fn drop_generated(files: Vec<(String, String)>, outputs: &[String]) -> Vec<(String, String)> { + files + .into_iter() + .filter(|(p, _)| { + !outputs + .iter() + .any(|g| crate::passes::generators::glob_match(g, p)) + }) + .collect() +} + +/// The output globs of the generators the repository has at `git_ref`. +async fn generator_outputs( + github: &GitHubClient, + owner: &str, + repo: &str, + git_ref: &str, + tree: &[String], +) -> Vec { + use crate::passes::generators; + let mut files = std::collections::HashMap::new(); + for p in generators::candidate_files(tree).into_iter().take(40) { + if let Ok(t) = github.read_file(owner, repo, &p, git_ref).await { + files.insert(p, t); + } + } + let repo_files = generators::RepoFiles { + tree: tree.to_vec(), + files, + }; + generators::detect(&repo_files) + .into_iter() + .flat_map(|g| g.outputs) + .map(|o| generators::normalize_path(&o)) + .collect() +} + +/// A place's history on the default branch: the commits that changed it +/// (at most 100) and its text at the earliest of them. +async fn place_history(github: &GitHubClient, owner: &str, repo: &str, path: &str) -> History { + let Ok(commits) = github.commits_for_path(owner, repo, path, None, 100).await else { + return History::Unknown; + }; + let Some(sha) = commits.last().and_then(|c| c["sha"].as_str()) else { + return History::Unknown; + }; + match github.read_file(owner, repo, path, sha).await { + Ok(earliest) => History::Read { + commits: commits.len(), + earliest, + }, + Err(_) => History::Unknown, + } +} + /// Registries the item is missing from: these go back to the coder and block. pub fn blocking(missing: &[Missing]) -> Vec { missing.iter().filter(|m| m.registry).cloned().collect() @@ -919,6 +1131,8 @@ pub async fn check( ) -> (Vec, usize) { let mut out: Vec = Vec::new(); let mut checked = 0usize; + // The repository's generator outputs, read once when a place is looked for. + let mut outputs: Option> = None; for item in new_items(added, tree).into_iter().take(6) { let sibs = siblings(&item, tree, recorded_sibling); if sibs.is_empty() { @@ -979,6 +1193,10 @@ pub async fn check( files.push((p, t)); } } + if outputs.is_none() { + outputs = Some(generator_outputs(github, owner, repo, base, tree).await); + } + let files = drop_generated(files, outputs.as_deref().unwrap_or_default()); let keep = registration_places(&item, &sibs, &files); let places: Vec<(String, String, bool)> = files .into_iter() @@ -1003,6 +1221,23 @@ pub async fn check( tracing::info!(item = %item.path, why, "Not a new item of its siblings' kind"); continue; } + // A candidate registry is one only when it grew with the kind. + let mut histories: Vec<(String, History)> = Vec::new(); + for (p, _, registry) in &places { + if *registry { + histories.push((p.clone(), place_history(github, owner, repo, p).await)); + } + } + let (places, listed) = settle_places(places, &sibs, &|p: &str| { + histories + .iter() + .find(|(q, _)| q == p) + .map(|(_, h)| h.clone()) + .unwrap_or(History::Unknown) + }); + for (p, why) in &listed { + tracing::info!(item = %item.path, place = %p, why, "Lists the siblings, not their registry"); + } checked += places.len(); let mut on_branch: Vec<(String, Option)> = Vec::new(); for (p, _, _) in &places { @@ -1017,7 +1252,9 @@ pub async fn check( .find(|(q, _)| q == p) .and_then(|(_, t)| t.clone()) }; - for m in judge(&item, &sibs, &kind, &places, &lookup) { + let mut found = judge(&item, &sibs, &kind, &places, &lookup); + mark_listed(&mut found, &listed); + for m in found { if !out.iter().any(|x| x.item == m.item && x.path == m.path) { out.push(m); } @@ -1198,7 +1435,7 @@ mod tests { } #[test] - fn comments_docs_and_migrations_never_make_a_place() { + fn comments_and_docs_never_make_a_place_and_a_migration_only_lists() { let item = &new_items( &["apps/web/src/components/ui/heading.tsx".to_string()], &ui_tree(), @@ -1214,12 +1451,114 @@ mod tests { "docs/components.md".to_string(), "`./accordion` `./alert` `./card`".to_string(), ), + ]; + assert!(registration_places(item, &sibs, &files).is_empty()); + // A migration that lists them is a candidate by its text; its + // history (written once, never grown) says it only lists them. + let migration = "const types = ['accordion', 'alert', 'card']".to_string(); + let path = "apps/web/migrations/rename-cards/index.ts".to_string(); + let places = registration_places(item, &sibs, &[(path.clone(), migration.clone())]); + assert_eq!(places, vec![(path.clone(), true)]); + let (settled, listed) = settle_places( + vec![(path.clone(), migration.clone(), true)], + &sibs, + &|_| History::Read { + commits: 1, + earliest: migration.clone(), + }, + ); + assert!(!settled[0].2); + assert_eq!(listed.len(), 1); + let mut m = missing(item, &sibs, &settled, &|_| Some(migration.clone())); + mark_listed(&mut m, &listed); + assert!(blocking(&m).is_empty()); + assert!(m[0].line().contains("check by hand"), "{}", m[0].line()); + assert!(m[0].line().contains("hasn't changed since it was written")); + } + + #[test] + fn a_registry_is_the_list_that_grew_with_the_kind() { + let sibs: Vec = ["alpha", "bravo", "charlie", "delta"] + .iter() + .map(|s| s.to_string()) + .collect(); + let now = "import alpha from './alpha'\nimport bravo from './bravo'\nimport charlie from './charlie'\nimport delta from './delta'\n"; + let first = "import alpha from './alpha'\n"; + let p = "src/kinds/index.ts"; + let grew = History::Read { + commits: 4, + earliest: first.to_string(), + }; + assert!(grew_with_kind(p, now, &sibs, &grew)); + assert_eq!(not_a_registry(p, now, &sibs, &grew), None); + // Edited since, but never given a new item: it lists them. + let edited = History::Read { + commits: 3, + earliest: now.to_string(), + }; + assert!(!grew_with_kind(p, now, &sibs, &edited)); + assert!(not_a_registry(p, now, &sibs, &edited) + .unwrap() + .contains("weren't added to it")); + // Unread history is never a block. + assert!(not_a_registry(p, now, &sibs, &History::Unknown) + .unwrap() + .contains("couldn't be read")); + } + + #[test] + fn a_list_of_the_kind_names_most_of_all_its_siblings_not_of_a_sample() { + // Forty siblings; a file that names the first eight alphabetically + // and nothing else names a fifth of the kind: not its list. + let sibs: Vec = (0..40).map(|i| format!("kind-{i:02}")).collect(); + let item = NewItem { + id: "kind-new".into(), + parent: "src/kinds".into(), + folder: false, + ext: "ts".into(), + path: "src/kinds/kind-new.ts".into(), + }; + let some: String = sibs[..8].iter().map(|s| format!("'{s}', ")).collect(); + let all: String = sibs.iter().map(|s| format!("'{s}', ")).collect(); + let files = vec![ ( - "apps/web/migrations/rename-cards/index.ts".to_string(), - "const types = ['accordion', 'alert', 'card']".to_string(), + "src/backfill.ts".to_string(), + format!("const types = [{some}]"), + ), + ( + "src/kinds/index.ts".to_string(), + format!("export const kinds = [{all}]"), ), ]; - assert!(registration_places(item, &sibs, &files).is_empty()); + assert_eq!( + registration_places(&item, &sibs, &files), + vec![("src/kinds/index.ts".to_string(), true)] + ); + } + + #[test] + fn generated_files_are_never_places() { + let item = &new_items( + &["apps/web/src/components/ui/heading.tsx".to_string()], + &ui_tree(), + )[0]; + let sibs = siblings(item, &ui_tree(), None); + let types = "/**\n * This file has been generated by the type generator.\n */\nexport type Accordion = { _type: 'accordion' }\nexport type Alert = { _type: 'alert' }\nexport type Card = { _type: 'card' }\n"; + let schema = r#"[{"name": "accordion"}, {"name": "alert"}, {"name": "card"}]"#; + let files = vec![ + ("apps/web/src/lib/types.ts".to_string(), types.to_string()), + ("apps/studio/schema.json".to_string(), schema.to_string()), + ]; + // By what its head says. + let places = registration_places(item, &sibs, &files); + assert_eq!(places, vec![("apps/studio/schema.json".to_string(), true)]); + // By what the repository's generators write. + let kept = drop_generated(files, &["apps/studio/schema.json".to_string()]); + assert!(registration_places(item, &sibs, &kept).is_empty()); + assert!(says_generated( + "// Code generated by protoc. DO NOT EDIT.\n" + )); + assert!(!says_generated("export const generatedAt = 1\n")); } #[test] diff --git a/services/worker/src/passes/incidents/rg_registered_where_the_kind_grows.rs b/services/worker/src/passes/incidents/rg_registered_where_the_kind_grows.rs new file mode 100644 index 000000000..4760f0f70 --- /dev/null +++ b/services/worker/src/passes/incidents/rg_registered_where_the_kind_grows.rs @@ -0,0 +1,404 @@ +//! rg. Two new-feature runs drafted their pull requests and were blocked +//! "new items aren't registered everywhere their siblings are", both for +//! places that don't register anything: +//! +//! - a run added a validation helper beside a studio's document schemas. +//! The rule called it unregistered in the documents index, in the desk +//! structure, and in a one-off data migration that lists, once, the +//! document types it rewrote; +//! - a run added a `heading` component beside the site's UI components. The +//! rule called it unregistered in the site's `package.json`, which names +//! `@radix-ui/react-accordion` and the like as dependencies. +//! +//! People closed both drafts. The rule took a file for a registry when it +//! named most of a sample of eight siblings (the first eight by name), and +//! told places apart by folder names: `migrations/`, `docs/`, `fixtures/` +//! were never places, every other file could be. So a backfill kept in any +//! other folder, or a generated types file, was a "registry"; and a real +//! registry of migrations (an index every new migration is added to) was +//! never one. +//! +//! Guarantee: a registry is told from a file that merely names the items by +//! what the file is, never by its folder or a list of names. It lists the +//! kind (more than half of all its existing siblings, by path or as whole +//! strings); it is part of the program (not prose, a test or its fixtures, +//! nor a file the repository's generators write or whose head says it is +//! generated); and it grew with the kind (its history names fewer of the +//! siblings when it was written than now). A file that lists them but never +//! grew is noted for a person, and one whose history can't be read is not +//! checked, so neither blocks. Only a checked registry blocks, and the coder +//! is told to add the entry itself first. + +use super::fixture::*; +use crate::passes::feature::registration::{self, History, Kind, NewItem}; +use crate::passes::generators; + +const OLD: &str = "isn't registered in `apps/studio/backfills"; + +/// A studio's document schemas, by the name of their type. +fn documents() -> Vec { + [ + "berth", + "boat", + "boat-index", + "captain", + "charter", + "charter-index", + "crew", + "dock", + "dock-index", + "ferry", + "fuel-dock", + "harbor-page", + "lesson", + "lesson-index", + "marina", + "mooring", + "pier", + "regatta", + "regatta-index", + "sail", + "slip", + ] + .iter() + .map(|s| s.to_string()) + .collect() +} + +fn doc_path(name: &str) -> String { + format!("apps/studio/schemaTypes/documents/{name}.ts") +} + +fn doc_schema(name: &str) -> String { + format!( + "import {{defineField, defineType}} from 'cms-kit'\n\nexport default defineType({{\n \ + name: '{name}',\n type: 'document',\n fields: [defineField({{name: 'title', type: 'string'}})],\n}})\n" + ) +} + +fn camel(name: &str) -> String { + let mut out = String::new(); + let mut up = false; + for c in name.chars() { + if c == '-' { + up = true; + } else if up { + out.push(c.to_ascii_uppercase()); + up = false; + } else { + out.push(c); + } + } + out +} + +/// The documents index, importing each schema's default export: `upto` of +/// them (in name order). +fn index_of(upto: usize) -> String { + let docs = documents(); + let mut s = String::new(); + for d in &docs[..upto] { + s.push_str(&format!("import {} from './{d}'\n", camel(d))); + } + let names: Vec = docs[..upto].iter().map(|d| camel(d)).collect(); + s.push_str(&format!( + "\nexport const documents = [{}]\n", + names.join(", ") + )); + s +} + +/// The desk structure, listing every document type by name. +fn structure() -> String { + let items: String = documents() + .iter() + .map(|d| format!(" S.documentTypeListItem('{d}'),\n")) + .collect(); + format!("export const structure = (S) =>\n S.list().items([\n{items} ])\n") +} + +/// A one-off backfill: the types it rewrote, once. Kept beside the studio, +/// not in a folder called `migrations`. +fn backfill() -> String { + "import {defineMigration} from 'cms-kit/migrate'\n\nexport default defineMigration({\n \ + title: 'Replace the slip url with a link object',\n documentTypes: [\n 'berth',\n \ + 'boat-index',\n 'captain',\n 'charter-index',\n 'dock',\n 'ferry',\n 'pier',\n \ + 'regatta',\n ],\n migrate: {},\n})\n" + .to_string() +} + +/// The site's generated types (the fixture's typegen writes them), naming +/// every document type. +fn generated_types() -> String { + let types: String = documents() + .iter() + .map(|d| format!("export type {} = {{ _type: \"{d}\" }}\n", camel(d))) + .collect(); + format!( + "/**\n * This file has been generated by the CMS type generator.\n * Command: `typegen generate`\n */\n\n{types}" + ) +} + +fn tree() -> Vec { + let mut t: Vec = documents().iter().map(|d| doc_path(d)).collect(); + t.extend( + [ + "apps/studio/schemaTypes/documents/index.ts", + "apps/studio/structure.ts", + "apps/studio/backfills/replace-slip-url/index.ts", + TYPES, + ] + .iter() + .map(|s| s.to_string()), + ); + t +} + +/// The files code search finds for the siblings, as the default branch has +/// them. +fn found() -> Vec<(String, String)> { + vec![ + ( + "apps/studio/schemaTypes/documents/index.ts".to_string(), + index_of(documents().len()), + ), + ("apps/studio/structure.ts".to_string(), structure()), + ( + "apps/studio/backfills/replace-slip-url/index.ts".to_string(), + backfill(), + ), + (TYPES.to_string(), generated_types()), + ] +} + +/// Each place's history: the index and the structure gained a type with +/// every new document; the backfill was written once. +fn history(p: &str) -> History { + match p { + "apps/studio/schemaTypes/documents/index.ts" => History::Read { + commits: 18, + earliest: index_of(3), + }, + "apps/studio/structure.ts" => History::Read { + commits: 14, + earliest: "export const structure = (S) =>\n S.list().items([\n S.documentTypeListItem('berth'),\n ])\n".to_string(), + }, + "apps/studio/backfills/replace-slip-url/index.ts" => History::Read { + commits: 1, + earliest: backfill(), + }, + _ => History::Unknown, + } +} + +fn item(path: &str) -> NewItem { + registration::new_items(&[path.to_string()], &tree()) + .into_iter() + .next() + .expect("a new item") +} + +/// The rule after its reads, as `registration::check` runs it, for a new +/// file with `text` that the branch registers nowhere. +fn replay(path: &str, text: &str) -> Vec { + let item = item(path); + let sibs = registration::siblings(&item, &tree(), None); + let files = registration::drop_generated(found(), &typegen_outputs()); + let keep = registration::registration_places(&item, &sibs, &files); + let places: Vec<(String, String, bool)> = files + .into_iter() + .filter_map(|(p, t)| keep.iter().find(|(k, _)| *k == p).map(|(_, r)| (p, t, *r))) + .collect(); + let registries: Vec<&str> = places + .iter() + .filter(|(_, _, r)| *r) + .map(|(_, t, _)| t.as_str()) + .collect(); + let sib_files: Vec<(String, String)> = sibs + .iter() + .take(3) + .map(|s| (doc_path(s), doc_schema(s))) + .collect(); + let kind = registration::kind_of(Some((path, text)), &sib_files, ®istries, &sibs); + if matches!(kind, Kind::Other(_)) { + return Vec::new(); + } + let (places, listed) = registration::settle_places(places, &sibs, &history); + let base = found(); + let unchanged = |p: &str| base.iter().find(|(q, _)| q == p).map(|(_, t)| t.clone()); + let mut m = registration::judge(&item, &sibs, &kind, &places, &unchanged); + registration::mark_listed(&mut m, &listed); + m +} + +/// What the fixture monorepo's typegen writes, from its own config. +fn typegen_outputs() -> Vec { + generators::detect(&monorepo()) + .into_iter() + .flat_map(|g| g.outputs) + .map(|o| generators::normalize_path(&o)) + .collect() +} + +#[test] +fn a_one_off_backfill_lists_the_types_it_never_registers_them() { + let item = item("apps/studio/schemaTypes/documents/promo.ts"); + let sibs = registration::siblings(&item, &tree(), None); + assert_eq!(sibs.len(), documents().len(), "every sibling, not a sample"); + // It names eight of twenty-one types: not the kind's list. + let places = registration::registration_places( + &item, + &sibs, + &[( + "apps/studio/backfills/replace-slip-url/index.ts".to_string(), + backfill(), + )], + ); + assert!(places.is_empty(), "{places:?}"); +} + +#[test] +fn a_generated_file_is_never_a_place() { + let item = item("apps/studio/schemaTypes/documents/promo.ts"); + let sibs = registration::siblings(&item, &tree(), None); + let places = + registration::registration_places(&item, &sibs, &[(TYPES.to_string(), generated_types())]); + assert!(places.is_empty(), "{places:?}"); + // And by the repository's own generator config, whatever the file says. + assert!(typegen_outputs() + .iter() + .any(|o| o == TYPES || o == SCHEMA_JSON)); + let schema = documents() + .iter() + .map(|d| format!("{{\"name\": \"{d}\"}}")) + .collect::>() + .join(","); + let kept = registration::drop_generated( + vec![(SCHEMA_JSON.to_string(), format!("[{schema}]"))], + &typegen_outputs(), + ); + assert!(kept.is_empty()); +} + +#[test] +fn a_registry_kept_under_a_migrations_folder_is_still_a_registry() { + // Migrations are a kind too: every new one is added to the index. + let t: Vec = [ + "db/migrations/0001-create-berths.ts", + "db/migrations/0002-add-slips.ts", + "db/migrations/0003-add-moorings.ts", + "db/migrations/0004-add-charters.ts", + "db/migrations/index.ts", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let item = ®istration::new_items(&["db/migrations/0005-add-ferries.ts".to_string()], &t)[0]; + let sibs = registration::siblings(item, &t, None); + assert_eq!(sibs.len(), 4); + let index = "import m1 from './0001-create-berths'\nimport m2 from './0002-add-slips'\n\ + import m3 from './0003-add-moorings'\nimport m4 from './0004-add-charters'\n\ + export const migrations = [m1, m2, m3, m4]\n"; + let places = registration::registration_places( + item, + &sibs, + &[("db/migrations/index.ts".to_string(), index.to_string())], + ); + assert_eq!(places, vec![("db/migrations/index.ts".to_string(), true)]); + let grew = History::Read { + commits: 4, + earliest: "import m1 from './0001-create-berths'\nexport const migrations = [m1]\n".into(), + }; + assert!(registration::grew_with_kind( + "db/migrations/index.ts", + index, + &sibs, + &grew + )); +} + +#[test] +fn the_helper_and_a_real_new_document_end_as_they_should() { + // The run's helper: another kind, nothing to register. + let helper = "import type {ValidationContext} from 'cms-kit'\n\n\ + export function endsAfterStart(value: unknown, context: ValidationContext) {\n \ + return true\n}\n"; + assert!(replay( + "apps/studio/schemaTypes/documents/promo-validation.ts", + helper + ) + .is_empty()); + + // A real new document the branch didn't register: blocked on the two + // registries only; the backfill and the generated types aren't places. + let m = replay( + "apps/studio/schemaTypes/documents/promo.ts", + &doc_schema("promo"), + ); + let mut end = Ending::default(); + for x in &m { + end.said(x.line()); + } + let b = registration::blocking(&m); + let paths: Vec<&str> = b.iter().map(|x| x.path.as_str()).collect(); + assert_eq!( + paths, + vec![ + "apps/studio/schemaTypes/documents/index.ts", + "apps/studio/structure.ts" + ], + "{:?}", + end.words + ); + end.never_says(OLD); + end.never_says(TYPES); + assert!(registration::feedback(&b).contains("Add the entry yourself")); +} + +#[test] +fn a_list_that_never_grew_or_an_unread_history_never_blocks() { + let item = item("apps/studio/schemaTypes/documents/promo.ts"); + let sibs = registration::siblings(&item, &tree(), None); + let all: String = documents().iter().map(|d| format!("'{d}', ")).collect(); + // A backfill over every type: it lists the kind, written once. + let every = format!("export default defineMigration({{ documentTypes: [{all}] }})\n"); + let p = "apps/studio/backfills/touch-all/index.ts".to_string(); + let places = vec![(p.clone(), every.clone(), true)]; + let (settled, listed) = + registration::settle_places(places.clone(), &sibs, &|_| History::Read { + commits: 1, + earliest: every.clone(), + }); + let mut m = registration::missing(&item, &sibs, &settled, &|_| Some(every.clone())); + registration::mark_listed(&mut m, &listed); + assert_eq!(m.len(), 1); + assert!(registration::blocking(&m).is_empty()); + assert!(m[0].line().contains("check by hand")); + // History unread: noted, never blocked. + let (settled, listed) = registration::settle_places(places, &sibs, &|_| History::Unknown); + assert!(!settled[0].2); + assert!(listed[0].1.contains("couldn't be read")); +} + +#[test] +fn a_dependency_in_a_manifest_is_still_no_registration() { + let t: Vec = [ + "apps/web/src/components/ui/accordion.tsx", + "apps/web/src/components/ui/alert.tsx", + "apps/web/src/components/ui/card.tsx", + "apps/web/package.json", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let item = + ®istration::new_items(&["apps/web/src/components/ui/heading.tsx".to_string()], &t)[0]; + let sibs = registration::siblings(item, &t, None); + let pkg = r#"{"dependencies": {"@radix-ui/react-accordion": "1.2.11", "@radix-ui/react-alert-dialog": "1.1.11", "@radix-ui/react-hover-card": "1.1.11"}}"#; + assert!(registration::registration_places( + item, + &sibs, + &[("apps/web/package.json".to_string(), pkg.to_string())] + ) + .is_empty()); +} From 819f1ec0b1cdb3a88ad6409038b174b442f1766f Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 21 Nov 2026 01:16:05 -0500 Subject: [PATCH 3/8] A run whose planned tasks stop moving ships what is done, never hands it back The guard's count of continuations without a finished task fired one step after the supervisor's ladder deferred the first stuck task, with words that hand the work to a person ("it continued 7 times without finishing another task ... Push to the branch"). The draft it opened shipped the work, but the stop stayed on the run, so the pull request's CI fix round and ready decision hit the stop on their first pass and the run ended failed instead of fixed. That stop is now a shipping stop like the converged one: its reason says what shipped and that the open tasks are deferred with why, and it is taken back once the work is on its pull request. Spend, pass transitions and the run ceilings stay hard stops. Incident dq replays the stuck run's steps through the step marks, the ladder and the guard. --- docs/incidents/dq_unfinished_stop_ships.md | 5 + .../incidents/dq_unfinished_stop_ships.rs | 133 ++++++++++++++++++ services/worker/src/passes/run_guard.rs | 53 +++++-- 3 files changed, 176 insertions(+), 15 deletions(-) create mode 100644 docs/incidents/dq_unfinished_stop_ships.md create mode 100644 services/worker/src/passes/incidents/dq_unfinished_stop_ships.rs diff --git a/docs/incidents/dq_unfinished_stop_ships.md b/docs/incidents/dq_unfinished_stop_ships.md new file mode 100644 index 000000000..d44d68c77 --- /dev/null +++ b/docs/incidents/dq_unfinished_stop_ships.md @@ -0,0 +1,5 @@ +# dq. `dq_unfinished_stop_ships` + +**What happened:** A run on a large ticket finished 23 of its 38 planned tasks, then spent nine steps reading the same files and writing nothing, because the files it was told were missing already had their planned form. The guard ended it with "CoderHelm stopped this run and handed it to you: it continued 7 times without finishing another task". Another run did the same on one README line: each step re-read the file, thought to the output limit and wrote nothing. The measuring and the cut replies were fixed on their own, and a stuck task now climbs the supervisor's ladder. But the guard's count of continuations without a finished task still ended the run one step after the ladder deferred the first stuck task, in words that hand the work to a person, and the stop stayed on the run, so the draft it shipped could not take a CI fix round. + +**The guarantee:** A run whose planned tasks stop moving changes approach first: the ladder (one task, fresh context with edits in place, a re-split, the strongest model, then the task deferred) runs before the guard's count is spent. When the count is spent, the run ships what is done with the rest deferred, and says so. That stop is taken back once the work is on its pull request, so CI's errors and comments start the next round. A CoderHelm limit never hands unfinished work to a person. diff --git a/services/worker/src/passes/incidents/dq_unfinished_stop_ships.rs b/services/worker/src/passes/incidents/dq_unfinished_stop_ships.rs new file mode 100644 index 000000000..eb9b200d4 --- /dev/null +++ b/services/worker/src/passes/incidents/dq_unfinished_stop_ships.rs @@ -0,0 +1,133 @@ +//! dq. A run on a large ticket finished 23 of its 38 planned tasks and then +//! spent nine steps reading the same files: each step searched, read, ran +//! the checks and wrote nothing, because the files it was told were missing +//! were already in their planned form. The guard ended it with "CoderHelm +//! stopped this run and handed it to you: it continued 7 times without +//! finishing another task ... Push to the branch or comment on the pull +//! request". A later run on another ticket did the same on one README line: +//! every step re-read the file, thought to the output limit and wrote +//! nothing, until the run stopped with the work on a held draft. +//! +//! The measuring and the cut replies are fixed on their own (`u`, the cut +//! retry in `agent::anthropic`), and a stuck task now climbs the +//! supervisor's ladder: one task, fresh context with edits in place, a +//! re-split, the strongest model, then the task deferred. But the guard's +//! count of continuations without a finished task still ended the run one +//! step after the ladder deferred the first stuck task, with the old words +//! that hand the work to a person, and its stop stayed on the run: the draft +//! it shipped could not take a CI fix round, because the round's first pass +//! hit the stop and the run ended failed instead of fixed. +//! +//! Guarantee: a run whose planned tasks stop moving changes approach first +//! (the ladder runs before the guard's count is spent), and when the count +//! is spent it ships what is done with the rest deferred, in words that say +//! so. It is a shipping stop: it is taken back once the work is on its pull +//! request, so CI's errors and comments start the next round. A CoderHelm +//! limit never hands unfinished work to a person. + +use super::fixture::fn_src; +use crate::passes::run_guard::*; +use crate::passes::steps; +use crate::passes::supervisor::{self, Rung}; + +/// What a recorded implement step cost, in USD (the README run's steps +/// spent 2.3 to 2.9 each). +const STEP_USD: f64 = 2.6; + +/// The recorded shape: the last task finished in the step before the first +/// hand-off; from then on each step writes nothing and the branch's head +/// stays where it is. Each hand-off is counted by the guard, then the next +/// step starts and the supervisor reads its stall from the step marks. The +/// ladder's rungs in order, and the guard's stop when it fired. +fn replay() -> (Vec, Option, GuardState) { + let at = "implement_started"; + let head = "4f0c2aa"; + let mut g = GuardState::default(); + assert!(g.apply(&Progress::TasksDone(23))); + // The mark the last productive step started at: its head moved since. + let mut prev = Some(steps::progress_mark("19be3d0", at)); + let mut stalled = 0; + let mut rungs = Vec::new(); + for _ in 0..20 { + // The step before hands off: no task finished. + g.on_continuation_to(STEP_USD, &Target::default()); + if let Some(trip) = g.trip() { + return (rungs, Some(trip), g); + } + // The next step starts and compares where the run stands. + let now = steps::progress_mark(head, at); + stalled = steps::stalled_after(prev.as_deref(), &now, stalled); + let rung = supervisor::next_rung(stalled, true); + rungs.push(rung); + match rung { + // A deferred task is settled: the next step counts from clean. + Rung::Defer => stalled = 0, + Rung::Ship => return (rungs, None, g), + _ => {} + } + prev = Some(now); + // Its plan check: the same 23 done, the next stuck task first. + assert!(!g.apply(&Progress::TasksDone(23))); + } + (rungs, None, g) +} + +#[test] +fn a_stuck_task_changes_approach_before_the_guard_stops_the_run() { + let (rungs, _, _) = replay(); + for r in [ + Rung::Narrow, + Rung::SwitchTools, + Rung::Resplit, + Rung::Escalate, + Rung::Defer, + ] { + assert!(rungs.contains(&r), "the ladder never reached {r:?}: {rungs:?}"); + } + // Never the same ask twice in a row after a step that changed nothing. + for w in rungs.windows(2) { + assert!(w[0] == Rung::Continue || w[0] != w[1], "{rungs:?}"); + } +} + +#[test] +fn a_spent_count_with_tasks_open_ships_and_is_never_handed_back() { + let (_, trip, mut g) = replay(); + let trip = trip.expect("the guard's count is spent with tasks still open"); + assert_eq!(trip, Trip::Continuations); + assert!(trip.ships(), "a CoderHelm limit ships what is done"); + assert!( + ships_code(trip.code()), + "the stop is taken back once the work is on its pull request" + ); + let why = trip.reason(&g); + assert!(!why.contains("handed it to you"), "{why}"); + assert!(!why.contains("without finishing another task"), "{why}"); + assert!(why.contains("shipped"), "{why}"); + assert!(why.contains("deferred"), "{why}"); + assert!(why.contains("fixes what CI reports"), "{why}"); + // Shipping starts the counts over: the rounds CI or a comment starts + // aren't stopped by the steps before them. + g.shipped(); + assert_eq!(g.trip(), None); + // The hard stops stay hard. + assert!(!ships_code(Trip::Spend.code())); + assert!(!ships_code(Trip::Transitions.code())); + assert!(!ships_code("ceiling_continuations")); +} + +/// A guard stop in a ticket step goes to the shipping draft, and that draft +/// takes back a shipping stop; a run with its pull request takes it back +/// before any hand-back is judged. +#[test] +fn the_pipeline_ships_and_takes_back_the_guard_stop() { + let guard = include_str!("../run_guard.rs"); + let end = fn_src(guard, "\npub async fn end_if_stopped("); + assert!(end.contains("stop_pr::open_with("), "{end}"); + assert!(end.contains("lift_shipped_stop("), "{end}"); + let settle = fn_src(guard, "\npub async fn settle_open_pr("); + assert!( + settle.find("ships_code(").unwrap() < settle.find("stop_judge").unwrap(), + "a shipping stop is never judged as a hand-back" + ); +} diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index eab03ec30..acaa414fb 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -24,8 +24,10 @@ //! not progress. Each of these only moves one way (or is capped elsewhere), //! so a checker that keeps finding something can't keep resetting the count. //! - When the guard fires a run ends one way, always: a draft pull request -//! with what exists and its Open items, status `needs_input`, a plain reason -//! on the run page, one notification, and the reason recorded for analytics. +//! with what exists and its Open items, a plain reason on the run page, one +//! notification, and the reason recorded for analytics. A stop over planned +//! work (tasks done, or tasks stuck after the supervisor's ladder) ships and +//! is taken back once the work is on its pull request ([`ships_code`]). //! //! [`Ledger`] is the other half: the pull request the run opened, what each //! check found on which head, and how many fix rounds it took, kept across @@ -119,12 +121,18 @@ const _: () = assert!(MAX_TRANSITIONS_WITHOUT_PROGRESS >= worst_normal_run()); /// The stored code of a [`Trip::Converged`] stop. pub const CONVERGED: &str = "converged_with_open_items"; -/// Stop codes that ship the work instead of handing it back: the current one -/// and the after-work cap it replaced (still on older runs' records). +/// Stop codes that ship the work instead of handing it back: the run that +/// converged, the run whose planned tasks stopped moving (its count of +/// continuations is spent after the supervisor's ladder changed approach), +/// and the after-work cap converging replaced (still on older runs' +/// records). Spend, pass transitions and the run's ceilings stay hard stops. pub fn ships_code(code: &str) -> bool { - matches!(code, CONVERGED | "continuations_after_work") + matches!(code, CONVERGED | CONTINUATIONS | "continuations_after_work") } +/// The stored code of a [`Trip::Continuations`] stop. +pub const CONTINUATIONS: &str = "continuations"; + /// Why the guard ended a run. The stored code is what analytics counts. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Trip { @@ -133,7 +141,11 @@ pub enum Trip { /// Never a hand-back: CI and comments on the pull request still start /// rounds ([`Trip::ships`]). Converged, - /// Continuations without progress, tasks still open. + /// Continuations without progress, tasks still open. By then the + /// supervisor's ladder has changed approach on the stuck task (one task, + /// fresh context with edits in place, a re-split, the strongest model, + /// then the task deferred): the run ships what is done with the rest + /// deferred, never a hand-back ([`Trip::ships`]). Continuations, /// Pass transitions without progress. Transitions, @@ -145,7 +157,7 @@ impl Trip { pub fn code(self) -> &'static str { match self { Trip::Converged => CONVERGED, - Trip::Continuations => "continuations", + Trip::Continuations => CONTINUATIONS, Trip::Transitions => "pass_transitions", Trip::Spend => "spend", } @@ -155,7 +167,7 @@ impl Trip { /// done, so what is left is checks and fixes CoderHelm can still make, /// and new evidence (a red check with its error, a comment) starts them. pub fn ships(self) -> bool { - matches!(self, Trip::Converged) + matches!(self, Trip::Converged | Trip::Continuations) } /// What the run page says, in plain words. @@ -176,13 +188,19 @@ impl Trip { comment there starts another round." ); } - let what = match self { - // Answered above: it ships, it is never handed back. - Trip::Converged => String::new(), - Trip::Continuations => format!( - "it continued {} times without finishing another task", + if self == Trip::Continuations { + return format!( + "CoderHelm shipped what is done on the pull request: {} continuation(s) in a row \ + finished no further planned task after it changed its approach on the stuck \ + one, so the tasks still open are deferred there with why. CoderHelm fixes what \ + CI reports on the pull request, and a push or a comment there starts another \ + round.", g.continuations - ), + ); + } + let what = match self { + // Answered above: they ship, they are never handed back. + Trip::Converged | Trip::Continuations => String::new(), Trip::Transitions => format!( "it moved between steps {} times with no task finished, no fewer open findings \ and no green CI", @@ -1792,7 +1810,12 @@ mod tests { assert!(why.contains("fixes what CI reports"), "{why}"); assert!(!why.contains("handed it to you"), "{why}"); let why = Trip::Continuations.reason(&GuardState::default()); - assert!(why.contains("Push to the branch or comment"), "{why}"); + assert!(why.contains("shipped what is done"), "{why}"); + assert!(why.contains("a push or a comment"), "{why}"); + assert!(!why.contains("handed it to you"), "{why}"); + assert!(Trip::Transitions + .reason(&GuardState::default()) + .contains("Push to the branch or comment")); let g = GuardState { spend_usd: 20.5, ..Default::default() From abfd79329440a26ac0777f5c71c24d22a4f87310 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 21 Nov 2026 01:29:55 -0500 Subject: [PATCH 4/8] A wait is reminded once and its stated default is taken; an alert firing again never starts a second run; a fresh run ends its ticket's earlier waits The stuck-run sweep measured a wait from the run's last update, which its own reminder moved, so every wait was reminded daily; and its scan never read the default and deadline fields, so no stated default was ever taken. An alarm's gate compared two different texts, so each firing started a run beside the one still waiting. A run waiting on a person was not live, so a new trigger took the ticket over and left the old wait behind. --- .../dj_new_run_ends_earlier_waits.md | 5 ++ lambda/stuck-run-cleanup/handler.py | 17 +++- lambda/tests/test_stuck_run_cleanup.py | 89 +++++++++++++++++++ services/common/src/one_run.rs | 32 +++++++ services/gateway/src/routes/alerts.rs | 8 +- services/gateway/src/routes/trigger_gate.rs | 87 +++++++++++++++++- .../dj_new_run_ends_earlier_waits.rs | 65 ++++++++++++++ services/worker/src/passes/one_run.rs | 69 ++++++++++++++ 8 files changed, 363 insertions(+), 9 deletions(-) create mode 100644 docs/incidents/dj_new_run_ends_earlier_waits.md create mode 100644 services/worker/src/passes/incidents/dj_new_run_ends_earlier_waits.rs diff --git a/docs/incidents/dj_new_run_ends_earlier_waits.md b/docs/incidents/dj_new_run_ends_earlier_waits.md new file mode 100644 index 000000000..3a01f48be --- /dev/null +++ b/docs/incidents/dj_new_run_ends_earlier_waits.md @@ -0,0 +1,5 @@ +# dj. `dj_new_run_ends_earlier_waits` + +**What happened:** A booking ticket's run asked a person which booking page to embed and waited. Ten minutes later a comment on the ticket answered it and started a fresh run, which built the pages and opened its pull request. The first run went on waiting, reminded once a day, though its question was long settled. An alarm did the same: each firing started a run beside the one still asking, and two of those were still waiting days after a third had finished the fix. A run waiting on a person was not counted as live, so a new trigger took the ticket over, and nothing ended the old wait. + +**The guarantee:** When a fresh run of a ticket takes its claim, every earlier run of that ticket in the same repository that is still waiting on a person stops waiting (`one_run::earlier_waits`, `passes::one_run::end_earlier_waits`). It becomes `retried`, points at the new run, and its page says where the work went. The write only applies while that run still waits. A run that ended any other way is left as it is, and a run of the same ticket in another repository is its own. diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index 2a4494133..61a8062b8 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -66,6 +66,11 @@ REMINDED_FIELD = "wait_reminded_at" WAIT_REMIND_AFTER_HOURS = 24 QUESTIONS_FIELD = "questions" +# A judged question's default and deadline (worker stop_judge::keep_ask_deadline) +# and the sweep's claim on it: settle_waiting reads them, so the scan must too. +# The scan once left them out, every deadline read as absent, and no default +# was ever taken. +WAIT_FIELDS = ("ask_default", "ask_deadline", "ask_default_taken_at") # The worker's queue: the reminder and the notice for a named wait go out as # a `run_waiting` message (services/common/contract/worker_messages.json). TICKET_QUEUE_URL = os.environ.get("TICKET_QUEUE_URL", "") @@ -250,10 +255,15 @@ def said_nothing(run): def wait_since(run): - """When the current wait started: its waiting_on, else the last update.""" + """When the current wait started: its waiting_on's `since`, else when its + questions were asked, else when the run was created. Never the last + update: every note moves updated_at, the reminder's own note included, + so a wait counted from it was due its "one" reminder again every day.""" wait = _json(run.get(WAITING_ON_FIELD)) or {} since = _parse_time(wait.get("since")) if isinstance(wait, dict) else None - return since or _parse_time(run.get("updated_at") or run.get("created_at")) + asked = _json(run.get(QUESTIONS_FIELD)) or {} + asked_at = _parse_time(asked.get("asked_at")) if isinstance(asked, dict) else None + return since or asked_at or _parse_time(run.get("created_at") or run.get("updated_at")) def reminder_due(run, now): @@ -672,7 +682,8 @@ def handler(event, context): "ProjectionExpression": ( "team_id, run_id, created_at, updated_at, title, current_pass, pass_history, #s, " "step_queued_at, ceil_passes, ceil_continuations, ceil_worked_secs, ceil_spend_usd, " - "#round, pr_number, pr_url, error_message, #q, #w, #r, #oc, #notes" + "#round, pr_number, pr_url, error_message, #q, #w, #r, #oc, #notes, " + + ", ".join(WAIT_FIELDS) ), } scan_kwargs["ExpressionAttributeNames"]["#round"] = ROUND_FIELD diff --git a/lambda/tests/test_stuck_run_cleanup.py b/lambda/tests/test_stuck_run_cleanup.py index 720e3e5a5..c3880545d 100644 --- a/lambda/tests/test_stuck_run_cleanup.py +++ b/lambda/tests/test_stuck_run_cleanup.py @@ -306,6 +306,95 @@ def test_a_passed_question_deadline_goes_ahead_with_the_default_once(self): self.assertEqual(out["waiting_defaulted"], 0) self.assertNotIn("deadline", [m["why"] for m in sent]) + def _sweep_projected(self, runs): + """The sweep against a table that returns only the fields its scan + names, as DynamoDB does.""" + updates, sent = [], [] + + class Table: + def scan(self, **kw): + names = kw.get("ExpressionAttributeNames", {}) + fields = {names.get(f.strip(), f.strip()) for f in kw["ProjectionExpression"].split(",")} + return {"Items": [{k: v for k, v in r.items() if k in fields} for r in runs]} + + def update_item(self, **kw): + updates.append(kw) + + class Db: + class meta: + class client: + class exceptions: + ConditionalCheckFailedException = KeyError + + def Table(self, _name): + return Table() + + class Sqs: + def send_message(self, **kw): + sent.append(sweep.json.loads(kw["MessageBody"])) + + sweep._dynamodb, sweep._sqs = Db(), Sqs() + old_url, sweep.TICKET_QUEUE_URL = sweep.TICKET_QUEUE_URL, "https://sqs/q" + try: + out = sweep.handler({}, None) + finally: + sweep._dynamodb, sweep._sqs, sweep.TICKET_QUEUE_URL = None, None, old_url + return out, updates, sent + + def test_a_stated_default_is_taken_from_what_the_scan_reads(self): + # A run asked which page to embed, said what it would build if no one + # answered in a day, and kept the default and deadline on its record. + # The sweep's scan didn't read those fields, so the default was never + # taken and the run sat waiting, reminded, for days. + run = { + "team_id": "T", + "run_id": "R", + "status": "needs_input", + "created_at": "2026-11-14T15:30:06+00:00", + "updated_at": "2026-11-14T15:38:59+00:00", + "questions": '{"questions":[{"id":"q1","question":"Which booking page?"}],' + '"asked_at":"2026-11-14T15:38:59+00:00"}', + "ask_default": "Build with the live program page", + "ask_deadline": "2026-11-15T15:38:57.195130843+00:00", + "ask_question": "Which booking page?", + } + out, updates, sent = self._sweep_projected([run]) + self.assertEqual(out["waiting_defaulted"], 1) + self.assertEqual(out["waiting_reminded"], 0) + self.assertEqual(sent, [{"type": "run_waiting", "team_id": "T", "run_id": "R", "why": "deadline"}]) + # Taken once: a record that says so is reminded at most, never defaulted again. + out, _, sent = self._sweep_projected([dict(run, ask_default_taken_at=self.NOW.isoformat())]) + self.assertEqual(out["waiting_defaulted"], 0) + self.assertNotIn("deadline", [m["why"] for m in sent]) + + def test_a_question_is_reminded_once_however_often_its_record_changes(self): + # A run asked before waits were recorded (questions, no waiting_on). + # Each reminder's note moved updated_at, the wait counted from + # updated_at, so the next day it was due again: 15 reminders in 15 + # days, one every 24 hours and ten minutes. + run = { + "team_id": "T", + "run_id": "R", + "status": "needs_input", + "created_at": "2026-11-02T21:03:11+00:00", + "questions": '{"questions":[{"id":"q1","question":"Which branch?"}],' + '"asked_at":"2026-11-02T21:12:00+00:00"}', + } + first = sweep.datetime(2026, 11, 6, 16, 41, 19, tzinfo=sweep.timezone.utc) + self.assertTrue(sweep.reminder_due(dict(run, updated_at="2026-11-02T21:12:01+00:00"), first)) + # The reminder is sent; its note moves updated_at a second later. + after = dict( + run, + wait_reminded_at="2026-11-06T16:41:18+00:00", + updated_at="2026-11-06T16:41:19+00:00", + ) + for days in (1, 2, 14): + self.assertFalse(sweep.reminder_due(after, first + sweep.timedelta(days=days, minutes=10))) + self.assertEqual(sweep.wait_since(after).isoformat(), "2026-11-02T21:12:00+00:00") + out, updates, sent = self._sweep_projected([after]) + self.assertEqual(out["waiting_reminded"], 0) + self.assertEqual(sent, []) + def test_without_a_pull_request_it_waits_for_a_retry(self): wait = sweep.named_wait({"error_message": "stopped"}, "now") self.assertIn("Retry", wait["action"]) diff --git a/services/common/src/one_run.rs b/services/common/src/one_run.rs index 446dad744..f9fbf0af1 100644 --- a/services/common/src/one_run.rs +++ b/services/common/src/one_run.rs @@ -169,6 +169,38 @@ pub fn held_note(ticket_id: &str, source: &TicketSource) -> String { ) } +/// The ticket's earlier runs that still wait on a person (`needs_input`) +/// when fresh run `me` of it starts in `repo` (`owner/name`): `runs` is the +/// ticket's runs as `(run_id, status, repo)`. A waiting run is not live, so a +/// new trigger (a ticket edit, the alert firing again, a hand-queued ticket) +/// starts a fresh run beside it, and the old one went on waiting and being +/// reminded for days, its question already moot. Only runs older than `me` +/// (run ids sort by creation) in the same repository: a ticket worked in two +/// repositories has a run in each. +pub fn earlier_waits<'a>( + me: &str, + repo: &str, + runs: &'a [(String, String, String)], +) -> Vec<&'a str> { + runs.iter() + .filter(|(id, status, r)| { + id.as_str() < me + && status == crate::run_status::NEEDS_INPUT + && r.eq_ignore_ascii_case(repo) + }) + .map(|(id, _, _)| id.as_str()) + .collect() +} + +/// The note on an earlier waiting run when a fresh run of its ticket ends +/// its wait. +pub fn ended_wait_note(new_run: &str) -> String { + format!( + "A newer run of this ticket started ({new_run}): this run no longer waits, and the \ + ticket's work goes on there." + ) +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/gateway/src/routes/alerts.rs b/services/gateway/src/routes/alerts.rs index 968bb71f2..d6a78b169 100644 --- a/services/gateway/src/routes/alerts.rs +++ b/services/gateway/src/routes/alerts.rs @@ -1526,14 +1526,16 @@ async fn start_run( return Ok(Outcome::DailyCap); } - let context_hash = common::ticket_context_hash(&alert.title, &alert.body, &[]); + // A firing is the alert opening again, never an edit of its ticket + // (`trigger_gate::alert_firing`). + let (content, reopened) = super::trigger_gate::alert_firing(); match super::trigger_gate::gate_ticket_trigger( state, &route.team_id, tid, - Some(&context_hash), - false, + content, false, + reopened, None, false, ) diff --git a/services/gateway/src/routes/trigger_gate.rs b/services/gateway/src/routes/trigger_gate.rs index 1444c9d37..df542c2c7 100644 --- a/services/gateway/src/routes/trigger_gate.rs +++ b/services/gateway/src/routes/trigger_gate.rs @@ -50,6 +50,11 @@ //! one: on GitHub adding the trigger label or assigning CoderHelm, on //! Jira re-adding the trigger label or re-assigning to CoderHelm. Retry, //! commands and those gestures are never blocked by the cap +//! - an alert firing again is the alert reopening, never an edit +//! ([`alert_firing`]): while its run waits on a person, reports a change +//! outside the code or has its PR open, it starts nothing. Each firing's +//! own values (the datapoint, the time) used to read as a changed ticket, +//! and every firing started a run beside the one already asking //! - explicit human triggers (slash commands, comment retries) skip the //! content check but still respect in-flight blocking @@ -188,6 +193,22 @@ fn decide(latest: &LatestRun, new_hash: Option<&str>, reopened: bool) -> Decisio } } +/// What an alert's firing gives the gate: no content hash, and `reopened`. +/// +/// An alert has no edits. Each firing carries its own values (the datapoint, +/// the time the alarm changed), and the gate hashed the alert's text while the +/// run keeps the hash of the ticket text the worker reads, so the two never +/// matched: every firing past the alert's repeat window read as an edited +/// ticket and started a new run beside the one already waiting on a person +/// for the same alarm. A firing is the alert opening again. While its run +/// waits on a person, reports a change outside the code, or has its pull +/// request open, it starts nothing; after its fix merged, or a person closed +/// the run, it starts one (the fix didn't hold); a failed run is tried again +/// up to [`MAX_FAILED_RUNS_IN_A_ROW`]. +pub fn alert_firing() -> (Option<&'static str>, bool) { + (None, true) +} + /// A person's retry gesture on a GitHub issue: adding the `coderhelm` label, /// or assigning the issue to CoderHelm. These are the only issue events that /// start runs, so the failed-run cap never applies to one. @@ -640,9 +661,9 @@ pub fn expected_attachment_keys( #[cfg(test)] mod tests { use super::{ - decide, edit_note, failed_in_a_row, field, github_retry_gesture, handled, is_trigger_label, - jira_reopened, jira_retry_gesture, latest_ended_on_merge, latest_run, own_runs, retry_note, - Decision, Item, LatestRun, OpenPr, MAX_FAILED_RUNS_IN_A_ROW, + alert_firing, decide, edit_note, failed_in_a_row, field, github_retry_gesture, handled, + is_trigger_label, jira_reopened, jira_retry_gesture, latest_ended_on_merge, latest_run, + own_runs, retry_note, Decision, Item, LatestRun, OpenPr, MAX_FAILED_RUNS_IN_A_ROW, }; use aws_sdk_dynamodb::types::AttributeValue; @@ -1044,6 +1065,66 @@ mod tests { assert!(!n.contains("Title before"), "{n}"); } + /// One alarm on a made-up marina's slip sensors fired four times in a + /// day. Each firing past the alert's repeat window started a new run + /// beside the one already waiting on a person's answer, and each asked + /// the same question again: the gate read every firing as an edited + /// ticket. A firing is the alert opening again, never an edit. + #[test] + fn an_alert_firing_again_while_its_run_waits_starts_nothing() { + let firing = |value: &str, at: &str| { + let msg = serde_json::json!({ + "AlarmName": "harbor-slip-sensor-drift", + "AlarmArn": "arn:aws:cloudwatch:us-east-1:111122223333:alarm:harbor-slip-sensor-drift", + "NewStateValue": "ALARM", + "OldStateValue": "OK", + "NewStateReason": format!( + "Threshold Crossed: 1 datapoint [{value}] was greater than the threshold (500.0)." + ), + "StateChangeTime": at, + "Region": "US East (N. Virginia)", + }); + crate::routes::alerts::normalize(None, &msg.to_string()) + }; + let first = firing("510.0", "2026-11-17T02:29:20.977+0000"); + let again = firing("511.0", "2026-11-17T09:19:20.980+0000"); + assert_eq!(first.fingerprint, again.fingerprint); + // What the run keeps as its ticket's hash: the text the worker reads. + let kept = common::ticket_context_hash( + &first.title, + &crate::routes::alerts::ticket_body("arn:aws:sns:us-east-1:1:harbor", &first, ""), + &[], + ); + let (hash, reopened) = alert_firing(); + for waiting in [ + run("needs_input", 0, "", &kept), + run("needs_outside_change", 0, "", &kept), + run("completed", 0, "", &kept), + run("completed", 7, "", &kept), + ] { + assert!( + matches!(decide(&waiting, hash, reopened), Decision::Skip(_)), + "{} started a second run", + waiting.status + ); + } + // After its fix merged, the alarm firing again is news: the fix didn't hold. + assert_eq!( + decide(&run("merged", 7, "merged", &kept), hash, reopened), + Decision::Enqueue + ); + // A failed run is tried again, up to the cap. + assert_eq!( + decide(&run("failed", 0, "", &kept), hash, reopened), + Decision::Enqueue + ); + let capped = LatestRun { + failed_in_a_row: MAX_FAILED_RUNS_IN_A_ROW, + ..run("failed", 0, "", &kept) + }; + assert!(matches!(decide(&capped, hash, reopened), Decision::Skip(_))); + } + #[test] fn a_handled_ticket_needs_a_content_change_to_run_again() { // The cancelled run whose PR a person closed: a status change on the diff --git a/services/worker/src/passes/incidents/dj_new_run_ends_earlier_waits.rs b/services/worker/src/passes/incidents/dj_new_run_ends_earlier_waits.rs new file mode 100644 index 000000000..702bea651 --- /dev/null +++ b/services/worker/src/passes/incidents/dj_new_run_ends_earlier_waits.rs @@ -0,0 +1,65 @@ +//! dj. A made-up marina's booking ticket waited on a person's answer about +//! which booking page to embed. Ten minutes later an edit to the ticket +//! started a fresh run, which built the page and opened its pull request; +//! the first run went on waiting, reminded once a day, its question long +//! moot. One alarm did the same: each firing started a run beside the one +//! still asking, and two of them were still waiting days after a third had +//! finished the fix. +//! +//! Guarantee: when a fresh run of a ticket takes its claim, every earlier +//! run of that ticket in the same repository still waiting on a person +//! stops waiting: it becomes `retried`, replaced by the new run, and its +//! page says where the work went. A run that ended any other way is left as +//! it is, and a run of the same ticket in another repository is its own. + +use common::one_run; +use common::run_status::{FAILED, NEEDS_INPUT}; + +const ASKED: &str = "01JRUNASKED000000000000000"; +const ASKED_AGAIN: &str = "01JRUNASKEDAGAIN0000000000"; +const FAILED_RUN: &str = "01JRUNFAILED00000000000000"; +const OTHER_REPO: &str = "01JRUNOTHERREPO00000000000"; +const FRESH: &str = "01JRUNFRESH000000000000000"; +const LATER: &str = "01JRUNZLATER00000000000000"; + +fn runs() -> Vec<(String, String, String)> { + let r = |id: &str, status: &str, repo: &str| (id.to_string(), status.to_string(), repo.to_string()); + vec![ + r(ASKED, NEEDS_INPUT, "harbor/booking"), + r(ASKED_AGAIN, NEEDS_INPUT, "Harbor/Booking"), + r(FAILED_RUN, FAILED, "harbor/booking"), + r(OTHER_REPO, NEEDS_INPUT, "harbor/docks"), + r(LATER, NEEDS_INPUT, "harbor/booking"), + ] +} + +#[test] +fn a_fresh_run_ends_the_tickets_earlier_waits() { + let runs = runs(); + let ended = one_run::earlier_waits(FRESH, "harbor/booking", &runs); + assert_eq!(ended, vec![ASKED, ASKED_AGAIN], "both waits on the ticket end"); + // Never itself, never a newer run, never a run in another repository, + // never a run that ended some other way. + assert!(one_run::earlier_waits(ASKED, "harbor/booking", &runs).is_empty()); + let note = one_run::ended_wait_note(FRESH); + assert!(note.contains(FRESH) && note.contains("no longer waits"), "{note}"); +} + +#[test] +fn the_claim_ends_them_once_the_run_holds_the_ticket() { + let src = include_str!("../one_run.rs"); + let claim = &src[src.find("pub async fn claim(").unwrap()..]; + let held = claim + .find("\"The run holds its ticket\"") + .expect("the claim taken"); + let after = &claim[held..]; + assert!( + after[..after.find("return Ok(());").unwrap()].contains("end_earlier_waits(state, msg, run_id)"), + "taking the claim ends the earlier waits" + ); + let f = &src[src.find("async fn end_earlier_waits(").unwrap()..]; + assert!(f.contains("one_run::earlier_waits(")); + // Only while it still waits: an answer or a Retry that came first wins. + assert!(f.contains(".condition_expression(\"#s = :ni\")")); + assert!(f.contains("retried_as = :n")); +} diff --git a/services/worker/src/passes/one_run.rs b/services/worker/src/passes/one_run.rs index 6c4c67957..3ed48f79f 100644 --- a/services/worker/src/passes/one_run.rs +++ b/services/worker/src/passes/one_run.rs @@ -157,6 +157,7 @@ pub async fn claim(state: &WorkerState, msg: &TicketMessage, run_id: &str) -> Re match write(state, &msg.team_id, &sk, run_id, from.as_deref()).await { Ok(true) => { info!(run_id, ticket = %key, "The run holds its ticket"); + end_earlier_waits(state, msg, run_id).await; return Ok(()); } Ok(false) => {} @@ -186,6 +187,74 @@ pub async fn claim(state: &WorkerState, msg: &TicketMessage, run_id: &str) -> Re Ok(()) } +/// The ticket's earlier runs still waiting on a person stop waiting once +/// fresh run `run_id` holds the ticket (`one_run::earlier_waits`): each +/// becomes `retried`, replaced by this run, so one ticket has one current +/// run and no old question goes on being reminded. Only while each still +/// waits; best effort, like the claim. +async fn end_earlier_waits(state: &WorkerState, msg: &TicketMessage, run_id: &str) { + let out = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .index_name("ticket-index") + .key_condition_expression("team_id = :tid AND ticket_id = :ticket") + .projection_expression("run_id, #s, repo") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":tid", s(&msg.team_id)) + .expression_attribute_values(":ticket", s(&msg.ticket_id)) + .send() + .await; + let items = match out { + Ok(o) => o.items.unwrap_or_default(), + Err(e) => { + warn!(run_id, ticket_id = %msg.ticket_id, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Could not read the ticket's earlier runs"); + return; + } + }; + let get = |i: &std::collections::HashMap, k: &str| { + i.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let runs: Vec<(String, String, String)> = items + .iter() + .map(|i| (get(i, "run_id"), get(i, "status"), get(i, "repo"))) + .collect(); + let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + let now = chrono::Utc::now().to_rfc3339(); + for old in one_run::earlier_waits(run_id, &repo, &runs) { + let ended = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", s(&msg.team_id)) + .key("run_id", s(old)) + .update_expression( + "SET #s = :r, status_run_id = :sri, retried_as = :n, updated_at = :t", + ) + .condition_expression("#s = :ni") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":r", s(common::run_status::RETRIED)) + .expression_attribute_values( + ":sri", + s(&format!("{}#{old}", common::run_status::RETRIED)), + ) + .expression_attribute_values(":n", s(run_id)) + .expression_attribute_values(":t", s(&now)) + .expression_attribute_values(":ni", s(common::run_status::NEEDS_INPUT)) + .send() + .await + .is_ok(); + if ended { + info!(run_id, old, ticket_id = %msg.ticket_id, "An earlier waiting run of the ticket no longer waits"); + super::add_progress_note(state, &msg.team_id, old, &one_run::ended_wait_note(run_id)) + .await; + } + } +} + /// The live run that holds the ticket named `key` (seen from `repo`), if any: /// its claim, or for a run that started before claims were kept, a live run /// carrying that ticket id. From 8a00c9c7edfd949da9aa287432b38252df987a92 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 21 Nov 2026 01:39:07 -0500 Subject: [PATCH 5/8] Keep the reopen helper's comment on it; read a registry's history once per check The stacked-base helpers landed between reopen_prior_pr and its doc comment, so the comment described the wrong function. The new-feature check read the same candidate's commit history again for each new item it checked; it is now read once per check. --- services/worker/src/passes/feature/registration.rs | 12 +++++++++--- services/worker/src/passes/pr.rs | 10 +++++----- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/services/worker/src/passes/feature/registration.rs b/services/worker/src/passes/feature/registration.rs index 02d458d0d..02f0069f4 100644 --- a/services/worker/src/passes/feature/registration.rs +++ b/services/worker/src/passes/feature/registration.rs @@ -46,7 +46,7 @@ //! noted in the pull request for a person to check. And a block never stops //! the run: it is an Open item on the pull request (see `feature::gate`). -use std::collections::BTreeSet; +use std::collections::{BTreeSet, HashMap}; use crate::clients::github::GitHubClient; use crate::passes::feature::reuse::name_words; @@ -1061,7 +1061,7 @@ async fn generator_outputs( tree: &[String], ) -> Vec { use crate::passes::generators; - let mut files = std::collections::HashMap::new(); + let mut files = HashMap::new(); for p in generators::candidate_files(tree).into_iter().take(40) { if let Ok(t) = github.read_file(owner, repo, &p, git_ref).await { files.insert(p, t); @@ -1133,6 +1133,8 @@ pub async fn check( let mut checked = 0usize; // The repository's generator outputs, read once when a place is looked for. let mut outputs: Option> = None; + // A place's history is read once per check, however many new items name it. + let mut read_histories: HashMap = HashMap::new(); for item in new_items(added, tree).into_iter().take(6) { let sibs = siblings(&item, tree, recorded_sibling); if sibs.is_empty() { @@ -1225,7 +1227,11 @@ pub async fn check( let mut histories: Vec<(String, History)> = Vec::new(); for (p, _, registry) in &places { if *registry { - histories.push((p.clone(), place_history(github, owner, repo, p).await)); + if !read_histories.contains_key(p) { + let h = place_history(github, owner, repo, p).await; + read_histories.insert(p.clone(), h); + } + histories.push((p.clone(), read_histories[p].clone())); } } let (places, listed) = settle_places(places, &sibs, &|p: &str| { diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 4fe615205..1c0db3acc 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -1000,11 +1000,6 @@ async fn notify_alert_pr( .await; } -/// Reopen the branch's prior closed-unmerged PR, if any. A ticket-update -/// re-run force-resets the branch to base, which makes GitHub auto-close the -/// PR ("all commits removed"); once the fresh implementation has pushed new -/// commits, reopening keeps the PR number and its review history instead of -/// creating a new PR every re-run. Failures fall back to PR creation. /// The base a reused pull request (an open one of this branch, or a /// reopened one) moves to: the branch this run is built on, when that is /// another open pull request's branch of this repository (the run stacked @@ -1068,6 +1063,11 @@ async fn retarget(github: &GitHubClient, msg: &TicketMessage, pr: &serde_json::V } } +/// Reopen the branch's prior closed-unmerged PR, if any. A ticket-update +/// re-run force-resets the branch to base, which makes GitHub auto-close the +/// PR ("all commits removed"); once the fresh implementation has pushed new +/// commits, reopening keeps the PR number and its review history instead of +/// creating a new PR every re-run. Failures fall back to PR creation. async fn reopen_prior_pr( github: &GitHubClient, msg: &TicketMessage, From 31aff5add5b628baa50432a627148a89560d013c Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 21 Nov 2026 01:31:53 -0500 Subject: [PATCH 6/8] Red CI the change didn't cause is named and not fixed in code; fix rounds keep their work - A ci_failed event written without a webhook (a missed webhook, a straggler, a redrive) reads the failing checks from GitHub and carries each workflow's name, run id, conclusion and failing jobs, so the fix round reads the job log, can re-run it and compares it against the base. No failure is described as "Workflow 'unknown' failed (run_id: 0)". - A failure whose log shows a limit of the cloud account (TooMany..., ...LimitExceeded, ...QuotaExceeded, "reached the maximum number of") is not the change's: no fix round or re-run, nothing taken out; the pull request says so and names the repository's cleanup workflow. - Every contents URL percent-encodes each path segment and the ref, so a path like `%5Fmarkdown/[[...slug]]` reads the file it names. - A file GitHub won't give back is not a missing WIP branch: the branch and its work are kept, and the CI fix loop deletes the branch only for a fault that calls for a clean start. - A new CI or review fix round on a head where an unfinished round left checkpoints goes on from that WIP branch instead of resetting it. Incidents: fd_red_ci_not_the_changes, fe_round_work_round_trips. --- docs/incidents/fd_red_ci_not_the_changes.md | 5 + docs/incidents/fe_round_work_round_trips.md | 5 + services/common/src/repo_read.rs | 6 +- services/gateway/src/routes/plans.rs | 17 +- services/gateway/src/routes/tests_setup.rs | 3 +- services/worker/src/clients/github.rs | 26 +- .../incidents/fd_red_ci_not_the_changes.rs | 199 +++++++++ .../incidents/fe_round_work_round_trips.rs | 126 ++++++ services/worker/src/passes/quarantine.rs | 49 ++- services/worker/src/passes/resume.rs | 412 +++++++++++++++--- services/worker/src/passes/round.rs | 47 ++ 11 files changed, 823 insertions(+), 72 deletions(-) create mode 100644 docs/incidents/fd_red_ci_not_the_changes.md create mode 100644 docs/incidents/fe_round_work_round_trips.md create mode 100644 services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs create mode 100644 services/worker/src/passes/incidents/fe_round_work_round_trips.rs diff --git a/docs/incidents/fd_red_ci_not_the_changes.md b/docs/incidents/fd_red_ci_not_the_changes.md new file mode 100644 index 000000000..9e0b05dcc --- /dev/null +++ b/docs/incidents/fd_red_ci_not_the_changes.md @@ -0,0 +1,5 @@ +# fd. `fd_red_ci_not_the_changes` + +**What happened:** A pull request's "E2E on preview" check, a job no workflow webhook reported, was recorded from GitHub's aggregate as an event that named nothing. For eight days every fix round read "Workflow 'unknown' failed (run_id: 0)": no check to compare against the base branch, no job log, nothing to re-run. On another pull request a preview deploy failed on the cloud account's limit (`TooManyUniqueTargetGroupsPerLoadBalancer`); the fix rounds changed nothing, a re-run met the same limit, and the run took its own work out and failed. + +**The guarantee:** An event written without a webhook carries the failing checks read from GitHub, the way a webhook writes them: the workflow's name, its run id, its conclusion and the failing jobs (`resume::synthetic_payloads`). No failure is described as a workflow named "unknown" with run id 0 (`resume::collect_ci_failure_info`). A failure whose log shows a limit of the cloud account (`resume::looks_account_limit`) is not the change's: no fix round or re-run is spent on it, nothing is taken out, and the pull request says so and names the repository's cleanup workflow when it has one. diff --git a/docs/incidents/fe_round_work_round_trips.md b/docs/incidents/fe_round_work_round_trips.md new file mode 100644 index 000000000..7f3a5472f --- /dev/null +++ b/docs/incidents/fe_round_work_round_trips.md @@ -0,0 +1,5 @@ +# fe. `fe_round_work_round_trips` + +**What happened:** A pull request touched a route folder spelled `%5Fmarkdown`. Landing the fix round read that file back through a contents URL built with the path as it is; GitHub decoded `%5F` to `_` and answered 404 for a file that was there. The 404 was read as "its work branch wasn't there, so it had saved nothing", and the branch holding the work was deleted, twice. On two other pull requests a fix round ran out of its time budget three steps in a row; the run page said "Resume continues from there", but the next round reset the WIP branch to the pull request's head and did the same work again (20, then 17, then 4 checkpoint commits thrown away on one run). + +**The guarantee:** Every contents URL percent-encodes each path segment and the ref (`clients::github::contents_url`), so a path holding `%`, `#`, `?`, a space or brackets is the file it names. A file GitHub won't give back is not a missing branch (`round::fault_of`): the WIP branch and its work are kept, and the CI fix loop deletes the branch only for a fault that calls for a clean start. A new CI or review fix round on a head where a round left unfinished work goes on from that WIP branch, told it is continuing (`round::carried`, `round::picks_up`); a head that moved since starts fresh. diff --git a/services/common/src/repo_read.rs b/services/common/src/repo_read.rs index d70e3bf39..8d29dd0f3 100644 --- a/services/common/src/repo_read.rs +++ b/services/common/src/repo_read.rs @@ -147,8 +147,10 @@ pub struct GitHubHost<'a> { pub auth: String, } -/// A path's segments percent-encoded for a URL. -fn path_url(p: &str) -> String { +/// A path's segments percent-encoded for a URL: a file whose name holds +/// `%`, `#`, `?`, a space or brackets is the file GitHub serves, never one +/// it decodes to another name (`%5Fmarkdown` read as `_markdown`). +pub fn path_url(p: &str) -> String { p.split('/') .map(|s| enc(s).replace('+', "%20")) .collect::>() diff --git a/services/gateway/src/routes/plans.rs b/services/gateway/src/routes/plans.rs index 4ac5fc438..ac745c6b5 100644 --- a/services/gateway/src/routes/plans.rs +++ b/services/gateway/src/routes/plans.rs @@ -4113,7 +4113,11 @@ async fn github_read_file( path: &str, branch: &str, ) -> String { - let url = format!("https://api.github.com/repos/{owner}/{name}/contents/{path}?ref={branch}"); + let url = format!( + "https://api.github.com/repos/{owner}/{name}/contents/{}?ref={}", + common::repo_read::path_url(path), + urlencoding::encode(branch) + ); let resp = http .get(&url) .header("Authorization", format!("Bearer {token}")) @@ -4152,9 +4156,16 @@ async fn github_list_directory( branch: &str, ) -> String { let url = if path.is_empty() { - format!("https://api.github.com/repos/{owner}/{name}/contents?ref={branch}") + format!( + "https://api.github.com/repos/{owner}/{name}/contents?ref={}", + urlencoding::encode(branch) + ) } else { - format!("https://api.github.com/repos/{owner}/{name}/contents/{path}?ref={branch}") + format!( + "https://api.github.com/repos/{owner}/{name}/contents/{}?ref={}", + common::repo_read::path_url(path), + urlencoding::encode(branch) + ) }; let resp = http .get(&url) diff --git a/services/gateway/src/routes/tests_setup.rs b/services/gateway/src/routes/tests_setup.rs index f6f3b13af..8cb586b22 100644 --- a/services/gateway/src/routes/tests_setup.rs +++ b/services/gateway/src/routes/tests_setup.rs @@ -139,7 +139,8 @@ impl Gh<'_> { async fn file(&self, repo: &str, path: &str, git_ref: &str) -> Result, String> { let (status, v) = self .get(&format!( - "/repos/{repo}/contents/{path}?ref={}", + "/repos/{repo}/contents/{}?ref={}", + common::repo_read::path_url(path), urlencoding::encode(git_ref) )) .await?; diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index b886d6a8a..d7531ed43 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -11,6 +11,22 @@ use super::repo_snapshot::RepoSnapshot; const API_BASE: &str = "https://api.github.com"; +/// The contents API's URL for `path`, at `git_ref` when one is given. Each +/// segment of the path and the ref are percent-encoded: a repository's file +/// can be named `%5Fmarkdown` (Next.js spells a route folder that starts +/// with `_` that way), and sent as it is GitHub decodes it to `_markdown` +/// and answers 404 for a file that is there. +pub(crate) fn contents_url(owner: &str, repo: &str, path: &str, git_ref: Option<&str>) -> String { + let path = common::repo_read::path_url(path.trim_start_matches('/')); + match git_ref { + Some(r) => format!( + "{API_BASE}/repos/{owner}/{repo}/contents/{path}?ref={}", + common::knowledge::sources::connector::enc(r) + ), + None => format!("{API_BASE}/repos/{owner}/{repo}/contents/{path}"), + } +} + /// Tarballs larger than this are not snapshotted (Lambda memory guard); /// search falls back to the GitHub Code Search API for such repos. const MAX_TARBALL_BYTES: usize = 150 * 1024 * 1024; @@ -1992,7 +2008,7 @@ impl GitHubClient { path: &str, git_ref: &str, ) -> Result> { - let url = format!("{API_BASE}/repos/{owner}/{repo}/contents/{path}?ref={git_ref}"); + let url = contents_url(owner, repo, path, Some(git_ref)); let data = self.get(&url).await?; match contents_body(path, &data)? { ContentsBody::Text(text) => Ok(text), @@ -2014,7 +2030,7 @@ impl GitHubClient { path: &str, git_ref: &str, ) -> Result, Box> { - let url = format!("{API_BASE}/repos/{owner}/{repo}/contents/{path}?ref={git_ref}"); + let url = contents_url(owner, repo, path, Some(git_ref)); match self.get(&url).await { Ok(data) => Ok(Some(data.get("size").and_then(|s| s.as_u64()).unwrap_or(0))), Err(e) if is_not_found(&*e) => Ok(None), @@ -2075,7 +2091,7 @@ impl GitHubClient { path: &str, git_ref: &str, ) -> Result> { - let url = format!("{API_BASE}/repos/{owner}/{repo}/contents/{path}?ref={git_ref}"); + let url = contents_url(owner, repo, path, Some(git_ref)); let data = self.get(&url).await?; data.get("sha") .and_then(|s| s.as_str()) @@ -2270,7 +2286,7 @@ impl GitHubClient { .collect()); } } - let url = format!("{API_BASE}/repos/{owner}/{repo}/contents/{path}?ref={git_ref}"); + let url = contents_url(owner, repo, path, Some(git_ref)); let data = self.get(&url).await?; let entries: Vec = serde_json::from_value(data)?; Ok(entries) @@ -3491,7 +3507,7 @@ impl GitHubClient { }; self.guard_empty_overwrite(owner, repo, path, branch, content) .await?; - let url = format!("{API_BASE}/repos/{owner}/{repo}/contents/{path}"); + let url = contents_url(owner, repo, path, None); let encoded = B64.encode(content.as_bytes()); // FRESHNESS CONTRACT (same as batch_write): if the branch tip moved // past what this pass's snapshot reflects AND this file is among the diff --git a/services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs b/services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs new file mode 100644 index 000000000..8b567c959 --- /dev/null +++ b/services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs @@ -0,0 +1,199 @@ +//! fd. Three pull requests stayed red for days while fix rounds worked on +//! code that wasn't the cause. +//! +//! - A check no workflow webhook reported ("E2E on preview", a job of the +//! preview workflow) was recorded from GitHub's aggregate as an event that +//! named nothing. Every fix round read "Workflow 'unknown' failed (run_id: +//! 0)": no check to compare against the base branch, no job log to read, +//! nothing to re-run. The rounds guessed at code for eight days. +//! - A preview deploy failed with the cloud account's limit +//! (`TooManyUniqueTargetGroupsPerLoadBalancer`). The fix rounds changed +//! nothing, a re-run met the same limit, and the run took its own work +//! out and failed. +//! +//! Guarantee: an event written without a webhook carries the failing checks +//! read from GitHub the way a webhook writes them (the workflow's name, its +//! run id, its conclusion, the failing jobs), and no failure is ever +//! described as a workflow named "unknown" with run id 0. A failure whose +//! log shows a limit of the cloud account is not the change's: no fix round +//! runs for it, nothing is taken out, and the pull request says so and names +//! the repository's cleanup workflow when it has one. + +use serde_json::json; + +use super::fixture::fn_src; +use crate::passes::quarantine; +use crate::passes::resume::{ + account_limit_note, cleanup_workflows, collect_ci_failure_info, looks_account_limit, + looks_infra, synthetic_payloads, RunEvent, +}; + +/// The head's check runs as GitHub lists them: the preview workflow's two +/// jobs (the deploy passed, the end-to-end job failed), an older failed try +/// of the end-to-end job a re-run replaced, and a lint workflow that passed. +fn checks() -> Vec { + vec![ + json!({"name": "Deploy Preview Web App", "status": "completed", "conclusion": "success", + "started_at": "2026-11-18T11:00:00Z", + "details_url": "https://github.com/acme/site/actions/runs/9100/job/1"}), + json!({"name": "E2E on preview", "status": "completed", "conclusion": "failure", + "started_at": "2026-11-18T11:05:00Z", + "details_url": "https://github.com/acme/site/actions/runs/9100/job/2"}), + json!({"name": "E2E on preview", "status": "completed", "conclusion": "failure", + "started_at": "2026-11-18T09:05:00Z", + "details_url": "https://github.com/acme/site/actions/runs/9001/job/7"}), + json!({"name": "Web App Lint", "status": "completed", "conclusion": "success", + "started_at": "2026-11-18T11:00:00Z", + "details_url": "https://github.com/acme/site/actions/runs/9101/job/3"}), + ] +} + +fn event(payload: serde_json::Value) -> RunEvent { + RunEvent { + sk: "EVENT#20261118T111038.439Z#ci_failed".into(), + event_type: "ci_failed".into(), + payload, + } +} + +#[test] +fn an_event_written_without_a_webhook_names_the_failing_check() { + let failed = quarantine::failed_checks(&checks()); + assert_eq!(failed.len(), 1, "{failed:?}"); + assert_eq!(failed[0].name, "E2E on preview"); + assert_eq!(failed[0].workflow_run_id, Some(9100)); + + let payloads = synthetic_payloads( + "7431ad7a11799811566ff89840fd7fc02067178c", + &[(failed[0].clone(), Some("Deploy Preview".to_string()))], + ); + assert_eq!(payloads.len(), 1); + let p = &payloads[0]; + // The shape the webhook writes, so the fix round reads its job log, + // can re-run it, and compares it against the base branch. + assert_eq!(p["workflow_name"], "Deploy Preview"); + assert_eq!(p["workflow_run_id"], 9100); + assert_eq!(p["conclusion"], "failure"); + assert_eq!(p["head_sha"], "7431ad7a11799811566ff89840fd7fc02067178c"); + + let line = collect_ci_failure_info(&[event(p.clone())]); + assert!(line.contains("Deploy Preview") && line.contains("9100"), "{line}"); + assert!(line.contains("E2E on preview"), "{line}"); +} + +#[test] +fn a_failure_is_never_a_workflow_named_unknown() { + // What the run's events held: the head alone. + for payload in [ + json!({"head_sha": "5efa2aa1e7062091fcdf77868caedbf9b4562a9d"}), + json!({"head_sha": ""}), + json!({}), + ] { + let line = collect_ci_failure_info(&[event(payload)]); + assert!(!line.contains("'unknown'"), "{line}"); + assert!(!line.contains("run_id: 0"), "{line}"); + assert!(line.contains("A check failed"), "{line}"); + } + // A check from outside GitHub Actions is named as a check. + let other = quarantine::FailedCheck { + name: "Vendor deploy".into(), + workflow_run_id: None, + conclusion: "failure".into(), + }; + let p = synthetic_payloads("abc", &[(other, None)]); + let line = collect_ci_failure_info(&[event(p[0].clone())]); + assert!(line.contains("Check 'Vendor deploy' failed"), "{line}"); + // No check could be read: one event that names the head. + let none = synthetic_payloads("abcdef1234", &[]); + assert_eq!(none.len(), 1); + assert_eq!(none[0]["head_sha"], "abcdef1234"); +} + +#[test] +fn every_synthetic_event_reads_the_failing_checks_from_github() { + let src = include_str!("../resume.rs"); + let rec = fn_src(src, "async fn record_synthetic_ci_failed("); + assert!(rec.contains("failing_now("), "{rec}"); + assert!(rec.contains("synthetic_payloads("), "{rec}"); + // Every caller hands it the pull request's repository and branch. + let calls: Vec = src + .match_indices("record_synthetic_ci_failed(\n") + .map(|(i, _)| i) + .filter(|i| !src[..*i].ends_with("async fn ")) + .collect(); + assert!(calls.len() >= 4, "{calls:?}"); + let with_github = calls + .iter() + .filter(|i| { + let i = **i; + let call = &src[i..(i + 600).min(src.len())]; + let end = call.find(".await").unwrap_or(call.len()); + call[..end].contains("Some((&github") || call[..end].contains("github\n") + }) + .count(); + assert_eq!(calls.len(), with_github, "a synthetic event written without its checks"); +} + +/// The deploy step's log, as the run's CI showed it. +const DEPLOY_LOG: &str = "2026-11-16T22:40:11.0Z Creating listener rule for pr-41\n\ +2026-11-16T22:40:12.0Z aws: [ERROR]: An error occurred (TooManyUniqueTargetGroupsPerLoadBalancer) when calling the CreateRule operation: You have reached the maximum number of unique target groups that you can associate with a load balancer of type 'application':\n\ +2026-11-16T22:40:12.1Z ##[error]Process completed with exit code 254."; + +#[test] +fn the_cloud_accounts_limit_is_not_the_changes_failure() { + let line = looks_account_limit(DEPLOY_LOG).expect("an account limit"); + assert!(line.contains("TooManyUniqueTargetGroupsPerLoadBalancer"), "{line}"); + // The infrastructure check that re-runs once never claimed it: a re-run + // meets the same limit. + assert_eq!(looks_infra(DEPLOY_LOG), None); + // Other account limits read the same way; a rate limit and a test's + // own failure don't. + for l in [ + "An error occurred (LimitExceededException) when calling the CreateStack operation", + "ServiceQuotaExceededException: quota for Elastic IPs reached", + "An error occurred (TooManyTargets) when calling the RegisterTargets operation", + ] { + assert!(looks_account_limit(l).is_some(), "{l}"); + } + for l in [ + "An error occurred (TooManyRequestsException): Rate exceeded", + "Error: expect(received).toEqual(expected) // deep equality", + " 2 failed", + ] { + assert_eq!(looks_account_limit(l), None, "{l}"); + } + + let files: Vec = [ + ".github/workflows/deploy-preview.yml", + ".github/workflows/cleanup-previews.yml", + ".github/workflows/lint.yml", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let cleanup = cleanup_workflows(&files); + assert_eq!(cleanup, vec![".github/workflows/cleanup-previews.yml".to_string()]); + let note = account_limit_note(&["Deploy Preview".into()], &line, &cleanup); + assert!(note.contains("not on this change"), "{note}"); + assert!(note.contains("cleanup-previews.yml"), "{note}"); + assert!(note.contains("changed no code"), "{note}"); + assert!(note.contains("took none of this change's work out"), "{note}"); +} + +#[test] +fn no_fix_round_runs_for_the_accounts_limit() { + let src = include_str!("../resume.rs"); + let limit = src + .find("if let Some(line) = looks_account_limit(&logs)") + .expect("the CI fix path reads the account's limit"); + let round = src + .find("let mut ci_round = run_round::Round::start(") + .expect("the CI fix round"); + let rerun = src.find("let rerun = try_rerun_once(").expect("the re-run"); + assert!(limit < rerun && limit < round, "the limit is read after a fix or a re-run started"); + let block = &src[limit..limit + 3000]; + assert!(block.contains("mark_pr_ready("), "{block}"); + assert!(block.contains("\"completed\""), "{block}"); + assert!(block.contains("return Ok(());"), "{block}"); + assert!(!block.contains("implement::run("), "{block}"); +} diff --git a/services/worker/src/passes/incidents/fe_round_work_round_trips.rs b/services/worker/src/passes/incidents/fe_round_work_round_trips.rs new file mode 100644 index 000000000..8e969a1c6 --- /dev/null +++ b/services/worker/src/passes/incidents/fe_round_work_round_trips.rs @@ -0,0 +1,126 @@ +//! fe. Fix rounds lost the work they had done, and ran out of time doing it +//! again. +//! +//! - A pull request touched a route folder Next.js spells `%5Fmarkdown` (a +//! URL segment that starts with `_`). The round's file was read back for +//! landing with the path pasted into the contents URL as it is; GitHub +//! decoded `%5F` to `_`, answered 404 for a file that was there, and the +//! 404 was read as "its work branch wasn't there, so it had saved +//! nothing": the branch holding the work was deleted, twice, and the +//! coder tried `%255F` paths that wrote new files. +//! - A CI fix round and a review fix round each ran out of their time +//! budget three steps in a row (each command a sandbox build of one to +//! two minutes, the checks two to six). The run page said "Resume +//! continues from there", but the next round reset the WIP branch to the +//! pull request's head and did the same work again in the same budget: +//! 20, then 17, then 4 checkpoint commits thrown away on one run. +//! +//! Guarantee: every contents URL percent-encodes each path segment and the +//! ref, so a path holding `%`, `#`, `?`, a space or brackets reads and +//! writes the file it names. A file GitHub won't give back is not a missing +//! branch: the branch and its work are kept. A new round on a head that a +//! round left unfinished work on goes on from that WIP branch, told it is +//! continuing; a head that moved since starts fresh. + +use serde_json::json; + +use super::fixture::fn_src; +use crate::clients::github::contents_url; +use crate::passes::round::{self, fault_of, keeps_work, picks_up, Fault}; + +/// The segments of `url`'s path after `contents/`, decoded the way GitHub +/// decodes them, and its `ref`. +fn served(url: &str) -> (String, Option) { + let u = reqwest::Url::parse(url).expect("a URL"); + let segs: Vec = u + .path_segments() + .expect("segments") + .skip_while(|s| *s != "contents") + .skip(1) + .map(|s| urlencoding::decode(s).expect("utf-8").into_owned()) + .collect(); + let r = u + .query_pairs() + .find(|(k, _)| k == "ref") + .map(|(_, v)| v.into_owned()); + (segs.join("/"), r) +} + +#[test] +fn a_path_with_special_characters_is_the_file_github_serves() { + for path in [ + "apps/web/src/app/%5Fmarkdown/[[...slug]]/route.ts", + "apps/web/src/app/(site)/[venue]/page.tsx", + "docs/notes on #3?.md", + "data/100%.json", + "plain/path.ts", + ] { + for git_ref in ["coderhelm-wip/coderhelm/gh-41-card-block", "main", "a1b2c3d"] { + let url = contents_url("acme", "site", path, Some(git_ref)); + assert_eq!(served(&url), (path.to_string(), Some(git_ref.to_string())), "{url}"); + } + let put = contents_url("acme", "site", path, None); + assert_eq!(served(&put), (path.to_string(), None), "{put}"); + } +} + +#[test] +fn a_file_github_wont_give_back_is_not_a_missing_branch() { + // The run's own error, names invented. + let file_404 = "`apps/web/src/app/%5Fmarkdown/[[...slug]]/route.ts` couldn't be read from the WIP branch (HTTP status client error (404 Not Found) for url (https://api.github.com/repos/acme/site/contents/apps/web/src/app/%5Fmarkdown/[[...slug]]/route.ts?ref=coderhelm-wip/coderhelm/gh-41-card-block))"; + assert_eq!(fault_of(file_404), Fault::Unreadable); + assert!(keeps_work(fault_of(file_404)), "the branch holding the work is kept"); + // A branch that really isn't there still reads as one. + let ref_404 = "HTTP status client error (404 Not Found) for url (https://api.github.com/repos/acme/site/git/ref/heads/coderhelm-wip/coderhelm/gh-41-card-block)"; + assert_eq!(fault_of(ref_404), Fault::WipMissing); +} + +#[test] +fn the_ci_fix_loop_keeps_the_branch_a_fault_left_whole() { + let src = include_str!("../resume.rs"); + let at = src + .find("let fault_plan = super::round::plan_for_fault(") + .expect("the CI fix loop's fault decision"); + let block = &src[at..at + 4000]; + let clean = block.find("let clean = fault_plan.clean").expect("clean is decided"); + let delete = block.find(".delete_branch(").expect("the branch delete"); + assert!(clean < delete, "the WIP branch is deleted before the fault is read"); + assert!(block[clean..delete].contains("if clean"), "{block}"); +} + +#[test] +fn a_new_round_goes_on_from_unfinished_work_on_the_same_head() { + // compare(pr branch...WIP branch): the head plus the round's checkpoints. + let unfinished = json!({"status": "ahead", "ahead_by": 6, "behind_by": 0}); + assert!(picks_up(&unfinished)); + // The head moved since (a person's push, a landed round): fresh. + for c in [ + json!({"status": "diverged", "ahead_by": 6, "behind_by": 1}), + json!({"status": "behind", "ahead_by": 0, "behind_by": 2}), + json!({"status": "identical", "ahead_by": 0, "behind_by": 0}), + json!({"message": "Not Found"}), + ] { + assert!(!picks_up(&c), "{c}"); + } + assert!(round::CONTINUING.contains("already committed on this branch")); + + let src = include_str!("../resume.rs"); + // The CI fix round opens the carried branch, never a reset one. + let ci = fn_src(src, "\npub async fn run("); + let carried = ci + .find("let carried = super::round::carried(") + .expect("the CI round reads the unfinished work"); + let open = ci + .find("super::round::open_wip(&github, &repo_owner, &repo_name, &branch, &carried)") + .expect("the CI round opens the carried branch"); + assert!(carried < open); + assert!(!ci.contains("super::round::open_wip(&github, &repo_owner, &repo_name, &branch, \"\")")); + // The review fix round too: run_fix_round reads a set WIP branch as a + // continuing round. + assert!(ci.contains( + "fix_round.wip_branch =\n super::round::carried(&github, &repo_owner, &repo_name, &branch).await;" + )); + let fix = fn_src(src, "async fn run_fix_round("); + assert!(fix.contains("let continuing = !round.wip_branch.is_empty();")); + assert!(fix.contains("super::round::CONTINUING")); +} diff --git a/services/worker/src/passes/quarantine.rs b/services/worker/src/passes/quarantine.rs index ea9dd0fd1..adef0f71b 100644 --- a/services/worker/src/passes/quarantine.rs +++ b/services/worker/src/passes/quarantine.rs @@ -65,9 +65,40 @@ fn workflow_run_id(check: &Value) -> Option { }) } -/// The failing checks in a `check-runs` listing. Only the newest run of each -/// check name counts, so a failure that a re-run fixed doesn't linger. -pub fn failing_checks(checks: &[Value]) -> Failing { +/// One failing check, as a `check-runs` listing names it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FailedCheck { + /// The check's own name (a job's name for a GitHub Actions check). + pub name: String, + /// The workflow run it belongs to, when it is a GitHub Actions job. + pub workflow_run_id: Option, + pub conclusion: String, +} + +/// The failing checks in a `check-runs` listing, by name, newest run of +/// each name only, in name order. +pub fn failed_checks(checks: &[Value]) -> Vec { + let mut out: Vec = latest_by_name(checks) + .into_values() + .filter(|c| c["status"].as_str() == Some("completed")) + .filter_map(|c| { + let conclusion = c["conclusion"].as_str().unwrap_or(""); + FAILED.contains(&conclusion).then(|| FailedCheck { + name: c["name"].as_str().unwrap_or("check").to_string(), + workflow_run_id: workflow_run_id(c), + conclusion: conclusion.to_string(), + }) + }) + .collect(); + out.sort_by(|a, b| a.name.cmp(&b.name)); + out +} + +/// The conclusions that mean a check failed. +const FAILED: &[&str] = &["failure", "timed_out", "startup_failure", "action_required"]; + +/// The newest run of each check name. +fn latest_by_name(checks: &[Value]) -> HashMap<&str, &Value> { let mut latest: HashMap<&str, &Value> = HashMap::new(); for c in checks { let name = c["name"].as_str().unwrap_or("check"); @@ -80,15 +111,19 @@ pub fn failing_checks(checks: &[Value]) -> Failing { latest.insert(name, c); } } + latest +} + +/// The failing checks in a `check-runs` listing. Only the newest run of each +/// check name counts, so a failure that a re-run fixed doesn't linger. +pub fn failing_checks(checks: &[Value]) -> Failing { + let latest = latest_by_name(checks); let mut out = Failing::default(); for c in latest.values() { if c["status"].as_str() != Some("completed") { continue; } - let failed = matches!( - c["conclusion"].as_str().unwrap_or(""), - "failure" | "timed_out" | "startup_failure" | "action_required" - ); + let failed = FAILED.contains(&c["conclusion"].as_str().unwrap_or("")); if !failed { continue; } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index f3f72c859..7bb89cefd 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -431,40 +431,145 @@ async fn current_branch_head( /// Record a synthetic `ci_failed` event so a follow-up resume routes the run into /// the fix path. Used when GitHub's aggregate says a check failed but no -/// `ci_failed` webhook event is present yet — a missed webhook, or a straggler -/// that failed after a `ci_passed` already landed. The empty payload carries no -/// `workflow_run_id`, so the fix path falls back to check-run annotations for the -/// failure detail (see the log-collection block in the fix path). +/// `ci_failed` webhook event is present yet — a missed webhook, a straggler +/// that failed after a `ci_passed` already landed, a check that no workflow +/// webhook reports, or a round sent back to fixing. The failing checks are +/// read from GitHub now and written the way a webhook writes them (each +/// workflow's name, its run id, its conclusion: [`synthetic_payloads`]), so +/// the fix round names the check, reads its job log, can re-run it and +/// compares it against the base branch. An event that named nothing was +/// described as "Workflow 'unknown' failed (run_id: 0)", and the round +/// started with no check to compare, no log and nothing to re-run. async fn record_synthetic_ci_failed( state: &WorkerState, team_id: &str, run_id: &str, head_sha: Option<&str>, + github: Option<(&GitHubClient, &str, &str, &str)>, ) { + let head = head_sha.unwrap_or(""); + let failing = match github { + Some((gh, owner, repo, branch)) => { + failing_now( + gh, + owner, + repo, + Some(head).filter(|h| !h.is_empty()).unwrap_or(branch), + ) + .await + } + None => Vec::new(), + }; let now = chrono::Utc::now(); - let event_sk = format!("EVENT#{}#ci_failed", now.format("%Y%m%dT%H%M%S%.3fZ")); - let payload = serde_json::json!({ "head_sha": head_sha.unwrap_or("") }); - if let Err(e) = common::run_events::put( - &state.dynamo, - &state.config.events_table_name, - team_id, - run_id, - &event_sk, - ) - .item("event_type", attr_s("ci_failed")) - .item("payload", attr_s(&payload.to_string())) - .item("processed", AttributeValue::Bool(false)) - .item("created_at", attr_s(&now.to_rfc3339())) - // The events table's TTL attribute (infra database-stack). - .item( - "expires_at", - attr_n((now.timestamp() as u64 + 30 * 86400).to_string()), - ) - .send() - .await - { - warn!(run_id, error = %e, "Failed to write synthetic ci_failed event"); + for (i, payload) in synthetic_payloads(head, &failing).iter().enumerate() { + let stamp = now.format("%Y%m%dT%H%M%S%.3fZ"); + let event_sk = if i == 0 { + format!("EVENT#{stamp}#ci_failed") + } else { + format!("EVENT#{stamp}-{i}#ci_failed") + }; + if let Err(e) = common::run_events::put( + &state.dynamo, + &state.config.events_table_name, + team_id, + run_id, + &event_sk, + ) + .item("event_type", attr_s("ci_failed")) + .item("payload", attr_s(&payload.to_string())) + .item("processed", AttributeValue::Bool(false)) + .item("created_at", attr_s(&now.to_rfc3339())) + // The events table's TTL attribute (infra database-stack). + .item( + "expires_at", + attr_n((now.timestamp() as u64 + 30 * 86400).to_string()), + ) + .send() + .await + { + warn!(run_id, error = %e, "Failed to write synthetic ci_failed event"); + } + } +} + +/// The checks failing on `git_ref` now, each with the name of the workflow +/// its run belongs to when GitHub gives it. Empty when the checks can't be +/// read. +async fn failing_now( + github: &GitHubClient, + owner: &str, + repo: &str, + git_ref: &str, +) -> Vec<(quarantine::FailedCheck, Option)> { + let Ok(listing) = github.list_check_runs_for_ref(owner, repo, git_ref).await else { + return Vec::new(); + }; + let checks = listing["check_runs"] + .as_array() + .cloned() + .unwrap_or_default(); + let mut names: std::collections::HashMap> = Default::default(); + let mut out = Vec::new(); + for c in quarantine::failed_checks(&checks) { + let workflow = match c.workflow_run_id { + Some(id) => match names.get(&id) { + Some(n) => n.clone(), + None => { + let n = github + .get_workflow_run(owner, repo, id) + .await + .ok() + .and_then(|r| r["name"].as_str().map(str::to_string)) + .filter(|n| !n.trim().is_empty()); + names.insert(id, n.clone()); + n + } + }, + None => None, + }; + out.push((c, workflow)); + } + out +} + +/// The `ci_failed` payloads for what fails on `head`, one per workflow run +/// (its jobs are one workflow's) and one per failing check outside GitHub +/// Actions, in the shape the webhook writes: `workflow_name` (the +/// workflow's, else the check's own name), `workflow_run_id`, `conclusion`, +/// and `check_names`. When nothing could be read, one payload naming the +/// head alone. +pub(crate) fn synthetic_payloads( + head: &str, + failing: &[(quarantine::FailedCheck, Option)], +) -> Vec { + let mut out: Vec = Vec::new(); + for (c, workflow) in failing { + let same_run = c.workflow_run_id.and_then(|id| { + out.iter_mut() + .find(|p| p["workflow_run_id"].as_u64() == Some(id)) + }); + if let Some(p) = same_run { + if let Some(list) = p["check_names"].as_array_mut() { + list.push(Value::String(c.name.clone())); + } + continue; + } + let mut p = serde_json::json!({ + "head_sha": head, + "workflow_name": workflow.clone().unwrap_or_else(|| c.name.clone()), + "conclusion": c.conclusion, + "check_names": [c.name], + "synthetic": true, + }); + if let Some(id) = c.workflow_run_id { + p["workflow_run_id"] = Value::from(id); + } + out.push(p); + } + if out.is_empty() { + out.push(serde_json::json!({ "head_sha": head, "synthetic": true })); } + out } #[cfg(test)] @@ -582,10 +687,10 @@ fn wall_clock_secs( } #[derive(Debug, Clone)] -struct RunEvent { - sk: String, - event_type: String, - payload: Value, +pub(crate) struct RunEvent { + pub(crate) sk: String, + pub(crate) event_type: String, + pub(crate) payload: Value, } /// Split CI events into (current, stale). A ci_failed/ci_passed event is stale @@ -794,6 +899,83 @@ pub(crate) fn looks_infra(logs: &str) -> Option { }) } +/// The line a failure's logs show when a deploy step hit a limit of the +/// team's cloud account, not anything in the code: AWS answers with an +/// error code `TooMany…` (other than a rate limit's `TooManyRequests…`), +/// `…LimitExceeded…` or `…QuotaExceeded…`, or says "You have reached the +/// maximum number of". A re-run meets the same limit and no code change +/// lifts it: someone frees what holds it (the repository's cleanup +/// workflow, when it has one) or raises the limit. Fix rounds on the code +/// were spent on it, and a run once took its own work out for it. +pub(crate) fn looks_account_limit(logs: &str) -> Option { + logs.lines().find_map(|l| { + let low = l.to_lowercase(); + let code = l.split(|c: char| !c.is_ascii_alphanumeric()).any(|w| { + (w.starts_with("TooMany") + && !w.starts_with("TooManyRequests") + && w.len() > "TooMany".len()) + || (w.contains("LimitExceeded") && !w.contains("Rate")) + || w.contains("QuotaExceeded") + }); + (code + || low.contains("you have reached the maximum number of") + || low.contains("service quota exceeded")) + .then(|| common::truncate_str(l.trim(), 300).to_string()) + }) +} + +/// The repository's workflows that free preview or test resources, by file +/// name (`cleanup-previews.yml`, `teardown.yml`, `prune-stacks.yml`): what +/// a person runs when a deploy hit the account's limit. +pub(crate) fn cleanup_workflows(files: &[String]) -> Vec { + const MARKS: &[&str] = &[ + "cleanup", + "clean-up", + "clean_up", + "teardown", + "tear-down", + "prune", + "destroy", + "reap", + ]; + files + .iter() + .filter(|f| f.ends_with(".yml") || f.ends_with(".yaml")) + .filter(|f| { + let low = f.rsplit('/').next().unwrap_or(f).to_lowercase(); + MARKS.iter().any(|m| low.contains(m)) + }) + .cloned() + .collect() +} + +/// What the pull request and the run page say when a check failed on the +/// cloud account's limit (`line`): not this change's, nothing in the code +/// changed for it, and what frees it. +pub(crate) fn account_limit_note(checks: &[String], line: &str, cleanup: &[String]) -> String { + let which = if checks.is_empty() { + "A check".to_string() + } else { + format!("`{}`", checks.join("`, `")) + }; + let free = + match cleanup { + [] => "Someone with access to the account frees what holds the limit (old preview \ + environments, for one) or raises it, then re-runs the check." + .to_string(), + c => format!( + "The repository's cleanup workflow ({}) frees old preview resources; once it has run \ + (or the limit is raised), re-run the check.", + c.iter().map(|w| format!("`{w}`")).collect::>().join(", ") + ), + }; + format!( + "{which} failed on a limit of the team's cloud account, not on this change: `{line}`. \ + A re-run meets the same limit and no code change lifts it, so CoderHelm changed no code \ + for it and took none of this change's work out. {free}" + ) +} + /// How many fix attempts one CI failure gets, each with fresh evidence and, /// after one that changed nothing, a different approach /// (`CODERHELM_CI_FIX_ATTEMPTS`, 1 to 10, default 3). @@ -1832,6 +2014,7 @@ pub async fn run( &msg.team_id, &msg.run_id, branch_head.as_deref(), + Some((&github, &repo_owner, &repo_name, &branch)), ) .await; send_delayed_resume(state, &msg, 0).await; @@ -2335,8 +2518,61 @@ pub async fn run( // the pull request says so. When GitHub won't let CoderHelm re-run // it, the pull request says that too, and no code changes for a // check with a flaky record. - let infra = looks_infra(&logs); let failing_wf = failing_workflows(&events); + // A deploy step that hit the cloud account's limit: not the change's + // failure, and nothing a re-run or a code change gets past. The pull + // request says so, names what frees it, and moves on with its work + // whole; no fix round is spent on it. + if let Some(line) = looks_account_limit(&logs) { + let workflows: Vec = github + .list_directory(&repo_owner, &repo_name, ".github/workflows", &branch) + .await + .map(|e| e.into_iter().map(|d| d.path).collect()) + .unwrap_or_default(); + let note = account_limit_note(&failing_wf, &line, &cleanup_workflows(&workflows)); + info!(run_id = msg.run_id, checks = ?failing_wf, line = %line, "CI failed on the cloud account's limit — no fix round, the pull request says why"); + super::flaky::note_on_pr(&github, &repo_owner, &repo_name, pr_number, note.clone()) + .await; + super::add_progress_note(state, &msg.team_id, &msg.run_id, ¬e).await; + super::record_ci_outcome( + state, + &msg.team_id, + &msg.run_id, + super::CiOutcome::HandedOff(super::GaveUp::UnrelatedTest), + ) + .await; + super::pr_watch::mark_ci_head( + state, + &msg.team_id, + &msg.run_id, + branch_head.as_deref().unwrap_or_default(), + ) + .await; + mark_events_processed(state, &msg.run_id, &events).await; + mark_pr_ready( + state, + &msg.team_id, + &github, + &repo_owner, + &repo_name, + pr_number, + ) + .await; + complete_run_with_status( + state, + &ticket_msg, + &msg.run_id, + "completed", + &pr_url, + pr_number, + &branch, + &usage, + wall_clock_secs(created_at, &start), + ) + .await?; + return Ok(()); + } + let infra = looks_infra(&logs); let (judgement, touch) = super::flaky::judge( state, &github, @@ -2815,7 +3051,7 @@ pub async fn run( ) }; - let feedback = format!( + let mut feedback = format!( "CI workflow failed on PR #{pr_number} (branch: {branch}). Fix the failures.\n\n\ Rules:\n\ - Only fix what CI is complaining about. Don't refactor or add features.\n\ @@ -2840,6 +3076,13 @@ pub async fn run( Some(h) if !h.is_empty() => h.to_string(), _ => super::round::branch_head(&github, &repo_owner, &repo_name, &branch).await, }; + // A round that didn't finish on this same head left its work on + // the WIP branch: this round goes on from it instead of resetting + // that branch to the head and doing the work again. + let carried = super::round::carried(&github, &repo_owner, &repo_name, &branch).await; + if !carried.is_empty() { + feedback = format!("{feedback}\n\n{}", super::round::CONTINUING); + } let mut ci_round = run_round::Round::start( run_round::Kind::CiFix, (cycle + 1).min(u32::MAX as usize) as u32, @@ -2874,9 +3117,10 @@ pub async fn run( // request gets one commit when it's done. // (Each attempt below makes sure the branch is there before it // writes; one that can't be made here is that attempt's fault.) - ci_round.wip_branch = super::round::open_wip(&github, &repo_owner, &repo_name, &branch, "") - .await - .unwrap_or_default(); + ci_round.wip_branch = + super::round::open_wip(&github, &repo_owner, &repo_name, &branch, &carried) + .await + .unwrap_or_default(); super::round::record(state, &msg.team_id, &msg.run_id, &ci_round).await; // The tree before the fix: compared with the tree after it to tell a @@ -2897,7 +3141,6 @@ pub async fn run( .next() .unwrap_or(&feedback) .to_string(); - let mut feedback = feedback; 'fix: loop { // Every attempt starts with its WIP branch there: an attempt // that changed nothing had it cleaned up when it landed, and the @@ -3312,7 +3555,12 @@ pub async fn run( )); // A clean state for whatever runs next: the WIP branch goes, // and the round starts from the pull request's head as it is. - if !ci_round.wip_branch.is_empty() && ci_round.wip_branch != branch { + // A fault that left the work whole (a file or a compare GitHub + // wouldn't give back, a refused push, GitHub busy) keeps the + // WIP branch and the round's starting point for the next try + // (`round::keeps_work`): deleting it threw the work away. + let clean = fault_plan.clean || next != super::round::AfterFault::RetryClean; + if clean && !ci_round.wip_branch.is_empty() && ci_round.wip_branch != branch { let _ = github .delete_branch(&repo_owner, &repo_name, &ci_round.wip_branch) .await; @@ -3320,9 +3568,15 @@ pub async fn run( match next { super::round::AfterFault::RetryClean => { attempt += 1; - ci_round.base_sha = - super::round::branch_head(&github, &repo_owner, &repo_name, &branch) - .await; + if clean { + ci_round.base_sha = super::round::branch_head( + &github, + &repo_owner, + &repo_name, + &branch, + ) + .await; + } let fresh = ci_evidence( &github, &repo_owner, @@ -3351,6 +3605,7 @@ pub async fn run( &msg.team_id, &msg.run_id, branch_head.as_deref(), + Some((&github, &repo_owner, &repo_name, &branch)), ) .await; if set_run_awaiting_ci( @@ -3549,6 +3804,7 @@ pub async fn run( &msg.team_id, &msg.run_id, branch_head.as_deref(), + Some((&github, &repo_owner, &repo_name, &branch)), ) .await; let still_active = set_run_awaiting_ci( @@ -3939,7 +4195,7 @@ pub async fn run( // never a failed run when it can't finish. let base_sha = super::round::branch_head(&github, &repo_owner, &repo_name, &branch).await; - let fix_round = run_round::Round::start( + let mut fix_round = run_round::Round::start( run_round::Kind::ReviewFix, (cycle + 1).min(u32::MAX as usize) as u32, &base_sha, @@ -3950,6 +4206,11 @@ pub async fn run( review_feedback.is_empty() && !own_scope.unscoped, chrono::Utc::now(), ); + // A round that didn't finish on this same head left its work on + // the WIP branch: this one goes on from it (`run_fix_round` reads + // it as a continuing round), never from a reset one. + fix_round.wip_branch = + super::round::carried(&github, &repo_owner, &repo_name, &branch).await; let mut ctx = FixContext { ticket_msg, provider, @@ -4383,12 +4644,7 @@ async fn run_fix_round( super::round::record(state, &msg.team_id, &msg.run_id, &round).await; super::update_pass(state, &msg.team_id, &msg.run_id, "implement").await?; let feedback = if round.attempt > 1 || continuing { - format!( - "{}\n\n## CONTINUING THIS ROUND\nAn earlier step of this round stopped before it \ - finished; everything it wrote is already committed on this branch. Read the files you \ - need first, then finish only what is left.", - round.feedback - ) + format!("{}\n\n{}", round.feedback, super::round::CONTINUING) } else { round.feedback.clone() }; @@ -5730,16 +5986,47 @@ async fn mark_events_processed(state: &WorkerState, run_id: &str, events: &[RunE } } -fn collect_ci_failure_info(events: &[RunEvent]) -> String { +/// One line per failed check the events name: the workflow, its run id and +/// the jobs that failed when they are known. An event that names no check +/// says what is known (the commit) instead of "Workflow 'unknown' failed +/// (run_id: 0)", which read as a workflow of that name. +pub(crate) fn collect_ci_failure_info(events: &[RunEvent]) -> String { events .iter() .filter(|e| e.event_type == "ci_failed") .map(|e| { - format!( - "Workflow '{}' failed (run_id: {})", - e.payload["workflow_name"].as_str().unwrap_or("unknown"), - e.payload["workflow_run_id"].as_u64().unwrap_or(0), - ) + let p = &e.payload; + let name = p["workflow_name"].as_str().filter(|n| !n.trim().is_empty()); + let run = p["workflow_run_id"].as_u64().filter(|id| *id > 0); + let jobs: Vec<&str> = p["check_names"] + .as_array() + .map(|a| { + a.iter() + .filter_map(Value::as_str) + .filter(|j| Some(*j) != name) + .collect() + }) + .unwrap_or_default(); + let jobs = if jobs.is_empty() { + String::new() + } else { + format!(", failing: {}", jobs.join(", ")) + }; + match (name, run) { + (Some(n), Some(id)) => format!("Workflow '{n}' failed (run_id: {id}{jobs})"), + (Some(n), None) => format!("Check '{n}' failed (not a GitHub Actions run{jobs})"), + _ => { + let head = p["head_sha"].as_str().unwrap_or(""); + let at = if head.is_empty() { + String::new() + } else { + format!(" on {}", &head[..head.len().min(7)]) + }; + format!( + "A check failed{at}; GitHub's checks didn't say which when it was recorded" + ) + } + } }) .collect::>() .join("\n") @@ -8130,7 +8417,24 @@ async fn redrive_red_ci( return Ok(false); } add_run_number(state, &msg.team_id, run_id, "red_redrives").await; - record_synthetic_ci_failed(state, &msg.team_id, run_id, None).await; + // The checks that are red now, by name, so the round reads them. + let github = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + msg.installation_id, + &state.http, + ) + .ok(); + record_synthetic_ci_failed( + state, + &msg.team_id, + run_id, + None, + github + .as_ref() + .map(|g| (g, msg.repo_owner.as_str(), msg.repo_name.as_str(), branch)), + ) + .await; if !set_run_awaiting_ci( state, msg, run_id, pr_url, pr_number, branch, usage, duration, ) diff --git a/services/worker/src/passes/round.rs b/services/worker/src/passes/round.rs index 59e0259f2..814a03875 100644 --- a/services/worker/src/passes/round.rs +++ b/services/worker/src/passes/round.rs @@ -350,6 +350,48 @@ pub(crate) async fn end_unfinished( true } +/// Whether a leftover WIP branch is unlanded work on the pull request's +/// head as it is now: from a compare of the pull request's branch with it, +/// the WIP branch is that head plus commits, none missing. A round that +/// ran out of its time budget leaves exactly that ("Resume continues from +/// there"); a new round that reset the branch to the head threw those +/// checkpoints away and did the same work again in the same budget. +pub(crate) fn picks_up(compare: &serde_json::Value) -> bool { + compare["behind_by"].as_u64() == Some(0) + && compare["ahead_by"].as_u64().unwrap_or(0) > 0 + && compare["status"].as_str() == Some("ahead") +} + +/// The WIP branch a new round on `pr_branch` goes on from, when one is +/// left there with unlanded work on the head ([`picks_up`]); "" for a +/// fresh one. A head that moved since (a person's push, a landed round) +/// starts fresh: that work was written on an older head. +pub(crate) async fn carried( + github: &GitHubClient, + owner: &str, + repo: &str, + pr_branch: &str, +) -> String { + let wip = run_round::wip_branch(pr_branch); + match github.get_diff(owner, repo, pr_branch, &wip).await { + Ok(c) if picks_up(&c) => { + info!( + wip, + ahead = c["ahead_by"].as_u64().unwrap_or(0), + "Going on from the unfinished round's WIP branch" + ); + wip + } + _ => String::new(), + } +} + +/// What a round that picks up an earlier one's work is told first. +pub(crate) const CONTINUING: &str = + "## CONTINUING THIS ROUND\nAn earlier step of this round stopped before it \ + finished; everything it wrote is already committed on this branch. Read the files you \ + need first, then finish only what is left."; + /// The round's WIP branch, ready to write to: the one it already has when /// it continues (`reuse`), else a fresh one at the pull request's head. /// Returns its name. @@ -449,6 +491,11 @@ pub(crate) fn fault_of(error: &str) -> Fault { let has = |needles: &[&str]| needles.iter().any(|n| e.contains(n)); if has(&["changed the same files meanwhile"]) { Fault::Clash + } else if has(&["/contents/", "couldn't be read from the wip branch"]) { + // One file of the round's that GitHub wouldn't give back: the + // branch is there and holds the work, so it is kept and read again, + // never deleted as a branch that "saved nothing". + Fault::Unreadable } else if has(&["no wip branch"]) || (e.contains("404") && has(&["coderhelm-wip/", "wip branch", "/git/ref"])) { From ebac093c2e48fcda3aa22ca946d98d0d583ebf6f Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 21 Nov 2026 01:58:22 -0500 Subject: [PATCH 7/8] Only the cloud's own error codes read as an account limit A browser's QuotaExceededError or a client's TooManyRedirects thrown by the code under test is the change's failure. Reading those words anywhere in a log as the account's limit would have marked a pull request ready with its bug in it. Only the code in an AWS CLI 'An error occurred (Code)' line, or an SDK's ...Exception, counts. --- .../incidents/fd_red_ci_not_the_changes.rs | 4 ++++ services/worker/src/passes/resume.rs | 16 ++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs b/services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs index 8b567c959..8d524c7f0 100644 --- a/services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs +++ b/services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs @@ -159,6 +159,10 @@ fn the_cloud_accounts_limit_is_not_the_changes_failure() { "An error occurred (TooManyRequestsException): Rate exceeded", "Error: expect(received).toEqual(expected) // deep equality", " 2 failed", + // The code under test throwing the same words is the change's own. + "DOMException: QuotaExceededError: the quota has been exceeded (localStorage)", + "FetchError: TooManyRedirects: maximum redirect reached at /account", + "TooManyBookingsError: the slip already has a booking", ] { assert_eq!(looks_account_limit(l), None, "{l}"); } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 7bb89cefd..34bb6faca 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -910,13 +910,25 @@ pub(crate) fn looks_infra(logs: &str) -> Option { pub(crate) fn looks_account_limit(logs: &str) -> Option { logs.lines().find_map(|l| { let low = l.to_lowercase(); - let code = l.split(|c: char| !c.is_ascii_alphanumeric()).any(|w| { + // Only the cloud's own error codes count: the one in "An error + // occurred (Code) when calling ...", or an SDK's `...Exception`. The + // same words thrown by the code under test (a browser's + // `QuotaExceededError`, a client's `TooManyRedirects`) are the + // change's failures, never the account's. + let cli_code = low.find("an error occurred (").and_then(|i| { + let rest = &l[i + "an error occurred (".len()..]; + rest.split(')').next() + }); + let limit = |w: &str| { (w.starts_with("TooMany") && !w.starts_with("TooManyRequests") && w.len() > "TooMany".len()) || (w.contains("LimitExceeded") && !w.contains("Rate")) || w.contains("QuotaExceeded") - }); + }; + let code = cli_code.is_some_and(limit) + || l.split(|c: char| !c.is_ascii_alphanumeric()) + .any(|w| w.ends_with("Exception") && limit(w)); (code || low.contains("you have reached the maximum number of") || low.contains("service quota exceeded")) From 536245740c2b274a13191df0fb807e5f206d0302 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 21 Nov 2026 13:54:48 -0500 Subject: [PATCH 8/8] Format the new incident cases as CI checks them --- .../dj_new_run_ends_earlier_waits.rs | 17 +++++++--- .../incidents/dq_unfinished_stop_ships.rs | 5 ++- .../fa_stacked_pr_targets_its_base.rs | 23 +++++++++++--- .../incidents/fd_red_ci_not_the_changes.rs | 31 +++++++++++++++---- .../incidents/fe_round_work_round_trips.rs | 26 +++++++++++++--- 5 files changed, 81 insertions(+), 21 deletions(-) diff --git a/services/worker/src/passes/incidents/dj_new_run_ends_earlier_waits.rs b/services/worker/src/passes/incidents/dj_new_run_ends_earlier_waits.rs index 702bea651..cb4a41c3a 100644 --- a/services/worker/src/passes/incidents/dj_new_run_ends_earlier_waits.rs +++ b/services/worker/src/passes/incidents/dj_new_run_ends_earlier_waits.rs @@ -23,7 +23,8 @@ const FRESH: &str = "01JRUNFRESH000000000000000"; const LATER: &str = "01JRUNZLATER00000000000000"; fn runs() -> Vec<(String, String, String)> { - let r = |id: &str, status: &str, repo: &str| (id.to_string(), status.to_string(), repo.to_string()); + let r = + |id: &str, status: &str, repo: &str| (id.to_string(), status.to_string(), repo.to_string()); vec![ r(ASKED, NEEDS_INPUT, "harbor/booking"), r(ASKED_AGAIN, NEEDS_INPUT, "Harbor/Booking"), @@ -37,12 +38,19 @@ fn runs() -> Vec<(String, String, String)> { fn a_fresh_run_ends_the_tickets_earlier_waits() { let runs = runs(); let ended = one_run::earlier_waits(FRESH, "harbor/booking", &runs); - assert_eq!(ended, vec![ASKED, ASKED_AGAIN], "both waits on the ticket end"); + assert_eq!( + ended, + vec![ASKED, ASKED_AGAIN], + "both waits on the ticket end" + ); // Never itself, never a newer run, never a run in another repository, // never a run that ended some other way. assert!(one_run::earlier_waits(ASKED, "harbor/booking", &runs).is_empty()); let note = one_run::ended_wait_note(FRESH); - assert!(note.contains(FRESH) && note.contains("no longer waits"), "{note}"); + assert!( + note.contains(FRESH) && note.contains("no longer waits"), + "{note}" + ); } #[test] @@ -54,7 +62,8 @@ fn the_claim_ends_them_once_the_run_holds_the_ticket() { .expect("the claim taken"); let after = &claim[held..]; assert!( - after[..after.find("return Ok(());").unwrap()].contains("end_earlier_waits(state, msg, run_id)"), + after[..after.find("return Ok(());").unwrap()] + .contains("end_earlier_waits(state, msg, run_id)"), "taking the claim ends the earlier waits" ); let f = &src[src.find("async fn end_earlier_waits(").unwrap()..]; diff --git a/services/worker/src/passes/incidents/dq_unfinished_stop_ships.rs b/services/worker/src/passes/incidents/dq_unfinished_stop_ships.rs index eb9b200d4..0a407ac6f 100644 --- a/services/worker/src/passes/incidents/dq_unfinished_stop_ships.rs +++ b/services/worker/src/passes/incidents/dq_unfinished_stop_ships.rs @@ -82,7 +82,10 @@ fn a_stuck_task_changes_approach_before_the_guard_stops_the_run() { Rung::Escalate, Rung::Defer, ] { - assert!(rungs.contains(&r), "the ladder never reached {r:?}: {rungs:?}"); + assert!( + rungs.contains(&r), + "the ladder never reached {r:?}: {rungs:?}" + ); } // Never the same ask twice in a row after a step that changed nothing. for w in rungs.windows(2) { diff --git a/services/worker/src/passes/incidents/fa_stacked_pr_targets_its_base.rs b/services/worker/src/passes/incidents/fa_stacked_pr_targets_its_base.rs index 210258bc4..92d1b3a84 100644 --- a/services/worker/src/passes/incidents/fa_stacked_pr_targets_its_base.rs +++ b/services/worker/src/passes/incidents/fa_stacked_pr_targets_its_base.rs @@ -100,9 +100,15 @@ fn a_branch_built_on_the_other_pull_request_is_stacked_without_a_rebuild() { let shared = stack::shared(&matched, &their); assert_eq!(shared, matched); let c = copy(&["a1a1a1a", "b2b2b2b"], &["a1a1a1a", "b2b2b2b"]); - assert!(stack::built_on(&c), "the other pull request's own commits read as copies"); + assert!( + stack::built_on(&c), + "the other pull request's own commits read as copies" + ); let why = stack::built_on_why(&c); - assert!(why.contains("built on #40's branch `coderhelm/harbor-40`"), "{why}"); + assert!( + why.contains("built on #40's branch `coderhelm/harbor-40`"), + "{why}" + ); assert!(!why.contains("under other hashes")); assert!(!why.contains("re-created")); // The kept branch of the incident: same changes under new hashes. These @@ -119,7 +125,9 @@ fn a_branch_built_on_the_other_pull_request_is_stacked_without_a_rebuild() { fn the_pipeline_moves_reused_pull_requests_and_skips_needless_rebuilds() { let pr = include_str!("../pr.rs"); let run = fn_src(pr, "pub async fn run("); - let reused = run.find("\"Using existing PR\"").expect("the existing pull request path"); + let reused = run + .find("\"Using existing PR\"") + .expect("the existing pull request path"); let reopened = run .find("\"Reopened prior PR for branch\"") .expect("the reopened pull request path"); @@ -132,8 +140,13 @@ fn the_pipeline_moves_reused_pull_requests_and_skips_needless_rebuilds() { let stack_src = include_str!("../stack.rs"); for head in ["pub async fn at_start(", "pub async fn before_pr("] { let f = fn_src(stack_src, head); - let check = f.find("built_on(&c)").unwrap_or_else(|| panic!("{head} rebuilds a stacked branch")); + let check = f + .find("built_on(&c)") + .unwrap_or_else(|| panic!("{head} rebuilds a stacked branch")); let rebuild = f.find("rebuild_on(").unwrap(); - assert!(check < rebuild, "{head} rebuilds before it asks whether the branch is built on it"); + assert!( + check < rebuild, + "{head} rebuilds before it asks whether the branch is built on it" + ); } } diff --git a/services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs b/services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs index 8d524c7f0..ced730b65 100644 --- a/services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs +++ b/services/worker/src/passes/incidents/fd_red_ci_not_the_changes.rs @@ -77,7 +77,10 @@ fn an_event_written_without_a_webhook_names_the_failing_check() { assert_eq!(p["head_sha"], "7431ad7a11799811566ff89840fd7fc02067178c"); let line = collect_ci_failure_info(&[event(p.clone())]); - assert!(line.contains("Deploy Preview") && line.contains("9100"), "{line}"); + assert!( + line.contains("Deploy Preview") && line.contains("9100"), + "{line}" + ); assert!(line.contains("E2E on preview"), "{line}"); } @@ -131,7 +134,11 @@ fn every_synthetic_event_reads_the_failing_checks_from_github() { call[..end].contains("Some((&github") || call[..end].contains("github\n") }) .count(); - assert_eq!(calls.len(), with_github, "a synthetic event written without its checks"); + assert_eq!( + calls.len(), + with_github, + "a synthetic event written without its checks" + ); } /// The deploy step's log, as the run's CI showed it. @@ -142,7 +149,10 @@ const DEPLOY_LOG: &str = "2026-11-16T22:40:11.0Z Creating listener rule for pr-4 #[test] fn the_cloud_accounts_limit_is_not_the_changes_failure() { let line = looks_account_limit(DEPLOY_LOG).expect("an account limit"); - assert!(line.contains("TooManyUniqueTargetGroupsPerLoadBalancer"), "{line}"); + assert!( + line.contains("TooManyUniqueTargetGroupsPerLoadBalancer"), + "{line}" + ); // The infrastructure check that re-runs once never claimed it: a re-run // meets the same limit. assert_eq!(looks_infra(DEPLOY_LOG), None); @@ -176,12 +186,18 @@ fn the_cloud_accounts_limit_is_not_the_changes_failure() { .map(|s| s.to_string()) .collect(); let cleanup = cleanup_workflows(&files); - assert_eq!(cleanup, vec![".github/workflows/cleanup-previews.yml".to_string()]); + assert_eq!( + cleanup, + vec![".github/workflows/cleanup-previews.yml".to_string()] + ); let note = account_limit_note(&["Deploy Preview".into()], &line, &cleanup); assert!(note.contains("not on this change"), "{note}"); assert!(note.contains("cleanup-previews.yml"), "{note}"); assert!(note.contains("changed no code"), "{note}"); - assert!(note.contains("took none of this change's work out"), "{note}"); + assert!( + note.contains("took none of this change's work out"), + "{note}" + ); } #[test] @@ -194,7 +210,10 @@ fn no_fix_round_runs_for_the_accounts_limit() { .find("let mut ci_round = run_round::Round::start(") .expect("the CI fix round"); let rerun = src.find("let rerun = try_rerun_once(").expect("the re-run"); - assert!(limit < rerun && limit < round, "the limit is read after a fix or a re-run started"); + assert!( + limit < rerun && limit < round, + "the limit is read after a fix or a re-run started" + ); let block = &src[limit..limit + 3000]; assert!(block.contains("mark_pr_ready("), "{block}"); assert!(block.contains("\"completed\""), "{block}"); diff --git a/services/worker/src/passes/incidents/fe_round_work_round_trips.rs b/services/worker/src/passes/incidents/fe_round_work_round_trips.rs index 8e969a1c6..8bb4b1712 100644 --- a/services/worker/src/passes/incidents/fe_round_work_round_trips.rs +++ b/services/worker/src/passes/incidents/fe_round_work_round_trips.rs @@ -55,9 +55,17 @@ fn a_path_with_special_characters_is_the_file_github_serves() { "data/100%.json", "plain/path.ts", ] { - for git_ref in ["coderhelm-wip/coderhelm/gh-41-card-block", "main", "a1b2c3d"] { + for git_ref in [ + "coderhelm-wip/coderhelm/gh-41-card-block", + "main", + "a1b2c3d", + ] { let url = contents_url("acme", "site", path, Some(git_ref)); - assert_eq!(served(&url), (path.to_string(), Some(git_ref.to_string())), "{url}"); + assert_eq!( + served(&url), + (path.to_string(), Some(git_ref.to_string())), + "{url}" + ); } let put = contents_url("acme", "site", path, None); assert_eq!(served(&put), (path.to_string(), None), "{put}"); @@ -69,7 +77,10 @@ fn a_file_github_wont_give_back_is_not_a_missing_branch() { // The run's own error, names invented. let file_404 = "`apps/web/src/app/%5Fmarkdown/[[...slug]]/route.ts` couldn't be read from the WIP branch (HTTP status client error (404 Not Found) for url (https://api.github.com/repos/acme/site/contents/apps/web/src/app/%5Fmarkdown/[[...slug]]/route.ts?ref=coderhelm-wip/coderhelm/gh-41-card-block))"; assert_eq!(fault_of(file_404), Fault::Unreadable); - assert!(keeps_work(fault_of(file_404)), "the branch holding the work is kept"); + assert!( + keeps_work(fault_of(file_404)), + "the branch holding the work is kept" + ); // A branch that really isn't there still reads as one. let ref_404 = "HTTP status client error (404 Not Found) for url (https://api.github.com/repos/acme/site/git/ref/heads/coderhelm-wip/coderhelm/gh-41-card-block)"; assert_eq!(fault_of(ref_404), Fault::WipMissing); @@ -82,9 +93,14 @@ fn the_ci_fix_loop_keeps_the_branch_a_fault_left_whole() { .find("let fault_plan = super::round::plan_for_fault(") .expect("the CI fix loop's fault decision"); let block = &src[at..at + 4000]; - let clean = block.find("let clean = fault_plan.clean").expect("clean is decided"); + let clean = block + .find("let clean = fault_plan.clean") + .expect("clean is decided"); let delete = block.find(".delete_branch(").expect("the branch delete"); - assert!(clean < delete, "the WIP branch is deleted before the fault is read"); + assert!( + clean < delete, + "the WIP branch is deleted before the fault is read" + ); assert!(block[clean..delete].contains("if clean"), "{block}"); }