diff --git a/docs/incidents/xn_stacked_merge_reaches_main.md b/docs/incidents/xn_stacked_merge_reaches_main.md new file mode 100644 index 000000000..2502e7cee --- /dev/null +++ b/docs/incidents/xn_stacked_merge_reaches_main.md @@ -0,0 +1,9 @@ +# xn. `xn_stacked_merge_reaches_main` + +**What happened:** Pull request B was stacked on pull request A, so B's base was A's branch. CoderHelm's merge gate squash-merged A into `main`. A's branch stayed, so GitHub never moved B to `main`. The gate then merged B into A's branch, which nothing read any more. B said "merged", and none of its change reached `main`. + +**Why:** GitHub moves a stacked pull request to the merged pull request's base only when the merged branch is deleted. CoderHelm never deleted that branch after its merge, and never moved the stacked pull requests itself. The merge gate merged into whatever base a pull request named, without checking whether that base was the branch of a pull request that had already merged. + +**The guarantee:** When a pull request merges, the open pull requests based on its branch move to its base. This happens for CoderHelm's own pull requests always, and for a person's where the repository's `retarget_stacked` setting is on. The new base is merged into each moved pull request with GitHub's merge, which is a signed commit. A conflict goes to the merge gate's own conflict path. Each moved pull request is reviewed again on its new base. CoderHelm's merged branch is deleted once nothing is based on it. The merge gate never merges into a base that is not the default branch (or the configured release branch) when that base is the head of a pull request that already merged and nothing reads it any more. It moves the pull request first, and waits for the review there. Where that merged pull request was a person's and `retarget_stacked` is off, the gate holds the pull request for a person to move instead of moving it. A branch is still read, and never treated as merged, while an open pull request comes from it, while it is protected, or once it was the head of more than one merged pull request, as a long-lived `develop` is. A merge from a branch still read moves nothing based on it. On the pull request watch sweep, open pull requests still based on such a branch are moved. A pull request CoderHelm merged into such a branch in the last 30 days gets one "Land #N on main" pull request, which picks its change onto the branch it belonged on. Nothing is opened when that branch already holds the change. Each landing is claimed once. When picking the change or opening the pull request fails, the claim is given back, a landing branch left without a pull request is deleted, and the next sweep tries again. A sweep opens at most three per repository. + +**Where it's enforced:** `dead_base::{on_merged, gate, sweep_repo, lost, live_base, dead_branches, carried_on, may_act_on, may_retarget, may_delete, GhRepo, after_merge, sweep}`. `await_merge::{evaluate, gated_repos}`. `pr_watch::sweep`. `github_webhook::stack_merged_message` and the `stack_merged` worker message. `GitHubClient::closed_pulls_from`. `OnApproveConfig::retarget_stacked` and `review_config`. diff --git a/services/common/contract/worker_messages.json b/services/common/contract/worker_messages.json index 39946baf3..cf2dceb2e 100644 --- a/services/common/contract/worker_messages.json +++ b/services/common/contract/worker_messages.json @@ -21,6 +21,7 @@ "graph_index": {"type":"graph_index","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","branch":"main","changed_files":["a.rs"]}, "release_notes": {"type":"release_notes","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","tag":"v1.0.0","sha":"abc","resend":"","check_branch":true}, "restack": {"type":"restack","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","branch":"coderhelm/feature-a","before":"abc","after":"def"}, + "stack_merged": {"type":"stack_merged","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","pr_number":2}, "tag_sweep": {"type":"tag_sweep","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","base_branch":"main","pr_number":2,"delay_remaining_secs":0,"sweep_id":"s","manual":true,"claimed":false,"attempt":0}, "test_ingest": {"type":"test_ingest","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","repo_id":9,"default_branch":"main","workflow":"e2e","workflow_path":".github/workflows/e2e.yml","run_id":10,"run_attempt":1,"head_sha":"abc","head_branch":"main","event":"push","pr_numbers":[2],"conclusion":"success","html_url":"https://example.test/run/10","started_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:10:00Z","upload_key":null}, "test_action": {"type":"test_action","team_id":"TEAM#team-a","repo":"acme/widgets","action":"fix","target_id":"t1","actor":"someone"}, diff --git a/services/common/src/dlq.rs b/services/common/src/dlq.rs index 162d076f2..d8fd9907d 100644 --- a/services/common/src/dlq.rs +++ b/services/common/src/dlq.rs @@ -53,6 +53,8 @@ pub const WORKER_MESSAGE_TYPES: &[&str] = &[ "tag_sweep", // A force push: the pull requests stacked on that branch are rebuilt. "restack", + // A merged pull request: the ones stacked on its branch move to its base. + "stack_merged", "release_notes", "graph_index", "app_map", diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 5623a22e0..032a1bad1 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -120,6 +120,11 @@ pub enum WorkerMessage { /// a time (`worker::passes::restack`). #[serde(rename = "restack")] Restack(RestackMessage), + /// A pull request merged: the open pull requests based on its branch + /// move to its base, and the branch goes when it is CoderHelm's + /// (`worker::passes::dead_base`). + #[serde(rename = "stack_merged")] + StackMerged(StackMergedMessage), /// Release notes for a release tag CoderHelm just cut (or a re-send from the /// dashboard): GitHub Release + Confluence changelog entry + IT email. #[serde(rename = "release_notes")] @@ -513,6 +518,7 @@ impl WorkerMessage { | WorkerMessage::RunWaiting(_) | WorkerMessage::RoleReadsWait(_) | WorkerMessage::ChangeWaitCheck(_) + | WorkerMessage::StackMerged(_) | WorkerMessage::LogAutofix | WorkerMessage::AwsPermissionsSweep | WorkerMessage::HybridNameCheck @@ -595,6 +601,7 @@ impl WorkerMessage { | WorkerMessage::RunWaiting(_) | WorkerMessage::RoleReadsWait(_) | WorkerMessage::ChangeWaitCheck(_) + | WorkerMessage::StackMerged(_) | WorkerMessage::PluginRun(_) | WorkerMessage::PluginPublish(_) | WorkerMessage::PluginSync(_) @@ -1173,6 +1180,16 @@ fn is_zero_u64(n: &u64) -> bool { *n == 0 } +/// A pull request that merged, read again by the worker. +#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq)] +pub struct StackMergedMessage { + pub team_id: String, + pub installation_id: u64, + pub repo_owner: String, + pub repo_name: String, + pub pr_number: u64, +} + /// A force push to `branch` (from `before` to `after`). #[derive(Serialize, Deserialize, Debug, Default, Clone)] pub struct RestackMessage { diff --git a/services/common/src/review_config.rs b/services/common/src/review_config.rs index 27479a092..ab4802573 100644 --- a/services/common/src/review_config.rs +++ b/services/common/src/review_config.rs @@ -149,6 +149,7 @@ pub fn view(item: &Item) -> Value { "auto_merge": item_bool(item, "auto_merge", false), "merge_method": item_str(item, "merge_method", "squash"), "require_human_approval": item_bool(item, "require_human_approval", true), + "retarget_stacked": item_bool(item, "retarget_stacked", false), "auto_tag": item_bool(item, "auto_tag", false), "tag_mode": item_str(item, "tag_mode", "semver"), "tag_prefix": item_str(item, "tag_prefix", "v"), @@ -302,6 +303,7 @@ pub fn build( "require_human_approval", flag("require_human_approval", true), ); + put("retarget_stacked", flag("retarget_stacked", false)); put("auto_tag", flag("auto_tag", false)); put("tag_mode", s(tag_mode)); put("tag_prefix", s(tag_prefix)); @@ -381,6 +383,7 @@ mod tests { let body = json!({ "enabled": true, "label": "review-me", "trigger": "every_pr", "instructions": "Look at SQL.", "auto_merge": true, "merge_method": "rebase", "require_human_approval": false, + "retarget_stacked": true, "tag_mode": "date", "tag_prefix": "rel-", "tag_batch_minutes": 30, "reminders_enabled": true, "reminder_cooldown_hours": 12, "health_log_groups": ["/aws/lambda/x"], @@ -395,6 +398,7 @@ mod tests { "auto_merge", "merge_method", "require_human_approval", + "retarget_stacked", "tag_mode", "tag_prefix", "tag_batch_minutes", diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index b2a28f2f1..26872c0fc 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -2117,6 +2117,19 @@ async fn handle_pull_request( if let Err(e) = send_to_queue(state, &state.config.ticket_queue_url, &check).await { warn!(error = ?e, "Could not ask waiting runs to read their dependency again"); } + // A merge: the open pull requests based on its branch move to its base + // (the worker reads the pull request and the repository's setting). + if let Some(m) = stack_merged_message(payload, installation_id, team_id, merged) { + if let Err(e) = send_to_queue( + state, + &state.config.ticket_queue_url, + &WorkerMessage::StackMerged(m), + ) + .await + { + warn!(error = ?e, "Could not ask to move the pull requests stacked on a merged one"); + } + } // CoderHelm's review bodies on it become one line each, its resolved // threads hidden (any pull request it reviewed, not only its own). if let Some(reason) = tidy_reason("pull_request", action, merged) { @@ -4641,6 +4654,32 @@ fn release_on_push( }) } +/// The worker's message for a merged pull request from this repository's +/// own branch (a fork's branch has nothing stacked on it here). +pub(crate) fn stack_merged_message( + payload: &Value, + installation_id: u64, + team_id: &str, + merged: bool, +) -> Option { + let pr = &payload["pull_request"]; + let repo = &payload["repository"]; + let same = pr["head"]["repo"]["full_name"].as_str().is_some() + && pr["head"]["repo"]["full_name"] == pr["base"]["repo"]["full_name"]; + let n = pr["number"].as_u64().unwrap_or(0); + let owner = repo["owner"]["login"].as_str().unwrap_or(""); + let name = repo["name"].as_str().unwrap_or(""); + (merged && same && n != 0 && !owner.is_empty() && !name.is_empty()).then(|| { + common::messages::StackMergedMessage { + team_id: team_id.to_string(), + installation_id, + repo_owner: owner.to_string(), + repo_name: name.to_string(), + pr_number: n, + } + }) +} + async fn handle_push( state: &AppState, payload: &Value, diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 1de5a5167..f005e65cd 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -6065,6 +6065,25 @@ impl GitHubClient { Ok(data.as_array().and_then(|arr| arr.first().cloned())) } + /// The closed pull requests whose head is `branch` of this repository, + /// merged or not, newest first (first page of 30). + pub async fn closed_pulls_from( + &self, + owner: &str, + repo: &str, + branch: &str, + ) -> Result, Box> { + let url = format!( + "{API_BASE}/repos/{owner}/{repo}/pulls?state=closed&head={owner}:{branch}&per_page=30" + ); + Ok(self + .get(&url) + .await? + .as_array() + .cloned() + .unwrap_or_default()) + } + /// List the files changed between base and head (compare API). The /// endpoint returns at most 300 files in one response; callers treat a /// near-cap result as "too large to trust" and fall back to unscoped. diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 0bdf27e6d..9ef31c4ce 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -972,6 +972,14 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe error!("Rebuilding stacked pull requests failed: {e:?}"); } } + models::WorkerMessage::StackMerged(msg) => { + if let Err(e) = passes::dead_base::after_merge(&state, &msg).await { + error!( + pr = msg.pr_number, + "Moving the pull requests stacked on a merged one failed: {e:?}" + ); + } + } models::WorkerMessage::HealthCheck(msg) => { info!(team_id = %msg.team_id, pr = msg.pr_number, attempt = msg.attempts, "Post-merge health check"); if let Err(e) = passes::health_check::run(&state, msg).await { diff --git a/services/worker/src/passes/await_merge.rs b/services/worker/src/passes/await_merge.rs index 8219e281c..19c31b892 100644 --- a/services/worker/src/passes/await_merge.rs +++ b/services/worker/src/passes/await_merge.rs @@ -1531,6 +1531,54 @@ async fn evaluate( return Ok(Next::Stop); } + // A base that is a merged pull request's branch reaches nothing: the + // gate never merges there. It moves the pull request to the branch that + // one merged into, brings it in, and waits for the review there + // (`dead_base::gate`). + let stack = super::dead_base::GhRepo { + state, + github, + team_id: &msg.team_id, + installation_id: msg.installation_id, + owner, + repo, + cfg: &cfg, + }; + match super::dead_base::gate(&stack, &pr).await? { + super::dead_base::Gate::Live => {} + super::dead_base::Gate::Moved { under, moved } => { + let line = super::dead_base::moved_line(&moved.from, under, &moved.to); + info!(pr = msg.pr_number, from = %moved.from, to = %moved.to, under, "await-merge: the base already merged — moved, not merged"); + set_state(state, msg, STATE_HEAD_MOVED, &line).await; + let body = render_status( + &msg.head_sha, + &moved.to, + &[(Mark::Waiting, line)], + None, + Some(&control_url(state, msg, Control::Stop)), + ); + publish_status(state, github, msg, record, &body).await; + return Ok(Next::Stop); + } + // A person's merged branch with the setting off: never merged + // into, and left for a person to move; read again on the slow timer. + super::dead_base::Gate::Held { under, to } => { + let from = pr["base"]["ref"].as_str().unwrap_or(""); + let line = super::dead_base::held_line(from, under, &to); + info!(pr = msg.pr_number, %from, %to, under, "await-merge: the base already merged — held for a person to move"); + set_state(state, msg, STATE_WAITING_APPROVAL, &line).await; + let body = render_status( + &msg.head_sha, + from, + &[(Mark::Waiting, line)], + None, + Some(&control_url(state, msg, Control::Stop)), + ); + publish_status(state, github, msg, record, &body).await; + return Ok(Next::Recheck); + } + } + let bot = bot_verdict_at_head(state, msg).await?; let (bot_verdict, bot_holding) = match bot { Some(b) => (Some(b.verdict), b.holding), @@ -2724,6 +2772,34 @@ pub(crate) async fn sweep_stalled( woken } +/// The repositories of one team's gate records (each armed in the +/// records' life), with their installation: `(owner, repo, installation)`. +pub(crate) async fn gated_repos(state: &WorkerState, team: &str) -> Vec<(String, String, u64)> { + let items = match gate_records(state, team).await { + Ok(i) => i, + Err(e) => { + warn!(team_id = %team, error = %e, "Could not read the team's gates"); + return Vec::new(); + } + }; + let mut out: Vec<(String, String, u64)> = Vec::new(); + for item in items { + let Some((owner, repo, _)) = common::merge_gate::parse_record_sk(&text(&item, "sk")) else { + continue; + }; + let installation_id = num(&item, "installation_id").unwrap_or(0) as u64; + if installation_id == 0 + || out + .iter() + .any(|(o, r, _)| o.eq_ignore_ascii_case(&owner) && r.eq_ignore_ascii_case(&repo)) + { + continue; + } + out.push((owner, repo, installation_id)); + } + out +} + /// One team's gate records, every page. async fn gate_records( state: &WorkerState, diff --git a/services/worker/src/passes/dead_base.rs b/services/worker/src/passes/dead_base.rs new file mode 100644 index 000000000..36a621a5e --- /dev/null +++ b/services/worker/src/passes/dead_base.rs @@ -0,0 +1,998 @@ +//! Stacked pull requests whose base already merged. +//! +//! A pull request stacked on another targets that pull request's branch. +//! GitHub moves it to the merged pull request's base only when that branch +//! is deleted; CoderHelm never deleted a branch after its merge, so a +//! stacked pull request kept a base nothing reads any more, and the merge +//! gate merged it there: "merged", and none of it on the default branch. +//! +//! Three places close that: +//! +//! - [`on_merged`]: when a pull request merges (CoderHelm's, or anyone's +//! where the repository's `retarget_stacked` setting says so), each open +//! pull request based on its branch moves to its base, the new base is +//! merged into it (GitHub's merge, a signed commit; a conflict goes to the +//! merge gate's own conflict path), and it is reviewed again there. A +//! branch that is CoderHelm's goes once nothing is based on it. +//! - [`gate`]: the merge gate never merges into a branch that is not the +//! default branch (nor the configured release branch) when that branch is +//! the head of a pull request that already merged and nothing reads it +//! any more. It moves the pull request first and waits for the review on +//! the new base; where the merged pull request was a person's and the +//! setting is off, it holds it for a person to move instead. +//! - [`sweep_repo`]: on the pull request watch sweep, open pull requests +//! still based on such a branch are moved, and a pull request CoderHelm +//! merged into one in the last [`WINDOW_DAYS`] days gets a +//! "Land #N on main" pull request with its change picked onto the branch +//! the dead one merged into. Nothing is opened when that branch already +//! holds the change. Each landing is claimed once, the claim goes back +//! when the landing fails, and a sweep opens at most [`MAX_LANDINGS`] per +//! repository. +//! +//! A branch is still read, so never dead, while an open pull request comes +//! from it, while it is protected, or once it was the head of more than one +//! merged pull request: a long-lived branch such as `develop`. + +use std::collections::{BTreeMap, HashMap}; + +use serde_json::Value; +use tracing::{info, warn}; + +use crate::clients::github::GitHubClient; +use crate::WorkerState; + +pub type Error = Box; + +/// Merged pull requests this recent are looked at for a lost merge. +pub const WINDOW_DAYS: i64 = 30; +/// Landing pull requests one sweep opens per repository. +pub const MAX_LANDINGS: usize = 3; +/// Pull requests moved per merge, or per repository per sweep. +pub const MAX_RETARGETS: usize = 20; +/// How far a chain of merged branches is followed to a live one. +pub const MAX_HOPS: usize = 5; +/// The branch a landing pull request comes from. +pub const LAND_PREFIX: &str = "coderhelm/land-"; +/// A landing claim outlives the window it is looked for in. +pub const LAND_CLAIM_SECS: u64 = 40 * 86_400; +/// Repositories one sweep looks at, all teams together. +pub const MAX_REPOS: usize = 20; +/// GitHub requests one repository's look may cost. +pub const SWEEP_REQUESTS: u64 = 12; + +// ─── Pure reads ───────────────────────────────────────────────────────────── + +fn s<'a>(v: &'a Value, ptr: &str) -> &'a str { + v.pointer(ptr).and_then(Value::as_str).unwrap_or("") +} + +/// CoderHelm's own account. +pub fn is_own(login: &str) -> bool { + common::stale_prs::is_own(login) +} + +/// The pull request's branch is in the repository it targets (not a fork). +pub fn same_repo(pr: &Value) -> bool { + let head = s(pr, "/head/repo/full_name"); + !head.is_empty() && head.eq_ignore_ascii_case(s(pr, "/base/repo/full_name")) +} + +fn ts(v: &Value) -> Option { + v.as_str() + .and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok()) + .map(|t| t.timestamp()) +} + +/// One merged pull request, as far as the stack cares. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Merged { + pub number: u64, + /// Its head branch: dead once it merged. + pub branch: String, + /// The branch it merged into. + pub into: String, + pub merged_at: i64, + /// Its head commit when it merged. + pub head_sha: String, + pub author: String, + pub title: String, +} + +/// Pure: a closed pull request that merged, from this repository's branch. +pub fn merged_of(pr: &Value) -> Option { + let merged_at = ts(&pr["merged_at"])?; + if !same_repo(pr) { + return None; + } + Some(Merged { + number: pr["number"].as_u64()?, + branch: s(pr, "/head/ref").to_string(), + into: s(pr, "/base/ref").to_string(), + merged_at, + head_sha: s(pr, "/head/sha").to_string(), + author: s(pr, "/user/login").to_string(), + title: s(pr, "/title").to_string(), + }) + .filter(|m| !m.branch.is_empty() && !m.into.is_empty()) +} + +/// Pure: may CoderHelm move what is stacked on this merged pull request? +/// Always for its own; for a person's only where the repository says so. +pub fn may_retarget(merged: &Value, setting: bool) -> bool { + merged["merged"].as_bool() == Some(true) + && same_repo(merged) + && (is_own(s(merged, "/user/login")) || setting) +} + +/// Pure: the open pull requests based on `branch`. +pub fn stacked_on<'a>(open: &'a [Value], branch: &str) -> Vec<&'a Value> { + open.iter() + .filter(|p| s(p, "/base/ref") == branch && !branch.is_empty()) + .take(MAX_RETARGETS) + .collect() +} + +/// Pure: the merged pull request's branch may go: it is CoderHelm's (its +/// pull request, in this repository, not the default or release branch) +/// and no open pull request is based on it any more. +pub fn may_delete(merged: &Value, default: &str, release: Option<&str>, open: &[Value]) -> bool { + let branch = s(merged, "/head/ref"); + is_own(s(merged, "/user/login")) + && same_repo(merged) + && !branch.is_empty() + && branch != default + && Some(branch) != release + && !open.iter().any(|p| s(p, "/base/ref") == branch) +} + +/// Pure: a base the gate merges into without asking. +pub fn live_by_name(base: &str, default: &str, release: Option<&str>) -> bool { + base == default || Some(base) == release +} + +/// Pure: the branches whose pull request merged, by branch. A branch that +/// was the head of more than one merged pull request is a long-lived one +/// (a `develop` released into `main` again and again) that keeps taking +/// work, never a stacked base: it is left out. +pub fn dead_branches(closed: &[Value]) -> BTreeMap { + let mut out: BTreeMap = BTreeMap::new(); + let mut reused: Vec = Vec::new(); + for m in closed.iter().filter_map(merged_of) { + if out.get(&m.branch).is_some_and(|had| had.number != m.number) { + reused.push(m.branch.clone()); + } else { + out.insert(m.branch.clone(), m); + } + } + for b in reused { + out.remove(&b); + } + out +} + +/// Pure: an open pull request from `branch` (in this repository) carries +/// it on, so the branch is still read whatever merged from it before. +pub fn carried_on(branch: &str, open: &[Value]) -> bool { + !branch.is_empty() + && open + .iter() + .any(|p| same_repo(p) && s(p, "/head/ref") == branch) +} + +/// Pure: may the stack code act on what sits on `under`'s branch? Always +/// when CoderHelm opened `under`; for a person's only where the +/// repository's `retarget_stacked` setting says so. +pub fn may_act_on(under: &Merged, setting: bool) -> bool { + is_own(&under.author) || setting +} + +/// A branch whose pull request merged is still read when an open pull +/// request carries it on or the branch is protected (a long-lived branch +/// the team keeps). A failed protection lookup counts as read: nothing is +/// moved or landed on a guess. +async fn still_read(r: &R, branch: &str, open: &[Value]) -> bool { + carried_on(branch, open) || r.protected(branch).await +} + +/// Pure: where a pull request based on `base` belongs: along the merged +/// branches (`dead`) to the first live one, at most [`MAX_HOPS`] steps. +pub fn live_base( + base: &str, + default: &str, + release: Option<&str>, + dead: &BTreeMap, +) -> String { + let mut at = base.to_string(); + for _ in 0..MAX_HOPS { + if live_by_name(&at, default, release) { + break; + } + match dead.get(&at) { + Some(m) => at = m.into.clone(), + None => break, + } + } + at +} + +/// A pull request merged into a branch that was already dead: its change +/// never reached `target`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Lost { + pub pr: Merged, + /// The pull request whose branch it merged into, merged before it. + pub under: Merged, + /// Where the change belongs. + pub target: String, +} + +/// Pure: the lost merges among `closed` (merged by anyone so far; the +/// caller keeps the ones CoderHelm merged): merged inside the window into a +/// branch whose own pull request had merged before. +pub fn lost( + closed: &[Value], + dead: &BTreeMap, + now: i64, + default: &str, + release: Option<&str>, +) -> Vec { + let mut out: Vec = closed + .iter() + .filter_map(merged_of) + .filter(|m| now - m.merged_at <= WINDOW_DAYS * 86_400) + .filter(|m| !live_by_name(&m.into, default, release)) + .filter_map(|m| { + let under = dead.get(&m.into)?.clone(); + (under.merged_at < m.merged_at).then(|| Lost { + target: live_base(&under.into, default, release, dead), + under, + pr: m, + }) + }) + .collect(); + out.sort_by_key(|l| l.pr.merged_at); + out +} + +pub fn land_branch(n: u64) -> String { + format!("{LAND_PREFIX}{n}") +} + +pub fn land_title(l: &Lost) -> String { + format!("Land #{} on {}", l.pr.number, l.target) +} + +/// The landing commit's message. +pub fn land_message(l: &Lost) -> String { + format!( + "Land #{} on {}\n\n#{} merged into `{}` after #{} had merged that branch into `{}`, \ + so its change never reached `{}`. This is that change, picked onto `{}`.", + l.pr.number, + l.target, + l.pr.number, + l.pr.into, + l.under.number, + l.under.into, + l.target, + l.target + ) +} + +pub fn land_body(l: &Lost) -> String { + format!( + "## Summary\n\n#{n} (\"{title}\") was merged into `{dead}`, the branch of #{under}. \ + #{under} had already merged into `{into}`, so nothing read `{dead}` any more and #{n}'s \ + change never reached `{target}`.\n\n## Changes\n\n#{n}'s own change, picked onto \ + `{target}` in one commit.\n\n## Verification\n\nThe pick is GitHub's own three way merge \ + of #{n}'s head onto `{target}`, from the point #{n} last shared with #{under}. It \ + changes `{target}`, so the change was not there yet.", + n = l.pr.number, + title = l.pr.title.replace('"', "'"), + dead = l.pr.into, + under = l.under.number, + into = l.under.into, + target = l.target, + ) +} + +/// The lost pull request's number in a `land#N` claim key. +fn land_number(key: &str) -> u64 { + key.strip_prefix("land#") + .and_then(|n| n.parse().ok()) + .unwrap_or(0) +} + +/// The claim that makes one landing pull request per lost merge, ever. +pub fn land_claim_sk(owner: &str, repo: &str, n: u64) -> String { + format!( + "STACKLAND#{}/{}#{n}", + owner.to_ascii_lowercase(), + repo.to_ascii_lowercase() + ) +} + +/// The merge gate's status line for a pull request it moved. +pub fn moved_line(from: &str, under: u64, to: &str) -> String { + format!( + "`{from}` is the branch of #{under}, which already merged into `{to}`, so nothing \ + merged into `{from}` reaches `{to}`. CoderHelm moved this pull request to `{to}`, \ + brings `{to}` in, and merges once the review of it there clears" + ) +} + +// ─── What the work needs from GitHub and storage ──────────────────────────── + +/// How bringing the new base in went. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BaseIn { + /// Merged in (GitHub's merge commit): the new head. + Merged(String), + /// It conflicts: the merge gate's conflict path takes it. + ToGate, + /// A fork's branch: nothing CoderHelm can push. + Fork, + Failed(String), +} + +/// How picking a lost change onto its target went. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Picked { + /// The target already holds the change: nothing to land. + Already, + /// The change is on this new branch, one commit past the target. + Branch(String), + /// It conflicts with the target: nothing pushed. + Conflict, +} + +#[async_trait::async_trait] +pub trait Repo: Send + Sync { + async fn default_branch(&self) -> Result; + /// The configured release branch, if one is set. + async fn release_branch(&self) -> Option; + async fn pull(&self, n: u64) -> Result; + async fn open_pulls(&self) -> Result, Error>; + /// Recently closed pull requests, newest first. + async fn closed_pulls(&self) -> Result, Error>; + /// Closed pull requests whose head is `branch`. + async fn closed_from(&self, branch: &str) -> Result, Error>; + async fn set_base(&self, n: u64, base: &str) -> Result<(), Error>; + async fn bring_base_in(&self, pr: &Value, base: &str) -> BaseIn; + /// CoderHelm reviews the pull request again (at `head`, on its new base). + async fn review(&self, pr: &Value, head: &str); + async fn delete_branch(&self, branch: &str) -> Result<(), Error>; + /// `l`'s change (its head past the point it last shared with the + /// branch it was stacked on) picked onto `l.target`, on `branch`. + async fn pick(&self, l: &Lost, branch: &str, message: &str) -> Result; + async fn open_pr(&self, title: &str, body: &str, head: &str, base: &str) -> Result; + /// Whether the branch is protected; true when that cannot be read. + async fn protected(&self, branch: &str) -> bool; + /// Once per key, ever: false when claimed before. + async fn claim(&self, key: &str) -> bool; + /// Gives a claim back, so a landing that failed is tried again. + async fn release(&self, key: &str); + /// Whether people's merges move what is stacked on them too. + fn retarget_setting(&self) -> bool; +} + +/// One pull request moved, and how its new base came in. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Moved { + pub pr: u64, + pub from: String, + pub to: String, + pub base_in: BaseIn, +} + +async fn move_one(r: &R, pr: &Value, to: &str) -> Result { + let n = pr["number"].as_u64().unwrap_or(0); + let from = s(pr, "/base/ref").to_string(); + r.set_base(n, to).await?; + let base_in = r.bring_base_in(pr, to).await; + match &base_in { + BaseIn::Merged(head) => r.review(pr, head).await, + BaseIn::Fork | BaseIn::Failed(_) => r.review(pr, s(pr, "/head/sha")).await, + BaseIn::ToGate => {} + } + info!(pr = n, %from, %to, ?base_in, "Moved a stacked pull request off a merged branch"); + Ok(Moved { + pr: n, + from, + to: to.to_string(), + base_in, + }) +} + +/// What a merge did to the pull requests stacked on it. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct AfterMerge { + pub moved: Vec, + pub deleted: bool, +} + +/// A pull request merged: each open pull request based on its branch moves +/// to its base, and the branch goes when it is CoderHelm's. +pub async fn on_merged(r: &R, merged: &Value) -> Result { + let mut out = AfterMerge::default(); + if !may_retarget(merged, r.retarget_setting()) { + return Ok(out); + } + let branch = s(merged, "/head/ref").to_string(); + let to = s(merged, "/base/ref").to_string(); + let open = r.open_pulls().await?; + let stacked = stacked_on(&open, &branch); + // A long-lived branch merging (a `develop` released into `main`) is + // still read: what is based on it stays. + if !stacked.is_empty() && still_read(r, &branch, &open).await { + return Ok(out); + } + if !stacked.is_empty() { + // The merge itself counts even before GitHub's list shows it. + let mut from = r.closed_from(&branch).await?; + from.push(merged.clone()); + if !dead_branches(&from).contains_key(&branch) { + return Ok(out); + } + } + for pr in stacked { + match move_one(r, pr, &to).await { + Ok(m) => out.moved.push(m), + Err(e) => { + warn!(pr = pr["number"].as_u64().unwrap_or(0), error = %e, "Could not move a stacked pull request"); + } + } + } + let default = r.default_branch().await?; + let release = r.release_branch().await; + // Read again: only a branch nothing is based on any more goes. + let open = r.open_pulls().await?; + if may_delete(merged, &default, release.as_deref(), &open) { + match r.delete_branch(&branch).await { + Ok(()) => out.deleted = true, + Err(e) => warn!(%branch, error = %e, "Could not delete a merged branch"), + } + } + Ok(out) +} + +/// What the merge gate found about the base. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Gate { + /// A base merging into reaches what it should. + Live, + /// The base was a merged pull request's branch: moved to `to`. + Moved { under: u64, moved: Moved }, + /// The base was the branch of a person's merged pull request and the + /// repository's `retarget_stacked` setting is off: not merged into, and + /// not moved either. The gate waits for a person to move it. + Held { under: u64, to: String }, +} + +/// The merge gate's status line for a pull request it holds. +pub fn held_line(from: &str, under: u64, to: &str) -> String { + format!( + "`{from}` is the branch of #{under}, which already merged into `{to}`, so nothing \ + merged into `{from}` reaches `{to}`. CoderHelm does not merge here; move this pull \ + request to `{to}` (or turn on `retarget_stacked` to let CoderHelm move it)" + ) +} + +/// The merge gate, before merging: a base that is not the default branch +/// (nor the release branch), is the head of a pull request that already +/// merged, and is no longer read (no open pull request carries it on, and +/// it is not protected) is never merged into. The pull request moves first +/// and the gate waits for the review there; where the merged pull request +/// was a person's and the repository's setting is off, it is held instead. +pub async fn gate(r: &R, pr: &Value) -> Result { + let base = s(pr, "/base/ref"); + let default = match s(pr, "/base/repo/default_branch") { + "" => r.default_branch().await?, + d => d.to_string(), + }; + let release = r.release_branch().await; + if live_by_name(base, &default, release.as_deref()) { + return Ok(Gate::Live); + } + let mut dead: BTreeMap = BTreeMap::new(); + let mut open: Option> = None; + let mut at = base.to_string(); + for _ in 0..MAX_HOPS { + if live_by_name(&at, &default, release.as_deref()) { + break; + } + let closed = r.closed_from(&at).await?; + let Some(m) = dead_branches(&closed).remove(&at) else { + break; + }; + if open.is_none() { + open = Some(r.open_pulls().await?); + } + if still_read(r, &at, open.as_deref().unwrap_or(&[])).await { + break; + } + at = m.into.clone(); + dead.insert(m.branch.clone(), m); + } + let Some(under) = dead.get(base).cloned() else { + return Ok(Gate::Live); + }; + let to = live_base(base, &default, release.as_deref(), &dead); + if !may_act_on(&under, r.retarget_setting()) { + return Ok(Gate::Held { + under: under.number, + to, + }); + } + let moved = move_one(r, pr, &to).await?; + Ok(Gate::Moved { + under: under.number, + moved, + }) +} + +/// Pure: the dead branches something still looks up: the base of an open +/// pull request, the branch a merge went into, or a hop on a chain. +fn looked_up(dead: &BTreeMap, open: &[Value], closed: &[Value]) -> Vec { + let mut out: Vec = open + .iter() + .map(|p| s(p, "/base/ref").to_string()) + .chain(closed.iter().filter_map(merged_of).map(|m| m.into)) + .chain(dead.values().map(|m| m.into.clone())) + .filter(|n| dead.contains_key(n)) + .collect(); + out.sort(); + out.dedup(); + out +} + +/// How one landing went. +enum Landing { + Already, + Conflict, + Opened(u64), +} + +/// Picks a lost change onto its target and opens its landing pull request. +/// A landing branch left without a pull request is deleted again. +async fn land(r: &R, l: &Lost) -> Result { + match r + .pick(l, &land_branch(l.pr.number), &land_message(l)) + .await? + { + Picked::Already => Ok(Landing::Already), + Picked::Conflict => Ok(Landing::Conflict), + Picked::Branch(b) => match r + .open_pr(&land_title(l), &land_body(l), &b, &l.target) + .await + { + Ok(n) => Ok(Landing::Opened(n)), + Err(e) => { + if let Err(d) = r.delete_branch(&b).await { + warn!(branch = %b, error = %d, "Lost merge: could not delete the landing branch left without a pull request"); + } + Err(e) + } + }, + } +} + +/// What one repository's sweep did. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Swept { + pub moved: Vec, + /// `(lost pull request, landing pull request)`. + pub landed: Vec<(u64, u64)>, + /// Lost pull requests whose change the target already holds. + pub already: Vec, + /// Lost pull requests whose change conflicts with the target. + pub conflicts: Vec, + /// Lost pull requests whose landing failed this sweep (claim given back). + pub failed: Vec, +} + +/// The backstop for one repository: open pull requests still based on a +/// merged branch move, and each lost merge CoderHelm made gets its landing +/// pull request. +pub async fn sweep_repo(r: &R, now: i64) -> Result { + let mut out = Swept::default(); + let default = r.default_branch().await?; + let release = r.release_branch().await; + let open = r.open_pulls().await?; + let closed = r.closed_pulls().await?; + let mut dead = dead_branches(&closed); + // A branch still read is not dead, whatever merged from it before. + for b in looked_up(&dead, &open, &closed) { + if still_read(r, &b, &open).await { + dead.remove(&b); + } + } + let setting = r.retarget_setting(); + let mut moved = 0; + for pr in &open { + let base = s(pr, "/base/ref"); + if live_by_name(base, &default, release.as_deref()) { + continue; + } + let Some(under) = dead.get(base) else { + continue; + }; + if !may_act_on(under, setting) || moved >= MAX_RETARGETS { + continue; + } + let to = live_base(base, &default, release.as_deref(), &dead); + match move_one(r, pr, &to).await { + Ok(m) => { + moved += 1; + out.moved.push(m); + } + Err(e) => { + warn!(pr = pr["number"].as_u64().unwrap_or(0), error = %e, "Sweep: could not move a stacked pull request") + } + } + } + let mut landed = 0; + for l in lost(&closed, &dead, now, &default, release.as_deref()) { + if landed >= MAX_LANDINGS { + break; + } + // Only a merge CoderHelm made is CoderHelm's to land. + let full = match r.pull(l.pr.number).await { + Ok(full) => full, + Err(e) => { + warn!(pr = l.pr.number, error = %e, "Lost merge: could not read the pull request; tried again next sweep"); + continue; + } + }; + if !is_own(s(&full, "/merged_by/login")) { + continue; + } + let key = format!("land#{}", l.pr.number); + if !r.claim(&key).await { + continue; + } + landed += 1; + match land(r, &l).await { + Ok(Landing::Already) => { + info!(pr = l.pr.number, target = %l.target, "Lost merge: the target already holds the change"); + out.already.push(l.pr.number); + } + Ok(Landing::Conflict) => { + warn!(pr = l.pr.number, target = %l.target, "Lost merge: its change conflicts with the target; nothing opened"); + out.conflicts.push(l.pr.number); + } + Ok(Landing::Opened(n)) => { + info!( + pr = l.pr.number, + landing = n, + "Lost merge: landing pull request opened" + ); + out.landed.push((l.pr.number, n)); + } + Err(e) => { + // Nothing final happened: the claim goes back, so the next + // sweep tries this landing again. + r.release(&key).await; + warn!(pr = l.pr.number, error = %e, "Lost merge: landing failed; tried again next sweep"); + out.failed.push(l.pr.number); + } + } + } + Ok(out) +} + +// ─── GitHub and storage ───────────────────────────────────────────────────── + +/// The [`Repo`] of one repository on GitHub. +pub struct GhRepo<'a> { + pub state: &'a WorkerState, + pub github: &'a GitHubClient, + pub team_id: &'a str, + pub installation_id: u64, + pub owner: &'a str, + pub repo: &'a str, + pub cfg: &'a super::review_actions::OnApproveConfig, +} + +#[async_trait::async_trait] +impl Repo for GhRepo<'_> { + async fn default_branch(&self) -> Result { + self.github.get_default_branch(self.owner, self.repo).await + } + + async fn release_branch(&self) -> Option { + let cfg = super::release_notes::ReleaseNotesConfig::load( + self.state, + self.team_id, + self.owner, + self.repo, + ) + .await; + Some(cfg.branch.trim().to_string()).filter(|b| !b.is_empty()) + } + + async fn pull(&self, n: u64) -> Result { + self.github.get_pull_request(self.owner, self.repo, n).await + } + + async fn open_pulls(&self) -> Result, Error> { + self.github + .list_open_pulls_all(self.owner, self.repo, 3) + .await + } + + async fn closed_pulls(&self) -> Result, Error> { + Ok(self + .github + .list_pull_requests(self.owner, self.repo, "closed", 100) + .await? + .as_array() + .cloned() + .unwrap_or_default()) + } + + async fn closed_from(&self, branch: &str) -> Result, Error> { + self.github + .closed_pulls_from(self.owner, self.repo, branch) + .await + } + + async fn set_base(&self, n: u64, base: &str) -> Result<(), Error> { + self.github + .set_pull_base(self.owner, self.repo, n, base) + .await + } + + async fn bring_base_in(&self, pr: &Value, base: &str) -> BaseIn { + let branch = s(pr, "/head/ref"); + if !same_repo(pr) || branch.is_empty() { + return BaseIn::Fork; + } + let message = format!("Merge {base} into {branch}"); + match self + .github + .merge_branch(self.owner, self.repo, branch, base, &message) + .await + { + Ok(true) => match self.github.get_ref(self.owner, self.repo, branch).await { + Ok(head) => BaseIn::Merged(head), + Err(e) => BaseIn::Failed(e.to_string()), + }, + Ok(false) => { + // A conflict: the merge gate resolves it on its own path + // (`await_merge::keep_current`) when auto-merge is on. + if self.cfg.auto_merge { + super::await_merge::arm( + self.state, + self.team_id, + self.installation_id, + self.owner, + self.repo, + pr["number"].as_u64().unwrap_or(0), + s(pr, "/head/sha"), + base, + is_own(s(pr, "/user/login")), + ) + .await; + } + BaseIn::ToGate + } + Err(e) => BaseIn::Failed(e.to_string()), + } + } + + async fn review(&self, pr: &Value, head: &str) { + super::review_pr::review_after_base_merge( + self.state, + self.team_id, + self.installation_id, + (self.owner, self.repo, pr["number"].as_u64().unwrap_or(0)), + head, + ) + .await; + } + + async fn delete_branch(&self, branch: &str) -> Result<(), Error> { + self.github + .delete_branch(self.owner, self.repo, branch) + .await + } + + async fn pick(&self, l: &Lost, branch: &str, message: &str) -> Result { + let (gh, owner, repo) = (self.github, self.owner, self.repo); + // The point the lost pull request last shared with the one it was + // stacked on: everything before it is already on the target. + let cmp = gh + .get_diff(owner, repo, &l.under.head_sha, &l.pr.head_sha) + .await?; + let from = cmp + .pointer("/merge_base_commit/sha") + .and_then(Value::as_str) + .ok_or("no merge base for the lost change")? + .to_string(); + let onto = gh.get_ref(owner, repo, &l.target).await?; + let (onto_tree, _) = gh.commit_tree_parents(owner, repo, &onto).await?; + // GitHub's three way merge: a scratch branch holds the target's tree + // on top of `from`, and the lost head is merged into it. + let scratch = format!("{LAND_PREFIX}scratch-{}", ulid::Ulid::new()); + let side = gh + .put_commit( + owner, + repo, + "Land: target tree", + &onto_tree, + std::slice::from_ref(&from), + ) + .await?; + gh.create_branch(owner, repo, &scratch, &side).await?; + let merged = gh + .merge_branch(owner, repo, &scratch, &l.pr.head_sha, message) + .await; + let tip = match &merged { + Ok(true) => gh.get_ref(owner, repo, &scratch).await.ok(), + _ => None, + }; + let _ = gh.delete_branch(owner, repo, &scratch).await; + if !merged? { + return Ok(Picked::Conflict); + } + let tip = tip.ok_or("the landing merge left no commit")?; + let (tree, _) = gh.commit_tree_parents(owner, repo, &tip).await?; + if tree == onto_tree { + return Ok(Picked::Already); + } + let commit = gh.put_commit(owner, repo, message, &tree, &[onto]).await?; + // A landing branch an earlier failed try left behind: the claim on + // this landing is ours, so no pull request comes from it. + let _ = gh.delete_branch(owner, repo, branch).await; + gh.create_branch(owner, repo, branch, &commit).await?; + Ok(Picked::Branch(branch.to_string())) + } + + async fn open_pr(&self, title: &str, body: &str, head: &str, base: &str) -> Result { + let pr = self + .github + .create_pull_request(self.owner, self.repo, title, body, head, base, false) + .await?; + Ok(pr["number"].as_u64().unwrap_or(0)) + } + + async fn protected(&self, branch: &str) -> bool { + match self + .github + .branch_is_protected(self.owner, self.repo, branch) + .await + { + Ok(p) => p, + Err(e) => { + warn!(%branch, error = %e, "Stack: could not read the branch's protection; left as it is"); + true + } + } + } + + async fn claim(&self, key: &str) -> bool { + common::claim::claim( + &self.state.dynamo, + &self.state.config.settings_table_name, + self.team_id, + &land_claim_sk(self.owner, self.repo, land_number(key)), + LAND_CLAIM_SECS, + ) + .await + == common::claim::Claim::Won + } + + async fn release(&self, key: &str) { + common::claim::release( + &self.state.dynamo, + &self.state.config.settings_table_name, + self.team_id, + &land_claim_sk(self.owner, self.repo, land_number(key)), + ) + .await + } + + fn retarget_setting(&self) -> bool { + self.cfg.retarget_stacked + } +} + +/// The worker's handler for a merged pull request (`stack_merged`). +pub async fn after_merge( + state: &WorkerState, + msg: &crate::models::StackMergedMessage, +) -> Result<(), Error> { + let github = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + msg.installation_id, + &state.http, + )?; + let (owner, repo) = (msg.repo_owner.as_str(), msg.repo_name.as_str()); + let cfg = super::review_actions::OnApproveConfig::load(state, &msg.team_id, owner, repo).await; + let merged = github.get_pull_request(owner, repo, msg.pr_number).await?; + let r = GhRepo { + state, + github: &github, + team_id: &msg.team_id, + installation_id: msg.installation_id, + owner, + repo, + cfg: &cfg, + }; + let done = on_merged(&r, &merged).await?; + if !done.moved.is_empty() || done.deleted { + info!(pr = msg.pr_number, moved = ?done.moved, deleted = done.deleted, "Merged pull request: stacked pull requests moved"); + } + Ok(()) +} + +/// The backstop, on the pull request watch sweep: each repository with a +/// merge gate armed in the gate records' life (30 days) is looked at once. +/// Returns `owner/repo: what` for each repository where something moved. +pub(crate) async fn sweep( + state: &WorkerState, + budget: &mut crate::clients::github_budget::SweepGate, + clients: &mut HashMap, +) -> Vec { + let now = chrono::Utc::now().timestamp(); + let mut report = Vec::new(); + let mut looked = 0; + for team in super::learning_wait::teams(state).await { + let repos = super::await_merge::gated_repos(state, &team).await; + for (owner, repo, installation_id) in repos { + if looked >= MAX_REPOS { + return report; + } + if !budget.allows(state, installation_id, SWEEP_REQUESTS).await { + continue; + } + if let std::collections::hash_map::Entry::Vacant(v) = clients.entry(installation_id) { + match GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + installation_id, + &state.http, + ) { + Ok(g) => { + v.insert(g); + } + Err(_) => continue, + } + } + looked += 1; + let cfg = + super::review_actions::OnApproveConfig::load(state, &team, &owner, &repo).await; + let r = GhRepo { + state, + github: &clients[&installation_id], + team_id: &team, + installation_id, + owner: &owner, + repo: &repo, + cfg: &cfg, + }; + match sweep_repo(&r, now).await { + Ok(done) => { + if !done.moved.is_empty() + || !done.landed.is_empty() + || !done.conflicts.is_empty() + || !done.failed.is_empty() + { + report.push(format!( + "{owner}/{repo}: moved {:?}, landed {:?}, conflicts {:?}, failed {:?}", + done.moved.iter().map(|m| m.pr).collect::>(), + done.landed, + done.conflicts, + done.failed + )); + } + } + Err(e) => { + warn!(%owner, %repo, error = %e, "Stack sweep: could not look at the repository") + } + } + } + } + report +} diff --git a/services/worker/src/passes/incidents/ac_partial_and_red_ci.rs b/services/worker/src/passes/incidents/ac_partial_and_red_ci.rs index ca4c5e545..b979fc3b2 100644 --- a/services/worker/src/passes/incidents/ac_partial_and_red_ci.rs +++ b/services/worker/src/passes/incidents/ac_partial_and_red_ci.rs @@ -86,6 +86,10 @@ fn pull_requests_are_opened_and_marked_ready_in_one_place_each() { assert_eq!( opens, vec![ + // The landing of a change CoderHelm merged into a branch that + // had already merged, not a run's: one per lost merge, claimed + // (`dead_base`). + "passes/dead_base.rs".to_string(), // The revert of a merged change whose deploy failed, not a // run's: opened ready with its evidence, never a draft or a // partial (`deploy_revert`). diff --git a/services/worker/src/passes/incidents/xn_stacked_merge_reaches_main.rs b/services/worker/src/passes/incidents/xn_stacked_merge_reaches_main.rs new file mode 100644 index 000000000..5d0001ab9 --- /dev/null +++ b/services/worker/src/passes/incidents/xn_stacked_merge_reaches_main.rs @@ -0,0 +1,680 @@ +//! xn. Pull request B was stacked on pull request A: its base was A's +//! branch. CoderHelm's merge gate squash-merged A into `main`. A's branch +//! was left in place, so GitHub never moved B, and the gate then merged B +//! into A's branch, which nothing read any more. B said "merged", and none +//! of its change reached `main`. +//! +//! Why: GitHub moves a stacked pull request to the merged one's base only +//! when the merged branch is deleted, and CoderHelm never deleted it nor +//! moved B itself. The gate merged into whatever base the pull request +//! named, with no look at whether that base was a branch whose own pull +//! request had already merged. +//! +//! Guarantee: when a pull request merges (CoderHelm's, or a person's where +//! the repository's `retarget_stacked` setting says so), every open pull +//! request based on its branch moves to its base, the new base is merged +//! into it (GitHub's merge, a signed commit; a conflict goes to the gate's +//! own conflict path), and it is reviewed there; CoderHelm's branch goes +//! once nothing is based on it. The gate never merges into a base that is +//! not the default (or release) branch and is a merged pull request's +//! branch nothing reads any more: it moves the pull request and waits for +//! the review, or holds it for a person where the merged pull request was a +//! person's and the setting is off. A branch an open pull request comes +//! from, a protected one, or one merged from more than once (a long-lived +//! `develop`) is still read. The watch +//! sweep moves what is still based on such a branch, and for a change +//! CoderHelm merged into one in the last 30 days opens one +//! "Land #N on main" pull request, claimed once and capped per sweep, and +//! none when `main` already holds the change; a landing that fails gives +//! its claim back and is tried again next sweep. +//! +//! The replays run the stack's own code against an invented repository: +//! branches are sets of changes, a squash merge adds the head's changes to +//! the base, and a pick is what the head adds past the branch it was +//! stacked on. + +use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::sync::Mutex; + +use serde_json::{json, Value}; + +use super::fixture::fn_src; +use crate::passes::dead_base::{self, BaseIn, Error, Gate, Lost, Picked, Repo}; + +const BOT: &str = "coderhelm[bot]"; +const PERSON: &str = "river-dev"; +const FULL: &str = "acme/widgets"; +const DAY: i64 = 86_400; +const NOW: i64 = 1_800_000_000; + +#[derive(Default)] +struct World { + /// Commit sha to the changes it holds. + commits: BTreeMap>, + branches: BTreeMap, + prs: Vec, + seq: u64, + reviewed: Vec<(u64, String)>, + claims: HashSet, + deleted: Vec, + retarget_setting: bool, + protected: BTreeSet, + /// Picks and pull request openings that fail (a GitHub 5xx), in turn. + fail_picks: usize, + fail_opens: usize, +} + +struct Fake(Mutex); + +fn iso(t: i64) -> String { + chrono::DateTime::from_timestamp(t, 0) + .unwrap() + .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) +} + +impl World { + fn commit(&mut self, content: BTreeSet) -> String { + self.seq += 1; + let sha = format!("{:040x}", self.seq); + self.commits.insert(sha.clone(), content); + sha + } + + fn content(&self, branch: &str) -> BTreeSet { + self.branches + .get(branch) + .and_then(|s| self.commits.get(s)) + .cloned() + .unwrap_or_default() + } + + fn branch_with(&mut self, branch: &str, from: &str, changes: &[&str]) { + let mut c = self.content(from); + c.extend(changes.iter().map(|s| s.to_string())); + let sha = self.commit(c); + self.branches.insert(branch.to_string(), sha); + } + + fn open_pr(&mut self, n: u64, head: &str, base: &str, author: &str) { + let pr = json!({ + "number": n, + "title": format!("Change {n}"), + "state": "open", + "merged": false, + "merged_at": null, + "user": {"login": author}, + "head": {"ref": head, "sha": self.branches[head], "repo": {"full_name": FULL}}, + "base": {"ref": base, "repo": {"full_name": FULL, "default_branch": "main"}}, + }); + self.prs.push(pr); + } + + fn pr(&self, n: u64) -> &Value { + self.prs.iter().find(|p| p["number"] == n).unwrap() + } + + fn pr_mut(&mut self, n: u64) -> &mut Value { + self.prs.iter_mut().find(|p| p["number"] == n).unwrap() + } + + /// A squash merge, as GitHub does it: the base gets the head's changes. + /// The branch stays, as CoderHelm's merge leaves it. + fn squash(&mut self, n: u64, by: &str, at: i64) { + let (head, base) = { + let p = self.pr(n); + ( + p["head"]["ref"].as_str().unwrap().to_string(), + p["base"]["ref"].as_str().unwrap().to_string(), + ) + }; + let mut c = self.content(&base); + c.extend(self.content(&head)); + let sha = self.commit(c); + self.branches.insert(base, sha.clone()); + let head_sha = self.branches[&head].clone(); + let p = self.pr_mut(n); + p["state"] = json!("closed"); + p["merged"] = json!(true); + p["merged_at"] = json!(iso(at)); + p["merged_by"] = json!({"login": by}); + p["merge_commit_sha"] = json!(sha); + p["head"]["sha"] = json!(head_sha); + } +} + +#[async_trait::async_trait] +impl Repo for Fake { + async fn default_branch(&self) -> Result { + Ok("main".to_string()) + } + async fn release_branch(&self) -> Option { + None + } + async fn pull(&self, n: u64) -> Result { + Ok(self.0.lock().unwrap().pr(n).clone()) + } + async fn open_pulls(&self) -> Result, Error> { + let w = self.0.lock().unwrap(); + Ok(w.prs + .iter() + .filter(|p| p["state"] == "open") + .cloned() + .collect()) + } + async fn closed_pulls(&self) -> Result, Error> { + let w = self.0.lock().unwrap(); + Ok(w.prs + .iter() + .filter(|p| p["state"] == "closed") + .map(|p| { + // The list endpoint has no `merged_by`. + let mut p = p.clone(); + p.as_object_mut().unwrap().remove("merged_by"); + p + }) + .collect()) + } + async fn closed_from(&self, branch: &str) -> Result, Error> { + let w = self.0.lock().unwrap(); + Ok(w.prs + .iter() + .filter(|p| p["state"] == "closed" && p["head"]["ref"] == branch) + .cloned() + .collect()) + } + async fn set_base(&self, n: u64, base: &str) -> Result<(), Error> { + self.0.lock().unwrap().pr_mut(n)["base"]["ref"] = json!(base); + Ok(()) + } + async fn bring_base_in(&self, pr: &Value, base: &str) -> BaseIn { + let mut w = self.0.lock().unwrap(); + let head = pr["head"]["ref"].as_str().unwrap().to_string(); + let mut c = w.content(&head); + c.extend(w.content(base)); + let sha = w.commit(c); + w.branches.insert(head, sha.clone()); + let n = pr["number"].as_u64().unwrap(); + w.pr_mut(n)["head"]["sha"] = json!(sha); + BaseIn::Merged(sha) + } + async fn review(&self, pr: &Value, head: &str) { + let n = pr["number"].as_u64().unwrap(); + self.0.lock().unwrap().reviewed.push((n, head.to_string())); + } + async fn delete_branch(&self, branch: &str) -> Result<(), Error> { + let mut w = self.0.lock().unwrap(); + w.branches.remove(branch); + w.deleted.push(branch.to_string()); + Ok(()) + } + async fn pick(&self, l: &Lost, branch: &str, _message: &str) -> Result { + let mut w = self.0.lock().unwrap(); + if w.fail_picks > 0 { + w.fail_picks -= 1; + return Err("502 Bad Gateway".into()); + } + let own: BTreeSet = w.commits[&l.pr.head_sha] + .difference(&w.commits[&l.under.head_sha]) + .cloned() + .collect(); + let onto = w.content(&l.target); + if own.is_subset(&onto) { + return Ok(Picked::Already); + } + let mut c = onto; + c.extend(own); + let sha = w.commit(c); + w.branches.insert(branch.to_string(), sha); + Ok(Picked::Branch(branch.to_string())) + } + async fn open_pr(&self, title: &str, body: &str, head: &str, base: &str) -> Result { + let mut w = self.0.lock().unwrap(); + if w.fail_opens > 0 { + w.fail_opens -= 1; + return Err("502 Bad Gateway".into()); + } + let n = 100 + w.prs.len() as u64; + w.open_pr(n, head, base, BOT); + let p = w.pr_mut(n); + p["title"] = json!(title); + p["body"] = json!(body); + Ok(n) + } + async fn protected(&self, branch: &str) -> bool { + self.0.lock().unwrap().protected.contains(branch) + } + async fn claim(&self, key: &str) -> bool { + self.0.lock().unwrap().claims.insert(key.to_string()) + } + async fn release(&self, key: &str) { + self.0.lock().unwrap().claims.remove(key); + } + fn retarget_setting(&self) -> bool { + self.0.lock().unwrap().retarget_setting + } +} + +/// `main` with one change; A (`coderhelm/feature-a`, one change) on it; B +/// (`coderhelm/feature-b`) stacked on A with its own change. +fn stacked(author: &str) -> Fake { + let mut w = World::default(); + let root = w.commit(["m0".to_string()].into()); + w.branches.insert("main".to_string(), root); + w.branch_with("coderhelm/feature-a", "main", &["a1"]); + w.branch_with("coderhelm/feature-b", "coderhelm/feature-a", &["b1"]); + w.open_pr(1, "coderhelm/feature-a", "main", author); + w.open_pr(2, "coderhelm/feature-b", "coderhelm/feature-a", BOT); + Fake(Mutex::new(w)) +} + +/// The gate's last word before merging: it merges only into a live base, +/// as `await_merge::evaluate` does (checked below in its source). +async fn gate_merges(f: &Fake, n: u64, at: i64) -> bool { + let pr = f.0.lock().unwrap().pr(n).clone(); + match dead_base::gate(f, &pr).await.unwrap() { + Gate::Live => { + f.0.lock().unwrap().squash(n, BOT, at); + true + } + Gate::Moved { .. } | Gate::Held { .. } => false, + } +} + +fn main_has(f: &Fake, change: &str) -> bool { + f.0.lock().unwrap().content("main").contains(change) +} + +#[tokio::test] +async fn a_squash_merge_moves_the_stacked_pull_request_and_it_reaches_main() { + let f = stacked(BOT); + assert!(gate_merges(&f, 1, NOW - 2 * DAY).await); + let merged = f.0.lock().unwrap().pr(1).clone(); + let done = dead_base::on_merged(&f, &merged).await.unwrap(); + + assert_eq!(done.moved.len(), 1); + assert_eq!(done.moved[0].pr, 2); + assert_eq!(done.moved[0].to, "main"); + assert!(matches!(done.moved[0].base_in, BaseIn::Merged(_))); + assert!(done.deleted, "CoderHelm's merged branch goes"); + { + let w = f.0.lock().unwrap(); + assert_eq!(w.pr(2)["base"]["ref"], "main"); + assert_eq!(w.deleted, vec!["coderhelm/feature-a".to_string()]); + assert_eq!(w.reviewed.len(), 1, "reviewed again on its new base"); + assert!(w + .content("coderhelm/feature-b") + .is_superset(&w.content("main"))); + } + + // The review clears; the gate merges B, and B's change is on main. + assert!(gate_merges(&f, 2, NOW - DAY).await); + assert!(main_has(&f, "a1") && main_has(&f, "b1")); +} + +#[tokio::test] +async fn a_persons_merge_moves_its_stack_only_where_the_repository_says_so() { + let f = stacked(PERSON); + f.0.lock().unwrap().squash(1, PERSON, NOW - DAY); + let merged = f.0.lock().unwrap().pr(1).clone(); + let done = dead_base::on_merged(&f, &merged).await.unwrap(); + assert!(done.moved.is_empty() && !done.deleted); + + f.0.lock().unwrap().retarget_setting = true; + let done = dead_base::on_merged(&f, &merged).await.unwrap(); + assert_eq!(done.moved.len(), 1); + assert!( + !done.deleted, + "a person's branch is never CoderHelm's to delete" + ); +} + +#[tokio::test] +async fn the_gate_refuses_a_base_that_already_merged() { + let f = stacked(BOT); + // A merged, and no event moved B (the webhook was missed). + f.0.lock().unwrap().squash(1, BOT, NOW - 2 * DAY); + + assert!( + !gate_merges(&f, 2, NOW - DAY).await, + "never merged into a dead branch" + ); + { + let w = f.0.lock().unwrap(); + assert_eq!(w.pr(2)["state"], "open"); + assert_eq!(w.pr(2)["base"]["ref"], "main", "moved first"); + assert_eq!(w.reviewed.len(), 1, "and it waits for the review there"); + assert!(!w.content("main").contains("b1")); + } + // The review clears and the gate goes on: B reaches main. + assert!(gate_merges(&f, 2, NOW).await); + assert!(main_has(&f, "b1")); +} + +#[tokio::test] +async fn the_default_branch_is_never_looked_up() { + let f = stacked(BOT); + let a = f.0.lock().unwrap().pr(1).clone(); + assert_eq!(dead_base::gate(&f, &a).await.unwrap(), Gate::Live); + assert!(dead_base::live_by_name( + "release/2", + "main", + Some("release/2") + )); +} + +#[tokio::test] +async fn the_sweep_moves_what_still_sits_on_a_merged_branch() { + let f = stacked(BOT); + f.0.lock().unwrap().squash(1, BOT, NOW - 2 * DAY); + + let done = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert_eq!(done.moved.len(), 1); + assert_eq!(done.moved[0].pr, 2); + assert_eq!(done.moved[0].from, "coderhelm/feature-a"); + assert_eq!(done.moved[0].to, "main"); + assert!(done.landed.is_empty()); + assert_eq!(f.0.lock().unwrap().pr(2)["base"]["ref"], "main"); + // A second sweep finds nothing left to move. + let again = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert!(again.moved.is_empty()); +} + +/// The incident as it happened: A merged, then the gate merged B into A's +/// branch. +fn lost_merge() -> Fake { + let f = stacked(BOT); + let mut w = f.0.lock().unwrap(); + w.squash(1, BOT, NOW - 3 * DAY); + w.squash(2, BOT, NOW - 2 * DAY); + drop(w); + f +} + +#[tokio::test] +async fn a_lost_merge_gets_one_landing_pull_request() { + let f = lost_merge(); + assert!(!main_has(&f, "b1"), "the incident: B never reached main"); + + let done = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert_eq!(done.landed.len(), 1); + let (lost, landing) = done.landed[0]; + assert_eq!(lost, 2); + { + let w = f.0.lock().unwrap(); + let p = w.pr(landing); + assert_eq!(p["title"], "Land #2 on main"); + assert_eq!(p["base"]["ref"], "main"); + assert_eq!(p["head"]["ref"], "coderhelm/land-2"); + let body = p["body"].as_str().unwrap(); + assert!(body.contains("## Summary") && body.contains("## Verification")); + let branch = w.content("coderhelm/land-2"); + assert!(branch.contains("b1") && branch.is_superset(&w.content("main"))); + } + // Claimed: the next sweep opens nothing more. + let again = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert!(again.landed.is_empty()); + // Merging the landing pull request puts B's change on main. + f.0.lock().unwrap().squash(landing, BOT, NOW); + assert!(main_has(&f, "b1")); +} + +#[tokio::test] +async fn a_change_already_on_main_gets_no_landing_pull_request() { + let f = lost_merge(); + // Someone landed B's change on main by hand already. + { + let mut w = f.0.lock().unwrap(); + w.branch_with("main", "main", &["b1"]); + } + let done = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert!(done.landed.is_empty()); + assert_eq!(done.already, vec![2]); + let w = f.0.lock().unwrap(); + assert!(!w + .prs + .iter() + .any(|p| p["title"].as_str().is_some_and(|t| t.starts_with("Land #")))); +} + +#[tokio::test] +async fn landings_are_only_coderhelms_merges_inside_the_window_and_capped() { + // B merged into A's branch BEFORE A merged: A carried it to main. + let f = stacked(BOT); + { + let mut w = f.0.lock().unwrap(); + w.squash(2, BOT, NOW - 3 * DAY); + w.squash(1, BOT, NOW - 2 * DAY); + } + assert!(main_has(&f, "b1")); + let done = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert!(done.landed.is_empty() && done.already.is_empty()); + + // A person's merge into a dead branch is theirs. + let f = stacked(BOT); + { + let mut w = f.0.lock().unwrap(); + w.squash(1, BOT, NOW - 3 * DAY); + w.squash(2, PERSON, NOW - 2 * DAY); + } + assert!(dead_base::sweep_repo(&f, NOW) + .await + .unwrap() + .landed + .is_empty()); + + // Older than the window. + let f = stacked(BOT); + { + let mut w = f.0.lock().unwrap(); + w.squash(1, BOT, NOW - 40 * DAY); + w.squash(2, BOT, NOW - 35 * DAY); + } + assert!(dead_base::sweep_repo(&f, NOW) + .await + .unwrap() + .landed + .is_empty()); + + // Many lost merges: one sweep opens at most the cap. + let f = stacked(BOT); + { + let mut w = f.0.lock().unwrap(); + w.squash(1, BOT, NOW - 10 * DAY); + for i in 0..5u64 { + let b = format!("coderhelm/extra-{i}"); + w.branch_with(&b, "coderhelm/feature-a", &[&format!("x{i}")]); + w.open_pr(10 + i, &b, "coderhelm/feature-a", BOT); + w.squash(10 + i, BOT, NOW - 5 * DAY + i as i64); + } + } + let first = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert_eq!(first.landed.len(), dead_base::MAX_LANDINGS); + let second = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert_eq!(second.landed.len(), 5 - dead_base::MAX_LANDINGS); +} + +#[tokio::test] +async fn the_gate_holds_a_persons_merged_base_until_the_setting_says_move() { + let f = stacked(PERSON); + f.0.lock().unwrap().squash(1, PERSON, NOW - 2 * DAY); + + let pr = f.0.lock().unwrap().pr(2).clone(); + match dead_base::gate(&f, &pr).await.unwrap() { + Gate::Held { under, to } => assert_eq!((under, to.as_str()), (1, "main")), + other => panic!("held, not {other:?}"), + } + { + let w = f.0.lock().unwrap(); + assert_eq!( + w.pr(2)["state"], + "open", + "never merged into the dead branch" + ); + assert_eq!( + w.pr(2)["base"]["ref"], + "coderhelm/feature-a", + "and not moved: a person's stack is theirs" + ); + assert!(w.reviewed.is_empty()); + } + // The sweep leaves it too. + assert!(dead_base::sweep_repo(&f, NOW) + .await + .unwrap() + .moved + .is_empty()); + + f.0.lock().unwrap().retarget_setting = true; + let pr = f.0.lock().unwrap().pr(2).clone(); + assert!(matches!( + dead_base::gate(&f, &pr).await.unwrap(), + Gate::Moved { under: 1, .. } + )); + assert_eq!(f.0.lock().unwrap().pr(2)["base"]["ref"], "main"); +} + +/// `develop` is released into `main` by a person's pull request, and +/// CoderHelm's feature pull requests keep targeting `develop`. +fn released_develop() -> Fake { + let mut w = World::default(); + let root = w.commit(["m0".to_string()].into()); + w.branches.insert("main".to_string(), root); + w.branch_with("develop", "main", &["d1"]); + w.open_pr(1, "develop", "main", PERSON); + w.squash(1, PERSON, NOW - 5 * DAY); + w.branch_with("coderhelm/feature-x", "develop", &["x1"]); + w.open_pr(2, "coderhelm/feature-x", "develop", BOT); + w.retarget_setting = true; + Fake(Mutex::new(w)) +} + +async fn develop_stays(f: &Fake) { + assert!( + gate_merges(f, 2, NOW - DAY).await, + "merged into develop as asked" + ); + { + let w = f.0.lock().unwrap(); + assert_eq!(w.pr(2)["base"]["ref"], "develop"); + assert!(w.content("develop").contains("x1")); + } + let done = dead_base::sweep_repo(f, NOW).await.unwrap(); + assert!(done.moved.is_empty(), "nothing moved off develop"); + assert!( + done.landed.is_empty() && done.already.is_empty() && done.failed.is_empty(), + "a merge into develop is not lost" + ); +} + +#[tokio::test] +async fn a_protected_long_lived_base_is_still_read() { + let f = released_develop(); + f.0.lock().unwrap().protected.insert("develop".to_string()); + develop_stays(&f).await; +} + +#[tokio::test] +async fn a_base_an_open_pull_request_carries_on_is_still_read() { + let f = released_develop(); + // The next release is already open from develop. + f.0.lock().unwrap().open_pr(3, "develop", "main", PERSON); + develop_stays(&f).await; +} + +#[tokio::test] +async fn a_branch_merged_from_more_than_once_is_long_lived() { + let f = released_develop(); + { + let mut w = f.0.lock().unwrap(); + w.branch_with("develop", "develop", &["d2"]); + w.open_pr(3, "develop", "main", PERSON); + w.squash(3, PERSON, NOW - 3 * DAY); + } + develop_stays(&f).await; +} + +#[tokio::test] +async fn a_long_lived_release_merging_moves_nothing_based_on_it() { + // Protected develop released: what targets develop stays there. + let f = released_develop(); + f.0.lock().unwrap().protected.insert("develop".to_string()); + let release = f.0.lock().unwrap().pr(1).clone(); + let done = dead_base::on_merged(&f, &release).await.unwrap(); + assert!(done.moved.is_empty() && !done.deleted); + assert_eq!(f.0.lock().unwrap().pr(2)["base"]["ref"], "develop"); + + // Unprotected, but released a second time: long-lived all the same. + let f = released_develop(); + { + let mut w = f.0.lock().unwrap(); + w.branch_with("develop", "develop", &["d2"]); + w.open_pr(3, "develop", "main", PERSON); + w.squash(3, PERSON, NOW - DAY); + } + let release = f.0.lock().unwrap().pr(3).clone(); + let done = dead_base::on_merged(&f, &release).await.unwrap(); + assert!(done.moved.is_empty()); + assert_eq!(f.0.lock().unwrap().pr(2)["base"]["ref"], "develop"); +} + +#[tokio::test] +async fn a_failed_landing_gives_its_claim_back_and_lands_next_sweep() { + // Opening the landing pull request fails once. + let f = lost_merge(); + f.0.lock().unwrap().fail_opens = 1; + let first = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert!(first.landed.is_empty()); + assert_eq!(first.failed, vec![2]); + { + let w = f.0.lock().unwrap(); + assert!(w.claims.is_empty(), "the claim goes back"); + assert!( + !w.branches.contains_key("coderhelm/land-2"), + "no landing branch left without a pull request" + ); + } + let second = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert_eq!(second.landed.len(), 1); + assert_eq!(second.landed[0].0, 2); + + // The pick fails once, for the first of two lost merges: the other + // still lands in the same sweep, and the first one next sweep. + let f = lost_merge(); + { + let mut w = f.0.lock().unwrap(); + w.branch_with("coderhelm/extra", "coderhelm/feature-a", &["e1"]); + w.open_pr(3, "coderhelm/extra", "coderhelm/feature-a", BOT); + w.squash(3, BOT, NOW - DAY); + w.fail_picks = 1; + } + let first = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert_eq!(first.failed, vec![2]); + assert_eq!( + first.landed.iter().map(|l| l.0).collect::>(), + vec![3] + ); + let second = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert_eq!( + second.landed.iter().map(|l| l.0).collect::>(), + vec![2] + ); + let third = dead_base::sweep_repo(&f, NOW).await.unwrap(); + assert!(third.landed.is_empty(), "each landing once"); +} + +#[test] +fn the_pipeline_calls_the_stack_code_where_it_matters() { + let gate = fn_src(include_str!("../await_merge.rs"), "async fn evaluate("); + let check = gate + .find("dead_base::gate(") + .expect("the gate checks the base"); + let merge = gate.find("merge(\n").expect("the gate merges"); + assert!(check < merge, "the base is checked before any merge"); + + let hook = include_str!("../../../../gateway/src/routes/github_webhook.rs"); + assert!(hook.contains("WorkerMessage::StackMerged(")); + let main = include_str!("../../main.rs"); + assert!(main.contains("dead_base::after_merge(")); + let watch = fn_src(include_str!("../pr_watch.rs"), "pub async fn sweep("); + assert!(watch.contains("dead_base::sweep(")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 01d09a396..cf69cfb31 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1302,6 +1302,7 @@ pub mod conversation; mod covering; mod cross_repo; pub mod customer_guard; +pub mod dead_base; pub mod dep_fix; /// The repository's deploy label, read for the preview of CoderHelm's own /// pull request and the auto-merge gate (`common::deploy_label`). diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 46c61d5b9..570d8ad9c 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -1392,6 +1392,10 @@ pub struct SweepReport { /// `owner/repo#pr` for each pull request whose file modes, dropped by /// an earlier CoderHelm commit, were put back (`mode_repair`). pub modes_restored: Vec, + /// `owner/repo: what` for each repository where a pull request moved + /// off a merged branch or a lost merge got its landing pull request + /// (`dead_base::sweep`). + pub stacks_mended: Vec, } /// The sweep's scan: finished runs with a pull request, changed inside the @@ -1473,6 +1477,10 @@ pub async fn sweep(state: &WorkerState) -> SweepReport { // Open pull requests whose executables or links an earlier CoderHelm // commit turned into plain files get their modes back, once each. report.modes_restored = super::mode_repair::sweep(state, &mut budget, &mut clients).await; + // Pull requests still based on a branch that already merged move to its + // base, and a change merged into such a branch gets its landing pull + // request. + report.stacks_mended = super::dead_base::sweep(state, &mut budget, &mut clients).await; report.skipped_installations = budget.skipped(); report.retry_in = budget.retry_in(); report diff --git a/services/worker/src/passes/review_actions.rs b/services/worker/src/passes/review_actions.rs index 4eabd050f..cfc6d63a6 100644 --- a/services/worker/src/passes/review_actions.rs +++ b/services/worker/src/passes/review_actions.rs @@ -55,6 +55,10 @@ pub struct OnApproveConfig { /// The repo reviews every person's pull request, labelled or not /// (`common::review_config::Trigger::EveryPr`): each is opted in. pub review_every_pr: bool, + /// When a person's pull request merges, CoderHelm also moves the open + /// pull requests stacked on its branch to its base (it always does for + /// its own, `dead_base::may_retarget`). + pub retarget_stacked: bool, } impl Default for OnApproveConfig { @@ -71,6 +75,7 @@ impl Default for OnApproveConfig { deploy_label: String::new(), review_label: "ch-review".to_string(), review_every_pr: false, + retarget_stacked: false, } } } @@ -167,6 +172,7 @@ impl OnApproveConfig { review_label, review_every_pr: common::review_config::Trigger::of(&item) == common::review_config::Trigger::EveryPr, + retarget_stacked: get_bool("retarget_stacked", d.retarget_stacked), }) } } diff --git a/services/worker/src/passes/stack.rs b/services/worker/src/passes/stack.rs index 21cc9ac09..33d1a13aa 100644 --- a/services/worker/src/passes/stack.rs +++ b/services/worker/src/passes/stack.rs @@ -77,9 +77,9 @@ impl Dependency { format!( "## Builds on #{n}\n\nThis pull request is stacked on #{n} (`{b}`, \"{t}\"): its \ base is that branch, so its diff shows only this ticket's change. {why}\n\n\ - Merge order: #{n} first, then this one. When #{n} merges, GitHub moves this pull \ - request's base to #{n}'s base; if it then needs a rebase, comment \"rebase\" on \ - it and CoderHelm brings it up to date." + Merge order: #{n} first, then this one. When #{n} merges, CoderHelm moves this pull \ + request's base to #{n}'s base, merges that base into it and reviews it there \ + before it merges; it never merges into `{b}` once #{n} has merged." ) }; if !self.unresolved.is_empty() {