Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/incidents/xn_stacked_merge_reaches_main.md
Original file line number Diff line number Diff line change
@@ -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`.
1 change: 1 addition & 0 deletions services/common/contract/worker_messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
Expand Down
2 changes: 2 additions & 0 deletions services/common/src/dlq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
17 changes: 17 additions & 0 deletions services/common/src/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down Expand Up @@ -513,6 +518,7 @@ impl WorkerMessage {
| WorkerMessage::RunWaiting(_)
| WorkerMessage::RoleReadsWait(_)
| WorkerMessage::ChangeWaitCheck(_)
| WorkerMessage::StackMerged(_)
| WorkerMessage::LogAutofix
| WorkerMessage::AwsPermissionsSweep
| WorkerMessage::HybridNameCheck
Expand Down Expand Up @@ -595,6 +601,7 @@ impl WorkerMessage {
| WorkerMessage::RunWaiting(_)
| WorkerMessage::RoleReadsWait(_)
| WorkerMessage::ChangeWaitCheck(_)
| WorkerMessage::StackMerged(_)
| WorkerMessage::PluginRun(_)
| WorkerMessage::PluginPublish(_)
| WorkerMessage::PluginSync(_)
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 4 additions & 0 deletions services/common/src/review_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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"],
Expand All @@ -395,6 +398,7 @@ mod tests {
"auto_merge",
"merge_method",
"require_human_approval",
"retarget_stacked",
"tag_mode",
"tag_prefix",
"tag_batch_minutes",
Expand Down
39 changes: 39 additions & 0 deletions services/gateway/src/routes/github_webhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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<common::messages::StackMergedMessage> {
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,
Expand Down
19 changes: 19 additions & 0 deletions services/worker/src/clients/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<serde_json::Value>, Box<dyn std::error::Error + Send + Sync>> {
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.
Expand Down
8 changes: 8 additions & 0 deletions services/worker/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -972,6 +972,14 @@ async fn handle_message_inner(state: Arc<WorkerState>, 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 {
Expand Down
76 changes: 76 additions & 0 deletions services/worker/src/passes/await_merge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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,
Expand Down
Loading