diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index 0b652e4ce..3b38863b0 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -56,6 +56,7 @@ "review_fix": "review fix round", "feedback": "feedback round", "security_fix": "security fix round", + "conflict_fix": "conflict round", } _dynamodb = None @@ -143,8 +144,8 @@ def round_kind(run, pass_name): return "ci_fix" if p == "feedback": return "feedback" - if p == "security_fix": - return "security_fix" + if p in ("security_fix", "conflict_fix"): + return p return "review_fix" diff --git a/services/common/src/merge_gate.rs b/services/common/src/merge_gate.rs index 67d316fda..30676b404 100644 --- a/services/common/src/merge_gate.rs +++ b/services/common/src/merge_gate.rs @@ -47,10 +47,22 @@ pub const STATE_MERGED: &str = "merged"; pub const STATE_CLOSED: &str = "closed"; /// A new commit arrived; the review of that commit re-arms the gate. pub const STATE_HEAD_MOVED: &str = "head_moved"; +/// The PR conflicts with its base. The gate stops: no poll, no completed +/// check suite and no repeated status edit can clear a conflict. CoderHelm +/// updates its own PR's branch once (a resumable round on the run); the +/// review of the new commit re-arms the gate. Otherwise a person resolves it. +pub const STATE_CONFLICT: &str = "conflict"; /// A person stopped auto-merge (a PR comment or the dashboard). Nothing /// wakes it, not CI, a review or a new commit; only a person re-arms it. pub const STATE_STOPPED: &str = "stopped"; +/// Whether GitHub's reading of a pull request is a merge conflict with its +/// base: `mergeable` false with `mergeable_state` "dirty". Branch protection +/// and checks GitHub still counts as missing are "blocked", not a conflict. +pub fn is_conflict(pr: &serde_json::Value) -> bool { + pr["mergeable_state"].as_str() == Some("dirty") && pr["mergeable"].as_bool() != Some(true) +} + /// Should a completed check suite on the gate's head re-arm it? Only while /// the gate is waiting on (or was stopped by) CI or GitHub's merge rules. pub fn wakes_on_ci(state: &str) -> bool { @@ -689,6 +701,19 @@ mod tests { } } + /// A conflict is never polled: CI can't clear it. The review of a new + /// commit (the head moves) is what re-arms the gate. + #[test] + fn a_conflict_stops_the_gate_until_a_new_commit() { + assert!(!wakes_on_ci(STATE_CONFLICT)); + assert!(wakes_on_review(STATE_CONFLICT)); + let pr = |m: serde_json::Value, st: &str| serde_json::json!({"mergeable": m, "mergeable_state": st}); + assert!(is_conflict(&pr(serde_json::json!(false), "dirty"))); + assert!(!is_conflict(&pr(serde_json::json!(true), "blocked"))); + assert!(!is_conflict(&pr(serde_json::json!(false), "blocked"))); + assert!(!is_conflict(&pr(serde_json::Value::Null, "unknown"))); + } + #[test] fn a_stopped_gate_wakes_on_nothing() { // No CI run, review, approval or new commit re-arms a person's stop. diff --git a/services/common/src/plugins/kv.rs b/services/common/src/plugins/kv.rs index ed5b1386a..c440519ba 100644 --- a/services/common/src/plugins/kv.rs +++ b/services/common/src/plugins/kv.rs @@ -250,6 +250,26 @@ fn rec_of(i: &HashMap) -> Option { Some(Rec { sk, data, rev }) } +/// The key condition for a query: the whole partition when `prefix` is +/// empty. DynamoDB refuses an empty string as an attribute value ("empty +/// string value. Key: sk"), so `begins_with(sk, "")` can never be sent. +fn key_condition(prefix: &str) -> &'static str { + if prefix.is_empty() { + "pk = :p" + } else { + "pk = :p AND begins_with(sk, :s)" + } +} + +/// The values [`key_condition`] names, never an empty string. +fn key_values(pk: &str, prefix: &str) -> HashMap { + let mut v = HashMap::from([(":p".to_string(), s(pk))]); + if !prefix.is_empty() { + v.insert(":s".to_string(), s(prefix)); + } + v +} + #[async_trait::async_trait] impl Kv for Dynamo { async fn get(&self, pk: &str, sk: &str) -> Result, String> { @@ -324,9 +344,8 @@ impl Kv for Dynamo { .client .query() .table_name(&self.table) - .key_condition_expression("pk = :p AND begins_with(sk, :s)") - .expression_attribute_values(":p", s(pk)) - .expression_attribute_values(":s", s(prefix)) + .key_condition_expression(key_condition(prefix)) + .set_expression_attribute_values(Some(key_values(pk, prefix))) .scan_index_forward(!reverse) .set_exclusive_start_key(start.take()); if let Some(n) = limit { @@ -404,4 +423,48 @@ mod tests { m.delete("t", "A#1").await.unwrap(); assert_eq!(m.get("t", "A#1").await.unwrap(), None); } + + /// The plugin source poll lists a whole index partition with an empty + /// prefix; the query must name only non-empty values, or DynamoDB + /// refuses it and no source is ever polled. + #[test] + fn an_empty_prefix_queries_the_whole_partition_with_no_empty_value() { + let cond = key_condition(""); + assert_eq!(cond, "pk = :p"); + let v = key_values(SOURCE_INDEX, ""); + assert_eq!(v.len(), 1); + assert!(v + .values() + .all(|a| a.as_s().map(|t| !t.is_empty()).unwrap_or(false))); + for name in v.keys() { + assert!(cond.contains(name.as_str())); + } + + let cond = key_condition("team|"); + assert!(cond.contains("begins_with(sk, :s)")); + let v = key_values("t", "team|"); + assert_eq!( + v.get(":s").and_then(|a| a.as_s().ok()).map(String::as_str), + Some("team|") + ); + } + + #[tokio::test] + async fn every_source_is_listed_for_the_poll() { + let m = Memory::new(); + m.put(SOURCE_INDEX, "t1|a", &json!({}), Expect::Any) + .await + .unwrap(); + m.put(SOURCE_INDEX, "t2|b", &json!({}), Expect::Any) + .await + .unwrap(); + let all = crate::plugins::source::all(&m).await.unwrap(); + assert_eq!( + all, + vec![ + ("t1".to_string(), "a".to_string()), + ("t2".to_string(), "b".to_string()) + ] + ); + } } diff --git a/services/common/src/review_live.rs b/services/common/src/review_live.rs index 6c941cfba..ff3841f82 100644 --- a/services/common/src/review_live.rs +++ b/services/common/src/review_live.rs @@ -93,6 +93,7 @@ pub fn pr_status(review_phase: &str, gate_state: &str) -> PrStatus { g::STATE_BLOCKED_CI => return st("ci_failing", GROUP_WAITING), g::STATE_WAITING_APPROVAL => return st("waiting_people", GROUP_WAITING), g::STATE_DECLINED => return st("merge_blocked", GROUP_WAITING), + g::STATE_CONFLICT => return st("merge_conflict", GROUP_WAITING), g::STATE_PAUSED => return st("paused", GROUP_WAITING), // Waits on a person to re-arm it. g::STATE_STOPPED => return st("stopped", GROUP_WAITING), @@ -451,6 +452,7 @@ mod tests { (g::STATE_BLOCKED_CI, "ci_failing", GROUP_WAITING), (g::STATE_WAITING_APPROVAL, "waiting_people", GROUP_WAITING), (g::STATE_DECLINED, "merge_blocked", GROUP_WAITING), + (g::STATE_CONFLICT, "merge_conflict", GROUP_WAITING), (g::STATE_PAUSED, "paused", GROUP_WAITING), (g::STATE_STOPPED, "stopped", GROUP_WAITING), (g::STATE_MERGED, "merged", GROUP_DONE), diff --git a/services/common/src/run_round.rs b/services/common/src/run_round.rs index 4421e4dde..86f50fd59 100644 --- a/services/common/src/run_round.rs +++ b/services/common/src/run_round.rs @@ -78,6 +78,10 @@ pub enum Kind { /// pull request in a fresh invocation, and the pull request stays a /// draft until the issues are gone. SecurityFix, + /// The pull request conflicts with its base and auto-merge stopped on + /// it: CoderHelm merges the base into its own pull request's branch, + /// once (`await_merge`). + Conflict, } impl Kind { @@ -87,6 +91,7 @@ impl Kind { Kind::ReviewFix => "review_fix", Kind::Feedback => "feedback", Kind::SecurityFix => "security_fix", + Kind::Conflict => "conflict_fix", } } @@ -96,6 +101,7 @@ impl Kind { "review_fix" => Some(Kind::ReviewFix), "feedback" => Some(Kind::Feedback), "security_fix" => Some(Kind::SecurityFix), + "conflict_fix" => Some(Kind::Conflict), _ => None, } } @@ -107,6 +113,7 @@ impl Kind { "ci_fix" | "test" => Kind::CiFix, "feedback" => Kind::Feedback, "security_fix" => Kind::SecurityFix, + "conflict_fix" => Kind::Conflict, _ => Kind::ReviewFix, } } @@ -118,6 +125,7 @@ impl Kind { Kind::ReviewFix => "review fix round", Kind::Feedback => "feedback round", Kind::SecurityFix => "security fix round", + Kind::Conflict => "conflict round", } } } diff --git a/services/common/src/run_status.rs b/services/common/src/run_status.rs index a7b38987e..d4d6a8766 100644 --- a/services/common/src/run_status.rs +++ b/services/common/src/run_status.rs @@ -61,6 +61,10 @@ pub fn ended_by_person(status: &str) -> bool { ENDED_BY_PERSON.contains(&status) } +/// The lesson trigger for a person's answer to "why was this closed?" on +/// CoderHelm's PR (the gateway sends it, the worker's lessons read it). +pub const CLOSE_REASON_TRIGGER: &str = "close_reason"; + /// The condition that refuses to overwrite a run a person ended, for the /// status attribute behind `status_name` (`#s`, `#status`). Add its values /// with [`EndedValues::ended_values`]. diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 232023cc3..8f86285f4 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -294,6 +294,11 @@ async fn main() -> Result<(), Error> { get(routes::knowledge_tokens::sign_in_apps), ) .route("/admin/dlq/delete", post(routes::admin::admin_dlq_delete)) + // A GitHub installation several teams carry: release the stale links + .route( + "/admin/installations/:installation_id/release-stale", + post(routes::admin::release_stale_installation_links), + ) .route("/admin/beta-signups", get(routes::admin::beta_signups)) .route( "/admin/beta-signups/invite", @@ -503,6 +508,10 @@ async fn main() -> Result<(), Error> { "/github/installation-status", get(routes::github::installation_status), ) + .route( + "/github/release-stale-link", + post(routes::github::release_stale_link), + ) .route( "/notifications", get(routes::api::get_notification_prefs).put(routes::api::update_notification_prefs), diff --git a/services/gateway/src/routes/admin.rs b/services/gateway/src/routes/admin.rs index d7ea46c83..8be8bb6d4 100644 --- a/services/gateway/src/routes/admin.rs +++ b/services/gateway/src/routes/admin.rs @@ -788,6 +788,28 @@ pub async fn admin_teams( } } } + // Installations several teams carry: who receives their events, and + // which links are stale (a warning on the page, with a way to release). + let links: Vec<(String, u64)> = teams + .iter() + .filter_map(|t| { + t.installation_id + .trim() + .parse::() + .ok() + .map(|iid| (t.team_id.clone(), iid)) + }) + .collect(); + let mut shared_installations: Vec = Vec::new(); + for (iid, team_ids) in super::installation_owner::shared(&links) { + let owner = super::github_webhook::resolve_team_by_installation(&state, iid).await; + shared_installations.push(json!({ + "installation_id": iid, + "owner_team_id": owner, + "stale_team_ids": super::installation_owner::stale_teams(&team_ids, owner.as_deref()), + })); + } + shared_installations.sort_by_key(|v| v["installation_id"].as_u64()); let flat: Vec = orgs .iter() .flat_map(|o| o["teams"].as_array().cloned().unwrap_or_default()) @@ -797,6 +819,7 @@ pub async fn admin_teams( "month": month, "orgs": orgs, "teams": flat, + "shared_installations": shared_installations, "counts": { "teams": teams.len(), "orgs": orgs.len(), @@ -806,6 +829,58 @@ pub async fn admin_teams( }))) } +#[derive(serde::Deserialize, Default)] +pub struct ReleaseStaleRequest { + /// Say what would be released without changing anything (the default). + #[serde(default = "yes")] + pub dry_run: bool, +} + +fn yes() -> bool { + true +} + +/// POST /api/admin/installations/:installation_id/release-stale { dry_run } +/// — removes the installation's link from every team that carries it but +/// doesn't own it (platform admins only). The owner keeps its link. A dry +/// run (the default) only lists them. +pub async fn release_stale_installation_links( + State(state): State>, + Extension(claims): Extension, + axum::extract::Path(installation_id): axum::extract::Path, + body: Option>, +) -> Result, StatusCode> { + if !is_platform_admin(&claims) { + warn!(email = %claims.email, "Installation link release refused: not a platform admin"); + return Err(StatusCode::FORBIDDEN); + } + let dry_run = body.map(|Json(b)| b.dry_run).unwrap_or(true); + let teams = + super::github_webhook::resolve_all_teams_by_installation(&state, installation_id).await; + let owner = super::github_webhook::resolve_team_by_installation(&state, installation_id).await; + let stale = super::installation_owner::stale_teams(&teams, owner.as_deref()); + let mut released: Vec = Vec::new(); + if !dry_run && owner.is_some() { + for team in &stale { + match super::installation_owner::release_stale(&state, team, installation_id).await { + Ok(true) => released.push(team.clone()), + Ok(false) => {} + Err(e) => { + warn!(team, installation_id, error = %e, "Could not release a stale link") + } + } + } + info!(installation_id, released = ?released, by = %claims.email, "Stale installation links released"); + } + Ok(Json(json!({ + "installation_id": installation_id, + "owner_team_id": owner, + "stale_team_ids": stale, + "dry_run": dry_run, + "released": released, + }))) +} + /// PUT /api/admin/teams/:team_id/flags { plugins } — turns a team's /// feature flags on or off (platform admins only). pub async fn set_team_flags( @@ -1320,6 +1395,6 @@ mod tests { ); checked += 1; } - assert_eq!(checked, 7); + assert_eq!(checked, 8); } } diff --git a/services/gateway/src/routes/github.rs b/services/gateway/src/routes/github.rs index c71abbce2..ef7da3df8 100644 --- a/services/gateway/src/routes/github.rs +++ b/services/gateway/src/routes/github.rs @@ -142,15 +142,90 @@ pub async fn installation_status( .map(|s| s.to_string()); match (installation_id, github_org) { - (Some(id), Some(org)) => Ok(Json(json!({ - "status": "connected", - "github_org": org, - "installation_id": id, - }))), + (Some(id), Some(org)) => { + // Another team receives this installation's events: this team's + // link is stale (an older sign-in's team). Its admins see that + // and can release it. + let owner = super::github_webhook::resolve_team_by_installation(&state, id).await; + if owner.as_deref().is_some_and(|o| o != claims.team_id) { + return Ok(Json(json!({ + "status": "stale", + "github_org": org, + "installation_id": id, + "message": stale_message(&org), + }))); + } + Ok(Json(json!({ + "status": "connected", + "github_org": org, + "installation_id": id, + }))) + } _ => Ok(Json(json!({ "status": "not_connected" }))), } } +/// What a team whose link is stale is told. +fn stale_message(org: &str) -> String { + format!( + "Another CoderHelm team receives the events of the GitHub installation for {org}, so \ + this team's link to it does nothing. An admin can remove this team's link, or ask that \ + team's admin for an invite." + ) +} + +/// POST /api/github/release-stale-link +/// +/// Removes this team's link to its GitHub installation when another team +/// owns that installation (the link is stale). Admins only. The owner's link +/// is never touched, and a team that owns its installation keeps it. +pub async fn release_stale_link( + State(state): State>, + Extension(claims): Extension, +) -> Result, StatusCode> { + if role_to_level(&claims.role) < 3 { + return Err(StatusCode::FORBIDDEN); + } + let item = state + .dynamo + .get_item() + .table_name(&state.config.teams_table_name) + .key("team_id", attr_s(&claims.team_id)) + .key("sk", attr_s("META")) + .send() + .await + .map_err(|e| { + error!("Failed to fetch team: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + let Some(installation_id) = item + .item() + .and_then(|i| i.get("github_installation_id")) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + else { + return Ok(Json( + json!({ "released": false, "reason": "This team has no GitHub installation linked." }), + )); + }; + match super::installation_owner::release_stale(&state, &claims.team_id, installation_id).await { + Ok(true) => { + info!(team_id = %claims.team_id, installation_id, by = %claims.email, "Stale GitHub installation link released"); + Ok(Json( + json!({ "released": true, "installation_id": installation_id }), + )) + } + Ok(false) => Ok(Json(json!({ + "released": false, + "reason": "This team's link isn't stale: no other team owns its installation.", + }))), + Err(e) => { + error!(team_id = %claims.team_id, installation_id, error = %e, "Could not release the stale link"); + Err(StatusCode::INTERNAL_SERVER_ERROR) + } + } +} + /// Verify an installation exists and belongs to our GitHub App. /// Returns (org_login, account_id). async fn verify_installation( @@ -335,3 +410,13 @@ mod tests { ); } } + +#[cfg(test)] +mod stale_tests { + #[test] + fn a_stale_link_says_what_to_do() { + let m = super::stale_message("acme"); + assert!(m.contains("for acme")); + assert!(m.contains("remove this team's link")); + } +} diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index f415416e7..e7c0cf190 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -51,6 +51,17 @@ pub async fn resolve_team_by_installation( // fresh team per person). Pick the OWNER deterministically — never // whichever DynamoDB lists first, which routed webhooks to the wrong team. if items.len() > 1 { + let team_ids: Vec = items + .iter() + .filter_map(|i| i.get("team_id").and_then(|v| v.as_s().ok()).cloned()) + .collect(); + // The owner, once chosen, is recorded and stands (one read, no + // member counts per event, no owner that moves when people join). + let recorded = super::installation_owner::recorded(state, installation_id).await; + if let Some(owner) = super::installation_owner::choose(&team_ids, recorded.as_deref(), None) + { + return Some(owner); + } let mut candidates: Vec = items .iter() .filter_map(|item| { @@ -89,13 +100,26 @@ pub async fn resolve_team_by_installation( }; } } - let owner = pick_installation_owner(&candidates); + let picked = pick_installation_owner(&candidates); + let rule = if candidates.iter().any(|c| c.linked_at.is_some()) { + "first_link" + } else { + "most_members" + }; + let owner = match picked { + Some(p) => Some( + super::installation_owner::record(state, installation_id, &p, &team_ids, rule) + .await, + ), + None => None, + }; if first_time_seen_shared(installation_id) { - tracing::debug!( + tracing::warn!( installation_id, team_count = candidates.len(), owner = owner.as_deref().unwrap_or(""), - "Installation is linked to several teams — routing to its owner" + rule, + "Installation is linked to several teams: routing to its recorded owner; the other links are stale (Teams page in admin)" ); } return owner; @@ -1249,6 +1273,33 @@ async fn handle_issue_comment( let name = repo["name"].as_str().unwrap_or(""); let pr_number = payload["issue"]["number"].as_u64().unwrap_or(0); + // The answer to CoderHelm's one question on a PR closed without + // a reason: it goes to the lessons, never to the fix loop. + if payload["issue"]["state"].as_str() == Some("closed") { + if let Some(item) = + lookup_run_item_by_pr(state, team_id, owner, name, pr_number).await + { + if awaits_close_reason(&item) { + let lesson = WorkerMessage::Lesson(crate::models::LessonMessage { + team_id: team_id.to_string(), + installation_id, + run_id: common::paged::run_id_of(&item).unwrap_or_default(), + repo_owner: owner.to_string(), + repo_name: name.to_string(), + pr_number, + trigger: common::run_status::CLOSE_REASON_TRIGGER.to_string(), + ..Default::default() + }); + if let Err(e) = + send_to_queue(state, &state.config.ticket_queue_url, &lesson).await + { + warn!(pr_number, status = ?e, "Could not queue the close reason's lesson"); + } + return Ok(StatusCode::OK); + } + } + } + let run_id = lookup_run_by_pr(state, team_id, owner, name, pr_number).await; if run_id.is_empty() { warn!(pr_number, "No run found for PR comment — skipping"); @@ -1635,7 +1686,10 @@ async fn handle_pull_request( ); // Learn from it: the worker reads the ticket, the plan's findings // and what people wrote, and records a lesson for the repository - // when the fix belonged outside the code. + // when the fix belonged outside the code; when nobody said why, + // it asks once. A PR CoderHelm closed itself (superseded, the fix + // belonged elsewhere) already says why. + let closed_by_us = is_own_actor(&payload["sender"]); let lesson = WorkerMessage::Lesson(crate::models::LessonMessage { team_id: team_id.to_string(), installation_id, @@ -1646,7 +1700,14 @@ async fn handle_pull_request( trigger: "pr_closed".to_string(), ..Default::default() }); - if let Err(e) = send_to_queue(state, &state.config.ticket_queue_url, &lesson).await { + if closed_by_us { + info!( + team_id, + run_id, pr_number, "CoderHelm closed its own PR — no lesson to ask for" + ); + } else if let Err(e) = + send_to_queue(state, &state.config.ticket_queue_url, &lesson).await + { warn!(team_id, run_id, pr_number, status = ?e, "Could not queue the closed PR's lesson"); } queue_reward_outcome( @@ -1762,6 +1823,19 @@ async fn handle_pull_request( Ok(StatusCode::OK) } +/// Whether a webhook's sender is CoderHelm itself (its app or bot user). +fn is_own_actor(sender: &Value) -> bool { + sender["login"] + .as_str() + .is_some_and(|l| l.to_ascii_lowercase().contains("coderhelm")) +} + +/// Whether CoderHelm asked why this run's PR was closed and nobody has +/// answered yet. +fn awaits_close_reason(item: &common::paged::Item) -> bool { + item.contains_key("close_asked_at") && !item.contains_key("close_answered_at") +} + /// A multi-repo run's PR that isn't the one its record names closed: its /// entry in `prs` gets the outcome, and it is scored and learned from like /// any other (with its own repository and number). @@ -4599,3 +4673,30 @@ mod rerequest_tests { assert!(a.contains("abc123")); } } + +#[cfg(test)] +mod close_reason_tests { + use super::*; + use aws_sdk_dynamodb::types::AttributeValue; + + /// A comment on a closed PR is the answer only while CoderHelm's one + /// question is open; after that it is ordinary conversation. + #[test] + fn only_an_open_question_takes_the_answer() { + let mut item: common::paged::Item = std::collections::HashMap::new(); + assert!(!awaits_close_reason(&item)); + item.insert("close_asked_at".into(), AttributeValue::S("t".into())); + assert!(awaits_close_reason(&item)); + item.insert("close_answered_at".into(), AttributeValue::S("t".into())); + assert!(!awaits_close_reason(&item)); + } + + #[test] + fn coderhelm_closing_its_own_pr_is_not_asked_about() { + assert!(is_own_actor( + &serde_json::json!({"login": "coderhelm[bot]"}) + )); + assert!(!is_own_actor(&serde_json::json!({"login": "pat"}))); + assert!(!is_own_actor(&serde_json::json!({}))); + } +} diff --git a/services/gateway/src/routes/installation_owner.rs b/services/gateway/src/routes/installation_owner.rs new file mode 100644 index 000000000..00c270391 --- /dev/null +++ b/services/gateway/src/routes/installation_owner.rs @@ -0,0 +1,252 @@ +//! Which team owns a GitHub installation that several teams carry. +//! +//! Older sign-ins created a team per person, and each one linked the org's +//! installation, so one installation can sit on several team records. Only +//! one of them may receive its events. The rule (see +//! [`super::github_webhook::pick_installation_owner`]) picks the first team +//! to link it, or for records from before link times the team with the most +//! members. Member counts change, so that answer could move from one team +//! to another between two webhooks; it also cost a query per team on every +//! event. The owner is now kept as a record of its own (settings table, +//! `INSTALLATION#` / `OWNER`), written once when the choice is first +//! made, and every later resolution reads it. +//! +//! The other teams' links are stale. Linking already refuses an +//! installation another team owns (auth::github_callback), so no new stale +//! link is made; the old ones are shown to platform admins (the Teams page) +//! and to the stale team's own admins (installation status), and either can +//! release them. Releasing removes only the stale team's link, never the +//! owner's, and only while that team still carries this installation. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use tracing::warn; + +use crate::AppState; + +const SK: &str = "OWNER"; + +fn pk(installation_id: u64) -> String { + format!("INSTALLATION#{installation_id}") +} + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +/// The owner to route to: the recorded one while it still carries the +/// installation, else `picked` (the rule's choice from the same records). +pub fn choose( + team_ids: &[String], + recorded: Option<&str>, + picked: Option, +) -> Option { + match recorded { + Some(r) if team_ids.iter().any(|t| t == r) => Some(r.to_string()), + _ => picked, + } +} + +/// The teams that carry the installation but don't own it. +pub fn stale_teams(team_ids: &[String], owner: Option<&str>) -> Vec { + let mut out: Vec = team_ids + .iter() + .filter(|t| Some(t.as_str()) != owner) + .cloned() + .collect(); + out.sort(); + out.dedup(); + out +} + +/// The recorded owner, if any. A failed read is none (the rule decides). +pub async fn recorded(state: &AppState, installation_id: u64) -> Option { + state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", s(&pk(installation_id))) + .key("sk", s(SK)) + .consistent_read(true) + .send() + .await + .ok()? + .item() + .and_then(|i| i.get("team_id")) + .and_then(|v| v.as_s().ok()) + .cloned() +} + +/// Records `team_id` as the owner unless one is recorded that still carries +/// the installation; returns the owner that stands. +pub async fn record( + state: &AppState, + installation_id: u64, + team_id: &str, + team_ids: &[String], + rule: &str, +) -> String { + let current = recorded(state, installation_id).await; + if let Some(c) = current + .as_deref() + .filter(|c| team_ids.iter().any(|t| t == c)) + { + return c.to_string(); + } + let mut put = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", s(&pk(installation_id))) + .item("sk", s(SK)) + .item("team_id", s(team_id)) + .item("rule", s(rule)) + .item("decided_at", s(&chrono::Utc::now().to_rfc3339())); + // Replace only what was read: two webhooks deciding at once agree on one. + put = match ¤t { + Some(c) => put + .condition_expression("team_id = :old") + .expression_attribute_values(":old", s(c)), + None => put.condition_expression("attribute_not_exists(pk)"), + }; + match put.send().await { + Ok(_) => team_id.to_string(), + Err(e) => { + if !common::run_fail::is_condition_failed(&e) { + warn!(installation_id, error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Could not record the installation's owner"); + return team_id.to_string(); + } + recorded(state, installation_id) + .await + .unwrap_or_else(|| team_id.to_string()) + } + } +} + +/// Removes `team_id`'s link to `installation_id` (both tables), only while +/// the team still carries that installation and isn't its owner. Returns +/// whether a link was removed. +pub async fn release_stale( + state: &AppState, + team_id: &str, + installation_id: u64, +) -> Result { + let owner = super::github_webhook::resolve_team_by_installation(state, installation_id).await; + if owner.as_deref() == Some(team_id) || owner.is_none() { + return Ok(false); + } + let now = chrono::Utc::now().to_rfc3339(); + let res = state + .dynamo + .update_item() + .table_name(&state.config.teams_table_name) + .key("team_id", s(team_id)) + .key("sk", s("META")) + .update_expression( + "REMOVE github_installation_id, github_org, installation_linked_at \ + SET updated_at = :t, installation_released_at = :t, installation_released = :iid", + ) + .condition_expression("github_installation_id = :iid") + .expression_attribute_values(":iid", AttributeValue::N(installation_id.to_string())) + .expression_attribute_values(":t", s(&now)) + .send() + .await; + match res { + Ok(_) => {} + Err(e) if common::run_fail::is_condition_failed(&e) => return Ok(false), + Err(e) => return Err(common::run_fail::error_text(&e)), + } + // The worker's copy, only while it names the same installation. + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.table_name) + .key("pk", s(team_id)) + .key("sk", s("META")) + .update_expression("REMOVE github_install_id, github_org SET updated_at = :t") + .condition_expression("github_install_id = :iid") + .expression_attribute_values(":iid", AttributeValue::N(installation_id.to_string())) + .expression_attribute_values(":t", s(&now)) + .send() + .await + { + if !common::run_fail::is_condition_failed(&e) { + warn!(team_id, installation_id, error = %common::run_fail::error_text(&e), "Released the stale link; the worker's copy stayed"); + } + } + Ok(true) +} + +/// Installations several teams carry, from the teams' records: id to team +/// ids. For the admin page. +pub fn shared(links: &[(String, u64)]) -> HashMap> { + let mut by: HashMap> = HashMap::new(); + for (team, iid) in links { + if *iid > 0 { + by.entry(*iid).or_default().push(team.clone()); + } + } + by.retain(|_, teams| { + teams.sort(); + teams.dedup(); + teams.len() > 1 + }); + by +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ids(v: &[&str]) -> Vec { + v.iter().map(|s| s.to_string()).collect() + } + + /// The recorded owner stands while it carries the installation; the + /// rule's pick (member counts can change) never moves it. + #[test] + fn the_recorded_owner_stands_while_it_holds_the_installation() { + let teams = ids(&["TEAM#a", "TEAM#b", "TEAM#c"]); + assert_eq!( + choose(&teams, Some("TEAM#b"), Some("TEAM#c".into())).as_deref(), + Some("TEAM#b") + ); + // Released or gone: the rule decides again. + assert_eq!( + choose(&teams, Some("TEAM#z"), Some("TEAM#c".into())).as_deref(), + Some("TEAM#c") + ); + assert_eq!( + choose(&teams, None, Some("TEAM#a".into())).as_deref(), + Some("TEAM#a") + ); + } + + #[test] + fn every_team_but_the_owner_holds_a_stale_link() { + let teams = ids(&["TEAM#c", "TEAM#a", "TEAM#b", "TEAM#a"]); + assert_eq!( + stale_teams(&teams, Some("TEAM#a")), + ids(&["TEAM#b", "TEAM#c"]) + ); + assert_eq!( + stale_teams(&ids(&["TEAM#a"]), Some("TEAM#a")), + Vec::::new() + ); + } + + #[test] + fn shared_installations_are_found_from_the_team_records() { + let links = vec![ + ("TEAM#a".to_string(), 7), + ("TEAM#b".to_string(), 7), + ("TEAM#c".to_string(), 9), + ("TEAM#d".to_string(), 0), + ("TEAM#e".to_string(), 0), + ]; + let s = shared(&links); + assert_eq!(s.len(), 1); + assert_eq!(s[&7], ids(&["TEAM#a", "TEAM#b"])); + } +} diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 7df04b635..f85b162ea 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -28,6 +28,7 @@ pub mod hybrid_admin; pub mod hybrid_email; pub mod hybrid_install; pub mod infrastructure; +pub mod installation_owner; pub mod integrations; pub mod jira_webhook; pub mod knowledge; diff --git a/services/worker/src/passes/await_merge.rs b/services/worker/src/passes/await_merge.rs index 57b78ba5a..78121022f 100644 --- a/services/worker/src/passes/await_merge.rs +++ b/services/worker/src/passes/await_merge.rs @@ -1401,9 +1401,18 @@ async fn merge( Ok(Next::Stop) } MergeOutcome::NotMergeable(reason) => { - // Branch protection, a required check GitHub still counts as - // missing, or a conflict. Keep polling: most of these clear on - // their own, and the reason is on the PR for the ones that don't. + // A conflict never clears by waiting: polling it kept the gate + // (and its status edits) going for hours. Stop on it. + let conflicted = github + .get_pull_request(owner, repo, msg.pr_number) + .await + .is_ok_and(|pr| common::merge_gate::is_conflict(&pr)); + if conflicted { + return on_conflict(state, github, msg, record, lines).await; + } + // Branch protection, or a required check GitHub still counts as + // missing. Keep polling: most of these clear on their own, and + // the reason is on the PR for the ones that don't. warn!(pr = msg.pr_number, reason = %reason, "await-merge: GitHub declined the merge"); lines.push(( Mark::Waiting, @@ -1431,6 +1440,86 @@ async fn merge( } } +/// The line the status comment shows for a conflict: CoderHelm updates its +/// own PR's branch once, or a person resolves it. +fn conflict_line(base: &str, updating: bool) -> (Mark, String) { + if updating { + ( + Mark::Waiting, + format!( + "Merge conflict with `{base}`: CoderHelm merges `{base}` into this branch once; \ + the review of that commit starts auto-merge again" + ), + ) + } else { + ( + Mark::Blocked, + format!( + "Merge conflict with `{base}`: resolve it on this branch; the review of the new \ + commit starts auto-merge again" + ), + ) + } +} + +/// The PR conflicts with its base: the gate stops (no polls, one status +/// update). On CoderHelm's own PR the first conflict starts a conflict round +/// on its run, once per PR; after that, or on anyone else's PR, a person +/// resolves it. +async fn on_conflict( + state: &WorkerState, + github: &GitHubClient, + msg: &AwaitMergeMessage, + record: &mut GateRecord, + mut lines: Vec<(Mark, String)>, +) -> Result { + let (owner, repo) = (msg.repo_owner.as_str(), msg.repo_name.as_str()); + let updating = msg.self_authored + && claim_conflict_round(state, msg).await + && super::resume::start_conflict_round( + state, + &msg.team_id, + msg.installation_id, + owner, + repo, + msg.pr_number, + ) + .await; + info!( + pr = msg.pr_number, + updating, "await-merge: merge conflict — the gate stops" + ); + let line = conflict_line(&msg.base_branch, updating); + set_state(state, msg, common::merge_gate::STATE_CONFLICT, &line.1).await; + lines.push(line); + let body = render_status( + &msg.head_sha, + &msg.base_branch, + &lines, + None, + Some(&control_url(state, msg, Control::Stop)), + ); + publish_status(state, github, msg, record, &body).await; + Ok(Next::Stop) +} + +/// Claims the one conflict round a PR gets. False when it was claimed +/// before (or the record can't be written). +async fn claim_conflict_round(state: &WorkerState, msg: &AwaitMergeMessage) -> bool { + state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(&msg.team_id)) + .key("sk", attr_s(&record_key(msg))) + .update_expression("SET conflict_round_head = :h") + .condition_expression("attribute_exists(sk) AND attribute_not_exists(conflict_round_head)") + .expression_attribute_values(":h", attr_s(&msg.head_sha)) + .send() + .await + .is_ok() +} + /// Arm the gate for a PR (called when CoderHelm approves; the gateway arms on /// approvals, dismissals, new reviews and completed check suites). Every /// arming starts a new chain. Returns false if the queue isn't configured. @@ -1501,6 +1590,20 @@ async fn send(state: &WorkerState, msg: &AwaitMergeMessage, attempts: u32, delay #[cfg(test)] mod ci_tests { use super::*; + + /// A conflict says once what happens next, and never asks to wait on CI. + #[test] + fn a_conflict_says_who_resolves_it() { + let (mark, text) = conflict_line("main", true); + assert_eq!(mark, Mark::Waiting); + assert!(text.contains("CoderHelm merges `main` into this branch once")); + let (mark, text) = conflict_line("main", false); + assert_eq!(mark, Mark::Blocked); + assert!(text.contains("resolve it on this branch")); + assert!(!common::merge_gate::wakes_on_ci( + common::merge_gate::STATE_CONFLICT + )); + } use crate::passes::quarantine::Gate; use serde_json::json; diff --git a/services/worker/src/passes/lessons.rs b/services/worker/src/passes/lessons.rs index dd2f503c6..b8b9379ce 100644 --- a/services/worker/src/passes/lessons.rs +++ b/services/worker/src/passes/lessons.rs @@ -28,6 +28,31 @@ const MAX_COMMENT_CHARS: usize = 6000; pub const TRIGGER_PR_CLOSED: &str = "pr_closed"; pub const TRIGGER_COMMENT: &str = "comment"; +/// A person answered CoderHelm's question on a PR closed without a reason. +pub const TRIGGER_CLOSE_REASON: &str = common::run_status::CLOSE_REASON_TRIGGER; + +/// The outcome signal on a run whose PR a person closed without saying why, +/// and once they answered (`close_signal` on the run record). +pub const SIGNAL_NO_REASON: &str = "closed_no_reason"; +pub const SIGNAL_WITH_REASON: &str = "closed_with_reason"; + +/// Marks CoderHelm's one question on a PR closed without a reason. +pub const CLOSE_ASK_MARKER: &str = ""; + +/// The one short question CoderHelm asks on a PR closed without a reason. +pub fn close_reason_question() -> String { + format!( + "{CLOSE_ASK_MARKER}\nThanks for looking at this. What was wrong with it? One line here \ + (wrong approach, not needed, the fix belonged somewhere else, ...) helps me get the next \ + ticket like this right. I won't ask again." + ) +} + +/// Whether people said why the PR was closed: a comment on it or on the +/// ticket's issue, or the reason picked when the run was closed in CoderHelm. +pub fn has_reason(ctx: &LessonContext, run_close_reason: &str) -> bool { + !run_close_reason.trim().is_empty() || ctx.comments.iter().any(|(_, t)| !t.trim().is_empty()) +} /// What the judge is shown. #[derive(Debug, Default, Clone)] @@ -405,7 +430,8 @@ pub async fn run( &state.http, )?; let mut ctx = run_context(&item); - ctx.closed_unmerged = msg.trigger == TRIGGER_PR_CLOSED; + ctx.closed_unmerged = + msg.trigger == TRIGGER_PR_CLOSED || msg.trigger == TRIGGER_CLOSE_REASON; if let Ok(pr) = github .get_pull_request(&msg.repo_owner, &msg.repo_name, msg.pr_number) .await @@ -434,6 +460,23 @@ pub async fn run( .extend(super::review_pr::human_comments(&c, 12)); } } + // Closed in CoderHelm with a reason picked: that is what people said. + let run_reason = s(&item, "close_reason"); + if !run_reason.trim().is_empty() { + ctx.comments.push(( + "the person who closed it".to_string(), + format!("Closed because: {}", run_reason.trim()), + )); + } + if msg.trigger == TRIGGER_PR_CLOSED && !has_reason(&ctx, &run_reason) { + // Nobody said why: that is a signal of its own, and CoderHelm + // asks once. The answer comes back as a close_reason lesson. + ask_close_reason(state, &github, &msg).await; + return Ok(()); + } + if msg.trigger == TRIGGER_CLOSE_REASON { + record_answer(state, &msg, &ctx).await; + } let mut usage = TokenUsage::default(); let judged = judge(state, &provider, &ctx, &mut usage).await; match judged.as_ref().and_then(Judgment::lesson_to_store) { @@ -489,6 +532,81 @@ pub async fn run( Ok(()) } +/// Records "closed, no reason" on the run and the team's counters, and asks +/// on the PR, once per run (a redelivered webhook asks nothing). +async fn ask_close_reason(state: &WorkerState, github: &GitHubClient, msg: &LessonMessage) { + let now = chrono::Utc::now().to_rfc3339(); + let first = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(&msg.run_id)) + .update_expression("SET close_signal = :sig, close_asked_at = :t") + .condition_expression("attribute_exists(run_id) AND attribute_not_exists(close_asked_at)") + .expression_attribute_values(":sig", attr_s(SIGNAL_NO_REASON)) + .expression_attribute_values(":t", attr_s(&now)) + .send() + .await + .is_ok(); + if !first { + return; + } + let month = chrono::Utc::now().format("%Y-%m").to_string(); + for period in [month.as_str(), "ALL_TIME"] { + let _ = state + .dynamo + .update_item() + .table_name(&state.config.analytics_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("period", attr_s(period)) + .update_expression("ADD prs_closed_no_reason :one") + .expression_attribute_values(":one", crate::passes::attr_n(1)) + .send() + .await; + } + info!(run_id = %msg.run_id, pr = msg.pr_number, "PR closed without a reason: asking once"); + if let Err(e) = github + .create_issue_comment( + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + &close_reason_question(), + ) + .await + { + warn!(run_id = %msg.run_id, error = %e, "Could not ask why the PR was closed"); + } +} + +/// The answer to the one question: kept on the run (the planner reads it +/// with the ticket's history) and the signal moved to "closed with reason". +async fn record_answer(state: &WorkerState, msg: &LessonMessage, ctx: &LessonContext) { + let Some((_, answer)) = ctx + .comments + .iter() + .rev() + .find(|(_, t)| !t.trim().is_empty()) + else { + return; + }; + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(&msg.run_id)) + .update_expression( + "SET close_signal = :sig, close_reason_answer = :a, close_answered_at = :t", + ) + .condition_expression("attribute_exists(close_asked_at)") + .expression_attribute_values(":sig", attr_s(SIGNAL_WITH_REASON)) + .expression_attribute_values(":a", attr_s(common::truncate_str(answer.trim(), 1000))) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await; +} + async fn mark(state: &WorkerState, msg: &LessonMessage, field: &str, value: Option<&str>) { let now = chrono::Utc::now().to_rfc3339(); let mut up = state @@ -514,6 +632,23 @@ async fn mark(state: &WorkerState, msg: &LessonMessage, field: &str, value: Opti mod tests { use super::*; + /// A close with nothing said is asked about once; anything people said + /// (on the PR, the ticket, or the close dialog) is the reason. + #[test] + fn a_close_without_a_reason_is_asked_about() { + let mut ctx = LessonContext::default(); + assert!(!has_reason(&ctx, "")); + assert!(has_reason(&ctx, "not needed")); + ctx.comments.push(("pat".into(), " ".into())); + assert!(!has_reason(&ctx, "")); + ctx.comments.push(("pat".into(), "Wrong approach".into())); + assert!(has_reason(&ctx, "")); + let q = close_reason_question(); + assert!(q.starts_with(CLOSE_ASK_MARKER)); + assert!(q.contains("I won't ask again")); + assert!(q.len() < 400); + } + fn closed_case() -> LessonContext { let d = crate::passes::fix_location::parse(crate::passes::fix_location::fixture::PLANNER_REPLY) diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index f62bb29b3..78b87d06e 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -2373,19 +2373,39 @@ async fn run_passes( // stops and asks, once. let mut open_pr_settled = msg.person_direction.is_some(); let mut other_open_pr: Option = None; + // CoderHelm's own pull request for this ticket that an earlier run + // opened and is still open in this repo: the re-run continues on it + // (its branch, its PR) instead of opening another one. + let own_open = history + .own_open_pr(&format!("{}/{}", msg.repo_owner, msg.repo_name)) + .map(|p| (p.number, p.branch.clone())); let branch_name = if can_skip_implement { checkpoint.as_ref().unwrap().1.clone() } else { - let own_branch = resolve_run_branch( - &github, - &msg.repo_owner, - &msg.repo_name, - &msg.ticket_id, - &conventions, - &tokens, - "", - ) - .await; + let own_branch = match &own_open { + Some((number, branch)) => { + add_progress_note( + state, + &msg.team_id, + run_id, + &format!("Continuing on my open pull request #{number} for this ticket"), + ) + .await; + branch.clone() + } + None => { + resolve_run_branch( + &github, + &msg.repo_owner, + &msg.repo_name, + &msg.ticket_id, + &conventions, + &tokens, + "", + ) + .await + } + }; match open_pr_for_ticket( &github, &msg.repo_owner, @@ -3585,6 +3605,8 @@ async fn run_passes( pr_count = pr_results.len(), "Multi-repo run set to awaiting_ci" ); + let repos: Vec = run_prs.iter().map(|p| p.repo.clone()).collect(); + supersede_moved_prs(&github, &history, &repos, &primary.url).await; // Schedule a safety-net resume if !state.config.ci_fix_queue_url.is_empty() { @@ -4348,6 +4370,15 @@ async fn run_passes( ) .await; info!(run_id, pr_url = %pr_result.pr_url, "Draft PR created"); + // The plan moved the change out of a repo an earlier run of this ticket + // opened a PR in: that PR is closed with a note naming this one. + supersede_moved_prs( + &github, + &history, + &[format!("{}/{}", msg.repo_owner, msg.repo_name)], + &pr_result.pr_url, + ) + .await; self::webhooks::emit_pr_opened( state, msg, @@ -6445,6 +6476,44 @@ fn own_pr_branch_for_ticket(prs: &serde_json::Value, ticket_id: &str) -> Option< }) } +/// Closes CoderHelm's own open pull requests for this ticket in repositories +/// the plan no longer changes, each with a note naming where the change is +/// now. A PR in a repository the run still changes is never closed: the +/// re-run continues on it. +async fn supersede_moved_prs( + github: &GitHubClient, + history: &ticket_history::TicketHistory, + repos: &[String], + now_at: &str, +) { + for p in history.own_open_prs_elsewhere(repos) { + let Some((owner, name)) = p.repo.split_once('/') else { + continue; + }; + let note = format!( + "Superseded by {now_at}: the plan for this ticket now changes {} instead of `{}`, \ + so this pull request is closed. Its branch `{}` is kept.", + repos + .iter() + .map(|r| format!("`{r}`")) + .collect::>() + .join(", "), + p.repo, + p.branch + ); + if let Err(e) = github + .create_issue_comment(owner, name, p.number, ¬e) + .await + { + warn!(repo = %p.repo, pr = p.number, error = %e, "Could not note the superseded PR; leaving it open"); + continue; + } + if let Err(e) = github.close_pull_request(owner, name, p.number).await { + warn!(repo = %p.repo, pr = p.number, error = %e, "Could not close the superseded PR"); + } + } +} + /// Whether a GitHub login is CoderHelm's app (it opens CoderHelm's PRs). pub fn is_own_login(login: &str) -> bool { login.to_ascii_lowercase().contains("coderhelm") diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 91bf936b8..2771a252f 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3200,7 +3200,12 @@ async fn run_pending_round( let round = pending.resumed(chrono::Utc::now()); let kind = round.kind; let number = round.number; - match run_fix_round(state, msg, &mut ctx, &pr, round, created_at, start).await? { + let end = if kind == run_round::Kind::Conflict { + run_conflict_round(state, msg, &mut ctx, &pr, &round).await + } else { + run_fix_round(state, msg, &mut ctx, &pr, round, created_at, start).await? + }; + match end { RoundEnd::Parked => {} RoundEnd::Incomplete => { complete_run_with_status( @@ -3285,6 +3290,154 @@ async fn run_pending_round( Ok(()) } +/// Starts the one conflict round on CoderHelm's own pull request after +/// auto-merge found it conflicting with its base: the run (completed or +/// waiting) gets a parked conflict round and a resume to run it. False when +/// there is no such run, or it is busy or ended: a person resolves it then. +pub(crate) async fn start_conflict_round( + state: &WorkerState, + team_id: &str, + installation_id: u64, + owner: &str, + repo: &str, + pr_number: u64, +) -> bool { + let Some(run_id) = + super::review_pr::lookup_run_by_pr(state, team_id, owner, repo, pr_number).await + else { + return false; + }; + let round = run_round::Round::start( + run_round::Kind::Conflict, + 1, + "", + "Merge the base branch into this pull request's branch and resolve the conflicts.", + true, + chrono::Utc::now(), + ) + .parked(false); + let claimed = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(&run_id)) + .update_expression( + "SET #s = :ac, status_run_id = :sri, #round = :r, current_pass = :ac, updated_at = :t \ + REMOVE #inc", + ) + .condition_expression("#s IN (:completed, :ac) AND attribute_not_exists(#round)") + .expression_attribute_names("#s", "status") + .expression_attribute_names("#round", run_round::FIELD) + .expression_attribute_names("#inc", run_round::INCOMPLETE_FIELD) + .expression_attribute_values(":ac", attr_s("awaiting_ci")) + .expression_attribute_values(":completed", attr_s("completed")) + .expression_attribute_values(":sri", attr_s(&format!("awaiting_ci#{run_id}"))) + .expression_attribute_values(":r", round.to_attr()) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await; + if let Err(e) = claimed { + if !common::run_fail::is_condition_failed(&e) { + warn!(run_id, error = %e, "Could not start the conflict round"); + } + return false; + } + if state.config.ci_fix_queue_url.is_empty() { + return false; + } + let body = serde_json::json!({ + "type": "resume", + "team_id": team_id, + "run_id": run_id, + "installation_id": installation_id, + }); + state + .sqs + .send_message() + .queue_url(&state.config.ci_fix_queue_url) + .message_body(body.to_string()) + .delay_seconds(5) + .send() + .await + .is_ok() +} + +/// The conflict round: the base branch merged into the pull request's +/// branch, the conflicting files resolved, one commit. A conflict that +/// can't be resolved that way is handed to a person with one comment. +async fn run_conflict_round( + state: &WorkerState, + msg: &ResumeMessage, + ctx: &mut FixContext, + pr: &PrRef<'_>, + round: &run_round::Round, +) -> RoundEnd { + let _ = super::update_pass(state, &msg.team_id, &msg.run_id, "conflict_fix").await; + let base = ctx.ticket_msg.base_branch.clone(); + match super::pr::resolve_conflicts( + state, + &ctx.ticket_msg, + &ctx.github, + pr.branch, + &ctx.provider, + &mut ctx.usage, + ) + .await + { + Ok(resolved) => { + super::round::clear(state, &msg.team_id, &msg.run_id).await; + super::add_progress_note( + state, + &msg.team_id, + &msg.run_id, + &if resolved { + format!( + "Merged `{base}` into the branch and resolved the conflicts in one commit" + ) + } else { + format!("Merged `{base}` into the branch; nothing conflicted any more") + }, + ) + .await; + // A new head: CI runs, the review of that commit re-arms auto-merge. + RoundEnd::Done { files: 1 } + } + Err(e) => { + let why = common::run_fail::error_text(&*e); + let gh = super::round::Pr { + github: &ctx.github, + owner: pr.owner, + repo: pr.repo, + branch: pr.branch, + }; + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + &gh, + round, + &format!("the conflict with `{base}` couldn't be resolved automatically ({why})"), + ) + .await; + let comment = format!( + "This pull request conflicts with `{base}` and CoderHelm couldn't resolve it on its \ + own ({}). Please resolve the conflict on this branch; auto-merge starts again with \ + the review of the new commit.", + common::truncate_str(&why, 300) + ); + if let Err(e) = ctx + .github + .create_issue_comment(pr.owner, pr.repo, pr.number, &comment) + .await + { + warn!(run_id = msg.run_id, error = %e, "Could not hand the conflict off on the PR"); + } + RoundEnd::Incomplete + } + } +} + /// After a security fix round: the security check runs again on the pull /// request, and its Open items say what it found. Fixed, the items go and /// the pull request may be marked ready; still failing, or a check that diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 9db46ceef..5dd717351 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -3085,7 +3085,7 @@ async fn plan_evidence_for_pr(state: &WorkerState, msg: &ReviewMessage) -> Strin } /// Newest run for a PR, via the runs-table repo-index GSI. None if untracked. -async fn lookup_run_by_pr( +pub(crate) async fn lookup_run_by_pr( state: &WorkerState, team_id: &str, owner: &str, diff --git a/services/worker/src/passes/round.rs b/services/worker/src/passes/round.rs index f2c9b1b8c..87fc2c240 100644 --- a/services/worker/src/passes/round.rs +++ b/services/worker/src/passes/round.rs @@ -428,6 +428,7 @@ pub(crate) async fn round_message( Kind::ReviewFix => "Address the review", Kind::Feedback => "Address the review comments", Kind::SecurityFix => "Fix the security issues the check found", + Kind::Conflict => "Merge the base branch and resolve the conflicts", }; let conventions = super::load_git_conventions(state, team_id, &ticket.ticket_id).await; conventions.commit_message(&super::ticket_tokens(ticket), summary) diff --git a/services/worker/src/passes/ticket_history.rs b/services/worker/src/passes/ticket_history.rs index 22794ee02..ff3d3578a 100644 --- a/services/worker/src/passes/ticket_history.rs +++ b/services/worker/src/passes/ticket_history.rs @@ -39,6 +39,8 @@ pub struct PriorRun { pub pr_comments: Vec<(String, String)>, /// Answers people gave in CoderHelm to the questions it stopped to ask. pub answers: Vec, + /// Every pull request the run opened, each with its repository. + pub pr_list: Vec, } impl PriorRun { @@ -166,6 +168,50 @@ pub enum Guard { } impl TicketHistory { + /// Whether an earlier run of this ticket opened `repo#number`. + fn opened_by_run(&self, repo: &str, number: u64) -> bool { + self.runs.iter().any(|r| { + r.pr_list + .iter() + .any(|p| p.pr_number == number && p.repo.eq_ignore_ascii_case(repo)) + }) + } + + /// CoderHelm's own pull request for this ticket that is still open in + /// `repo` (an earlier run opened it), newest first: a re-run continues + /// on it instead of opening another. + pub fn own_open_pr(&self, repo: &str) -> Option<&EarlierPr> { + self.prs + .iter() + .filter(|p| { + p.state == "open" + && p.repo.eq_ignore_ascii_case(repo) + && super::is_own_login(&p.author) + && !p.branch.is_empty() + && self.opened_by_run(&p.repo, p.number) + }) + .max_by(|a, b| { + a.created_at + .cmp(&b.created_at) + .then(a.number.cmp(&b.number)) + }) + } + + /// CoderHelm's own open pull requests for this ticket in repositories + /// this run's plan no longer changes: superseded, with a note, once the + /// new pull request is open. + pub fn own_open_prs_elsewhere(&self, repos: &[String]) -> Vec<&EarlierPr> { + self.prs + .iter() + .filter(|p| { + p.state == "open" + && !repos.iter().any(|r| r.eq_ignore_ascii_case(&p.repo)) + && super::is_own_login(&p.author) + && self.opened_by_run(&p.repo, p.number) + }) + .collect() + } + pub fn is_empty(&self) -> bool { self.runs.is_empty() && self.notes.is_empty() && self.prs.is_empty() } @@ -566,6 +612,7 @@ fn prior_run(item: &Item) -> PriorRun { pr_comments: Vec::new(), answers: serde_json::from_str(&s(item, common::run_questions::FIELD_ANSWERS)) .unwrap_or_default(), + pr_list: common::run_prs::from_item(item), } } @@ -668,12 +715,14 @@ pub async fn add_earlier_prs( ticket_id: &str, ) { let mut found: Vec<(String, u64)> = Vec::new(); - for r in &history.runs { - if r.pr_number > 0 - && r.repo.contains('/') - && !found.contains(&(r.repo.clone(), r.pr_number)) + // Every pull request an earlier run opened, in its own repository (a + // multi-repo run's record pairs its repo with only one of them). + for p in history.runs.iter().flat_map(|r| r.pr_list.iter()) { + if p.pr_number > 0 + && p.repo.contains('/') + && !found.contains(&(p.repo.clone(), p.pr_number)) { - found.push((r.repo.clone(), r.pr_number)); + found.push((p.repo.clone(), p.pr_number)); } } if !ticket_id.is_empty() { @@ -912,6 +961,71 @@ pub async fn load( mod tests { use super::*; + fn run_with_prs(id: &str, prs: &[(&str, u64)]) -> PriorRun { + PriorRun { + run_id: id.into(), + pr_list: prs + .iter() + .map(|(repo, n)| common::run_prs::RunPr { + repo: repo.to_string(), + pr_number: *n, + ..Default::default() + }) + .collect(), + ..Default::default() + } + } + + fn earlier(repo: &str, n: u64, author: &str, state: &str, at: &str) -> EarlierPr { + EarlierPr { + repo: repo.into(), + number: n, + author: author.into(), + branch: format!("coderhelm/t-{n}"), + state: state.into(), + created_at: at.into(), + ..Default::default() + } + } + + /// A re-run continues on CoderHelm's own open PR in the same repo: the + /// newest one an earlier run opened, never a person's, a closed one, or + /// one no run of this ticket opened. + #[test] + fn a_rerun_finds_its_own_open_pull_request() { + let h = TicketHistory { + runs: vec![ + run_with_prs("01A", &[("acme/web", 5)]), + run_with_prs("01B", &[("acme/web", 9), ("acme/api", 3)]), + ], + prs: vec![ + earlier("acme/web", 5, "coderhelm[bot]", "closed", "2026-10-01"), + earlier("acme/web", 9, "coderhelm[bot]", "open", "2026-10-02"), + earlier("acme/web", 11, "pat", "open", "2026-10-03"), + earlier("acme/web", 12, "coderhelm[bot]", "open", "2026-10-04"), + earlier("acme/api", 3, "coderhelm[bot]", "open", "2026-10-02"), + ], + ..Default::default() + }; + assert_eq!(h.own_open_pr("acme/web").map(|p| p.number), Some(9)); + assert_eq!(h.own_open_pr("ACME/Api").map(|p| p.number), Some(3)); + assert!(h.own_open_pr("acme/docs").is_none()); + + // The plan moved to acme/web only: the api PR is superseded. + let moved = h.own_open_prs_elsewhere(&["acme/web".to_string()]); + assert_eq!( + moved + .iter() + .map(|p| (p.repo.as_str(), p.number)) + .collect::>(), + [("acme/api", 3)] + ); + // Both repos still in the plan: nothing to supersede. + assert!(h + .own_open_prs_elsewhere(&["acme/web".into(), "acme/api".into()]) + .is_empty()); + } + /// The planner's decision on the rerun: a code change that forces one /// record active (the same change people closed before). fn override_plan(history_check: &str) -> FixDecision {