From d9eb2009a85b6cb3a28eb48eaf000a591938cbb1 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 16 Nov 2026 22:26:32 -0500 Subject: [PATCH] A merge is followed through its deploy, whoever merged it A person merged one of CoderHelm's pull requests hours after closing its run by hand, and nothing followed the deploy: - The merge kept the run closed, and the pull request watch looked only at finished runs, so the merge commit's deploy was never watched. A merge CoderHelm made itself was watched; a person's was not. - The release steps armed when the pull request opened waited on another service's deploy: a workflow with a production job on merge to main and a path filter on that service's folder, which never runs for the change. Staging's deploy was not a step, and the v* tag that deploys production was never asked for. Now: - pr_watch: a merged pull request takes Act::WatchDeploy whatever the run's status (finished, merged by CoderHelm, or closed, cancelled or failed before a person merged it). The act watches the merge commit's deploy and follows the release. The sweep reads merged runs a person ended until their deploy is followed, so merges already missed are picked up; a closed pull request's outcome is looked at as soon as it is scored. - release_plan: workflows' push path filters are read. A deploy is the change's only when its workflow runs for the files the pull request changed, and a workflow named for its environment goes before one service's deploy. A release with no migration waits for staging's deploy, then production's by the repository's own path. - release_run: follow_merge re-derives the deploys at the merge commit and points an armed release at the right ones, keeping steps already done; a pull request with no release gets its deploys followed. A step waiting on a person's approval is said once in the pull request's one status comment. Incident bx covers both merges taking the same follow, the existing release re-pointed, and the catch-up. --- docs/incidents/bx_merge_follows_the_deploy.md | 5 + services/worker/src/main.rs | 7 + .../incidents/bk_owns_the_outside_work.rs | 2 + .../incidents/bx_merge_follows_the_deploy.rs | 337 ++++++++++++++++++ services/worker/src/passes/pr_watch.rs | 91 +++-- services/worker/src/passes/release_plan.rs | 238 ++++++++++++- services/worker/src/passes/release_run.rs | 200 ++++++++++- 7 files changed, 837 insertions(+), 43 deletions(-) create mode 100644 docs/incidents/bx_merge_follows_the_deploy.md create mode 100644 services/worker/src/passes/incidents/bx_merge_follows_the_deploy.rs diff --git a/docs/incidents/bx_merge_follows_the_deploy.md b/docs/incidents/bx_merge_follows_the_deploy.md new file mode 100644 index 000000000..302e18a4e --- /dev/null +++ b/docs/incidents/bx_merge_follows_the_deploy.md @@ -0,0 +1,5 @@ +# bx. `bx_merge_follows_the_deploy` + +**What happened:** A person merged one of CoderHelm's pull requests hours after closing its run by hand. The merge kept the run closed and the pull request watch looked only at finished runs, so the merge commit's deploy was never watched. The release steps armed when the pull request opened waited on another service's deploy (a production job on merge with a path filter on that service's folder, which never runs for a web change); staging's deploy was not a step and the `v*` tag that deploys production was never asked for. + +**The guarantee:** A merge is followed the same way whoever merged it and whatever the run's status: CoderHelm's merge and a person's both take the watch's deploy act, which watches the merge commit's deploy and follows the release. A deploy is the change's only when its workflow runs for the files the pull request changed, and a workflow named for its environment goes before one service's deploy. The release waits for staging, then prepares production by the repository's own path (the tag under one approval when the team asks for it, said once in one line). A release armed on the wrong deploy is pointed at the right one, keeping steps already done, and the sweep picks up merges already missed. diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 4a98d76d6..c870aaf95 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -521,9 +521,16 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe } models::WorkerMessage::RewardOutcome(msg) => { info!(team_id = %msg.team_id, run_id = %msg.run_id, pr = msg.pr_number, "Scoring a closed pull request"); + let (team_id, run_id) = (msg.team_id.clone(), msg.run_id.clone()); + let follow = !run_id.is_empty() && !msg.review_only; if let Err(e) = passes::rewards::score_outcome(&state, msg).await { error!("Reward outcome failed: {e}"); } + // The same pull request's merge is followed now, whoever merged + // it: its deploys and its release (`pr_watch`). + if follow { + passes::pr_watch::after_pr_closed(&state, &team_id, &run_id).await; + } } models::WorkerMessage::ReviewLesson(msg) => { info!(team_id = %msg.team_id, pr = msg.pr_number, trigger = %msg.trigger, "Judging pushback on a review"); diff --git a/services/worker/src/passes/incidents/bk_owns_the_outside_work.rs b/services/worker/src/passes/incidents/bk_owns_the_outside_work.rs index 7a99ccb50..5fe2ee20d 100644 --- a/services/worker/src/passes/incidents/bk_owns_the_outside_work.rs +++ b/services/worker/src/passes/incidents/bk_owns_the_outside_work.rs @@ -156,6 +156,8 @@ fn the_repo() -> Abilities { name: "Deploy Production".into(), file: ".github/workflows/deploy-production.yml".into(), on: On::Tag("v*".into()), + paths: Vec::new(), + paths_ignore: Vec::new(), }], purge: Some(release_plan::Runner { name: "Purge cache".into(), diff --git a/services/worker/src/passes/incidents/bx_merge_follows_the_deploy.rs b/services/worker/src/passes/incidents/bx_merge_follows_the_deploy.rs new file mode 100644 index 000000000..a1a18af7c --- /dev/null +++ b/services/worker/src/passes/incidents/bx_merge_follows_the_deploy.rs @@ -0,0 +1,337 @@ +//! bx. A person merged one of CoderHelm's pull requests and nothing +//! followed its deploy. The run had been closed by hand ("done by hand") +//! hours before the merge, so the merge kept it closed, and the pull +//! request watch looked only at finished runs: the merge commit's deploy +//! was never watched. The release steps armed when the pull request opened +//! (the plan said "release through the `v*` tag") did tick after the merge, +//! but waited on the wrong workflow: another service's deploy that has a +//! production job on merge to `main` and a path filter on that service's +//! folder, so it never runs for a web change. Staging's deploy was not a +//! step at all, and the `v*` tag that deploys production was never asked +//! for. The product owner saw no deploy. +//! +//! Guarantee: a merge is followed the same way whoever merged it and +//! whatever the run's status: CoderHelm's merge (run `merged`) and a +//! person's (run `completed`, or `closed` by hand) both take +//! `Act::WatchDeploy`, which watches the merge commit's deploy and follows +//! the release (`release_run::follow_merge`). A deploy is this change's only +//! when its workflow runs for the files the pull request changed (the push +//! trigger's path filters); a workflow named for its environment goes +//! before one service's deploy. The release waits for staging's deploy, +//! then prepares production's by the repository's own path (the `v*` tag, +//! under one approval when the team's settings ask for it, said once in +//! one line). A release already armed on the wrong deploy is pointed at the +//! right one, keeping every step that is done. The sweep reads merged runs +//! a person ended, so a merge already missed is picked up. + +use crate::passes::pr_watch::{self, Act, Marks, Seen}; +use crate::passes::release_plan::{self, Env, Kind, On, Status, Step}; +use crate::passes::release_run::{self, approval_line, refollow, Next}; + +const MERGE: &str = "9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b"; + +/// Another service's deploy: a job per environment on merge to `main`, +/// limited to its folder. +const SERVICE_DEPLOY: &str = r#" +name: Deploy Thumbnail Service +on: + push: + branches: [main] + paths: + - 'services/thumbnail/**' + - '.github/workflows/deploy-thumbnail.yml' + workflow_dispatch: +jobs: + deploy-staging: + environment: staging + runs-on: ubuntu-latest + steps: + - run: ./deploy.sh staging + deploy-production: + needs: deploy-staging + environment: production + runs-on: ubuntu-latest + steps: + - run: ./deploy.sh production +"#; + +const STAGING: &str = r#" +name: Deploy Staging +on: + push: + branches: [main] +jobs: + deploy: + environment: staging + runs-on: ubuntu-latest + steps: + - run: npm run deploy +"#; + +const PRODUCTION: &str = r#" +name: Deploy Production +on: + push: + tags: ['v*'] +jobs: + deploy: + environment: production + runs-on: ubuntu-latest + steps: + - run: npm run deploy +"#; + +const TESTS: &str = r#" +name: Test Suite +on: + push: + branches: [main, develop] + workflow_dispatch: +jobs: + test: + runs-on: ubuntu-latest + steps: + - run: npm test +"#; + +fn repo() -> release_plan::Mechanics { + release_plan::mechanics( + &[ + ( + ".github/workflows/deploy-thumbnail.yml".into(), + SERVICE_DEPLOY.into(), + ), + ( + ".github/workflows/deploy-staging.yml".into(), + STAGING.into(), + ), + ( + ".github/workflows/deploy-production.yml".into(), + PRODUCTION.into(), + ), + (".github/workflows/test.yml".into(), TESTS.into()), + ], + None, + ) +} + +/// The web change the pull request made. +fn changed() -> Vec { + vec![ + "apps/web/src/components/blocks/portal-embed.tsx".into(), + "apps/web/src/lib/csp.ts".into(), + ] +} + +/// The release armed when the pull request opened, as it stood a moment +/// after the merge: production's deploy waiting on the service's workflow. +fn armed_before_the_fix() -> Vec { + let json = r#"[{"id":"deploy_production","kind":"deploy","env":"production", + "what":"Deploy the change to production", + "how":"wait for `Deploy Thumbnail Service` (.github/workflows/deploy-thumbnail.yml), which runs on merge to `main`", + "tool":"","after":[],"after_merge":true,"verify":"","status":"running", + "detail":"waiting for `.github/workflows/deploy-thumbnail.yml` on the merge commit", + "before":"","after_count":"","approval_id":"","run_id":0,"tag":"", + "workflow":".github/workflows/deploy-thumbnail.yml","inputs":[], + "trigger":{"on":"merge","value":"main"},"project_id":"p1","dataset":"production", + "started_at":1794879648}]"#; + serde_json::from_str(json).unwrap() +} + +fn merged_seen() -> Seen { + Seen { + merged: true, + merge_sha: MERGE.into(), + ..Default::default() + } +} + +#[test] +fn coderhelm_merge_and_person_merge_take_the_same_follow() { + let seen = merged_seen(); + // CoderHelm merged it: the webhook moved the run to `merged`. + assert_eq!( + pr_watch::decide("merged", &seen, &Marks::default()), + Act::WatchDeploy + ); + // A person merged it after the run finished. + assert_eq!( + pr_watch::decide("completed", &seen, &Marks::default()), + Act::WatchDeploy + ); + // A person merged it after closing the run by hand (this incident). + assert_eq!( + pr_watch::decide("closed", &seen, &Marks::default()), + Act::WatchDeploy + ); + // Each act claims the same mark against the same merge commit: one + // follow per merge, whichever way it came. + for status in ["merged", "completed", "closed"] { + let act = pr_watch::decide(status, &seen, &Marks::default()); + assert_eq!( + act.claim(&seen), + Some((Marks::DEPLOY, MERGE.to_string())), + "{status}" + ); + let done = Marks { + deploy_sha: MERGE.into(), + ..Default::default() + }; + assert_eq!(pr_watch::decide(status, &seen, &done), Act::Nothing); + } +} + +#[test] +fn a_closed_run_is_followed_only_for_its_merge() { + // An open pull request of a run a person closed is left to them. + let open = Seen { + open: true, + head: "abc".into(), + conflict: true, + base_sha: "def".into(), + failing: vec!["build".into()], + ..Default::default() + }; + for status in ["closed", "cancelled", "failed"] { + assert_eq!( + pr_watch::decide(status, &open, &Marks::default()), + Act::Nothing, + "{status}" + ); + assert!(pr_watch::follows_merge(status)); + } + for status in ["running", "queued", "retried", "archived"] { + assert!(!pr_watch::follows_merge(status), "{status}"); + assert_eq!( + pr_watch::decide(status, &merged_seen(), &Marks::default()), + Act::Nothing + ); + } +} + +#[test] +fn the_sweep_catches_up_merges_already_missed() { + // The scan reads a merged run a person ended until its deploy is + // followed, inside the watch window. + let f = pr_watch::SWEEP_FILTER; + assert!(f.contains("#s IN (:closed, :cancelled, :failed)"), "{f}"); + assert!(f.contains("pr_outcome = :merged AND attribute_not_exists(#wd)")); + assert!(f.contains("updated_at >= :cut")); +} + +#[test] +fn the_deploy_is_the_one_that_runs_for_the_change() { + let m = repo(); + // Without the files (when the pull request opens), the workflow named + // for production goes before a service's deploy with a path filter. + let d = m.deploy(Env::Production).unwrap(); + assert_eq!(d.name, "Deploy Production"); + assert_eq!(d.on, On::Tag("v*".into())); + assert_eq!(m.deploy(Env::Staging).unwrap().name, "Deploy Staging"); + + // With the files: the service's deploy never runs for a web change. + let web = m.for_change(&changed()); + assert!(!web + .deploys + .iter() + .any(|d| d.file.ends_with("deploy-thumbnail.yml") && matches!(d.on, On::Merge(_)))); + assert_eq!( + web.deploy(Env::Production).unwrap().name, + "Deploy Production" + ); + assert_eq!(web.deploy(Env::Staging).unwrap().name, "Deploy Staging"); + + // A change to the service runs it: it stays a deploy of the change. + let svc = m.for_change(&["services/thumbnail/src/index.ts".to_string()]); + assert!(svc + .deploys + .iter() + .any(|d| d.file.ends_with("deploy-thumbnail.yml") && matches!(d.on, On::Merge(_)))); +} + +#[test] +fn the_release_waits_for_staging_then_asks_for_the_tag() { + let steps = release_plan::follow_steps(&repo().for_change(&changed())); + let ids: Vec<&str> = steps.iter().map(|s| s.id.as_str()).collect(); + assert_eq!(ids, ["deploy_staging", "deploy_production"]); + let (stg, prod) = (&steps[0], &steps[1]); + // Staging deploys on merge: CoderHelm only waits for it, no gate. + assert_eq!(stg.workflow, ".github/workflows/deploy-staging.yml"); + assert_eq!(stg.trigger, Some(On::Merge("main".into()))); + assert!(stg.tool.is_empty()); + // Production: the next `v*` tag, checked by the team's release settings + // (an approval card unless the team allowed it), after staging's deploy. + assert_eq!(prod.workflow, ".github/workflows/deploy-production.yml"); + assert_eq!(prod.trigger, Some(On::Tag("v*".into()))); + assert_eq!(prod.tool, "release_production_tag"); + assert_eq!(prod.after, vec!["deploy_staging".to_string()]); + assert!(steps + .iter() + .all(|s| s.after_merge && s.kind == Kind::Deploy)); + + // After the merge, staging is waited for first; production holds. + assert_eq!(release_run::next(&steps, 0, true), Next::Start); + assert_eq!(release_run::next(&steps, 1, true), Next::Wait); +} + +#[test] +fn the_release_armed_on_the_wrong_deploy_is_pointed_at_the_right_one() { + let old = armed_before_the_fix(); + let fresh = release_plan::follow_steps(&repo().for_change(&changed())); + let now = refollow(&old, &fresh).expect("the release changes"); + let ids: Vec<&str> = now.iter().map(|s| s.id.as_str()).collect(); + assert_eq!(ids, ["deploy_staging", "deploy_production"]); + assert_eq!(now[0].status, Status::Pending); + let prod = &now[1]; + assert_eq!(prod.status, Status::Pending); + assert_eq!(prod.workflow, ".github/workflows/deploy-production.yml"); + assert_eq!(prod.trigger, Some(On::Tag("v*".into()))); + assert_eq!(prod.after, vec!["deploy_staging".to_string()]); + assert!(prod.detail.is_empty() && prod.started_at == 0); + // A second look changes nothing: the running chain is left as it is. + assert_eq!(refollow(&now, &fresh), None); +} + +#[test] +fn a_step_already_done_is_kept() { + let mut old = armed_before_the_fix(); + old[0].status = Status::Done; + old[0].detail = "`Deploy Thumbnail Service` succeeded".into(); + let fresh = release_plan::follow_steps(&repo().for_change(&changed())); + let now = refollow(&old, &fresh).unwrap(); + let prod = now.iter().find(|s| s.id == "deploy_production").unwrap(); + assert_eq!(prod.status, Status::Done); + assert_eq!(prod.workflow, ".github/workflows/deploy-thumbnail.yml"); +} + +#[test] +fn a_merge_with_no_release_gets_its_deploys_followed() { + // No release armed (a plain code change): the merge arms the deploys. + let fresh = release_plan::follow_steps(&repo().for_change(&changed())); + let now = refollow(&[], &fresh).unwrap(); + assert_eq!(now, fresh); + // A repository whose workflows deploy nothing has nothing to follow: + // no step names a grant for a deploy that happens elsewhere. + let none = release_plan::follow_steps(&release_plan::mechanics( + &[(".github/workflows/test.yml".into(), TESTS.into())], + None, + )); + assert!(none.is_empty(), "{none:?}"); +} + +#[test] +fn the_approval_is_said_once_in_one_short_line() { + let mut steps = release_plan::follow_steps(&repo().for_change(&changed())); + assert_eq!(approval_line(&steps), None); + steps[1].status = Status::Approval; + let line = approval_line(&steps).unwrap(); + assert!(line.contains("`v*`"), "{line}"); + assert!(line.contains("approval")); + assert!(!line.contains(".github/"), "{line}"); + assert!(!line.contains('\n')); + let rendered = common::comment_style::render(&line, true); + assert!( + common::comment_style::lint(&rendered).is_empty(), + "{rendered}" + ); +} diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index f2ea85a41..7a818bfda 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -217,24 +217,37 @@ pub fn watched(status: &str) -> bool { ) } +/// Run statuses whose merged pull request is followed through its deploy: +/// every finished one, and one a person ended (closed by hand, cancelled) +/// or that failed, since the merge still shipped the change. A person's +/// merge and CoderHelm's go through the same follow ([`Act::WatchDeploy`]). +pub fn follows_merge(status: &str) -> bool { + watched(status) + || matches!( + status, + common::run_status::CLOSED | common::run_status::CANCELLED | common::run_status::FAILED + ) +} + /// What to do, first need first. A merged pull request gets its deploy -/// watched; a closed one nothing. An open one: a conflict before anything +/// watched and its release followed, whatever the run's status says +/// ([`follows_merge`]); a closed one nothing. An open one: a conflict before anything /// (nothing else can be judged on a branch that can't merge), then red /// checks, then the reviewer's verdict on the head: none on this commit /// asks for one, and changes requested on this commit are fixed. Each only /// once per commit. pub fn decide(status: &str, seen: &Seen, marks: &Marks) -> Act { - if !watched(status) { - return Act::Nothing; - } if seen.merged { - return if !seen.merge_sha.is_empty() && marks.deploy_sha != seen.merge_sha { + return if follows_merge(status) + && !seen.merge_sha.is_empty() + && marks.deploy_sha != seen.merge_sha + { Act::WatchDeploy } else { Act::Nothing }; } - if !seen.open || seen.head.is_empty() { + if !watched(status) || !seen.open || seen.head.is_empty() { return Act::Nothing; } if seen.conflict { @@ -694,17 +707,31 @@ async fn perform( .await .into() } - Act::WatchDeploy => super::health_check::schedule_own( - state, - github, - &c.team_id, - c.installation_id, - (&c.owner, &c.repo, c.pr), - &c.base_branch, - &seen.merge_sha, - ) - .await - .into(), + Act::WatchDeploy => { + // The release follows the same merge: the deploys that run for + // its files, staging then production by the repository's own + // path (the tag under one approval when the team asks for it). + super::release_run::follow_merge( + state, + github, + &c.team_id, + c.installation_id, + (&c.owner, &c.repo, c.pr), + &c.run_id, + ) + .await; + super::health_check::schedule_own( + state, + github, + &c.team_id, + c.installation_id, + (&c.owner, &c.repo, c.pr), + &c.base_branch, + &seen.merge_sha, + ) + .await + .into() + } } } @@ -919,7 +946,7 @@ pub async fn after_completion(state: &WorkerState, team_id: &str, run_id: &str) let Some(c) = item.as_ref().and_then(candidate_of) else { return; }; - if !watched(&c.status) { + if !watched(&c.status) && !follows_merge(&c.status) { return; } if let Some(github) = client(state, c.installation_id) { @@ -927,6 +954,14 @@ pub async fn after_completion(state: &WorkerState, team_id: &str, run_id: &str) } } +/// A pull request with a run closed or merged (the webhook): it is looked +/// at now, so a merge is followed through its deploy within the minute, +/// whoever merged it and whatever the run's status. Best effort; the sweep +/// looks again. +pub async fn after_pr_closed(state: &WorkerState, team_id: &str, run_id: &str) { + after_completion(state, team_id, run_id).await; +} + /// What one sweep did. #[derive(Debug, Default)] pub struct SweepReport { @@ -944,6 +979,14 @@ pub struct SweepReport { pub caught_up: Vec, } +/// The sweep's scan: finished runs with a pull request, changed inside the +/// watch window; and a run a person ended (or that failed) whose pull +/// request merged and whose deploy nobody follows yet, so a merge the +/// webhook's look missed is still followed (the catch-up). +pub const SWEEP_FILTER: &str = "pr_number > :zero AND updated_at >= :cut AND \ + ((#s IN (:done, :old_done, :merged) AND (attribute_not_exists(pr_outcome) OR pr_outcome = :merged)) \ + OR (#s IN (:closed, :cancelled, :failed) AND pr_outcome = :merged AND attribute_not_exists(#wd)))"; + /// Finished runs with a pull request, changed inside the watch window: each /// pull request is looked at, least recently looked at first. pub async fn sweep(state: &WorkerState) -> SweepReport { @@ -956,14 +999,15 @@ pub async fn sweep(state: &WorkerState) -> SweepReport { .dynamo .scan() .table_name(&state.config.runs_table_name) - .filter_expression( - "#s IN (:done, :old_done, :merged) AND pr_number > :zero AND updated_at >= :cut \ - AND (attribute_not_exists(pr_outcome) OR pr_outcome = :merged)", - ) + .filter_expression(SWEEP_FILTER) .expression_attribute_names("#s", "status") + .expression_attribute_names("#wd", Marks::DEPLOY) .expression_attribute_values(":done", attr_s(common::run_status::COMPLETED)) .expression_attribute_values(":old_done", attr_s(common::run_status::SUCCESS)) .expression_attribute_values(":merged", attr_s("merged")) + .expression_attribute_values(":closed", attr_s(common::run_status::CLOSED)) + .expression_attribute_values(":cancelled", attr_s(common::run_status::CANCELLED)) + .expression_attribute_values(":failed", attr_s(common::run_status::FAILED)) .expression_attribute_values(":zero", attr_n(0)) .expression_attribute_values(":cut", attr_s(&cutoff)) .set_exclusive_start_key(start.take()) @@ -984,6 +1028,9 @@ pub async fn sweep(state: &WorkerState) -> SweepReport { } // A merged pull request whose deploy is already watched needs no look. all.retain(|c| c.status != "merged" || c.marks.deploy_sha.is_empty()); + // A run a person ended is looked at only for its merge (the scan reads + // only merged ones), and only until its deploy is followed. + all.retain(|c| watched(&c.status) || c.marks.deploy_sha.is_empty()); report.candidates = all.len(); let mut clients: HashMap = HashMap::new(); // Asked before each look: the sweep never spends the runs' share of diff --git a/services/worker/src/passes/release_plan.rs b/services/worker/src/passes/release_plan.rs index f1027831b..56a7447d6 100644 --- a/services/worker/src/passes/release_plan.rs +++ b/services/worker/src/passes/release_plan.rs @@ -114,9 +114,88 @@ pub struct Deploy { pub name: String, pub file: String, pub on: On, + /// The `push` trigger's `paths` and `paths-ignore` filters (a merge + /// deploy only): a merge that changes none of the files they let + /// through never starts this workflow. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub paths: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub paths_ignore: Vec, +} + +/// Whether a workflow path filter pattern matches `path`, as GitHub reads +/// it: `*` stops at `/`, `**` crosses it, `?` is one character. +pub fn glob_matches(pattern: &str, path: &str) -> bool { + let mut re = String::from("^"); + let p: Vec = pattern.chars().collect(); + let mut i = 0; + while i < p.len() { + match p[i] { + '*' if p.get(i + 1) == Some(&'*') => { + if p.get(i + 2) == Some(&'/') { + re.push_str("(?:.*/)?"); + i += 3; + } else { + re.push_str(".*"); + i += 2; + } + continue; + } + '*' => re.push_str("[^/]*"), + '?' => re.push_str("[^/]"), + c => re.push_str(®ex::escape(&c.to_string())), + } + i += 1; + } + re.push('$'); + Regex::new(&re).is_ok_and(|r| r.is_match(path)) +} + +/// Whether a list of filter patterns (a later `!pattern` takes a file back +/// out) selects `path`. +fn filter_selects(patterns: &[String], path: &str) -> bool { + let mut hit = false; + for p in patterns { + match p.strip_prefix('!') { + Some(neg) if glob_matches(neg, path) => hit = false, + None if glob_matches(p, path) => hit = true, + _ => {} + } + } + hit } impl Deploy { + /// Whether a merge changing `changed` starts this deploy: always for a + /// tag or a dispatch (GitHub reads no path filter there), and for a + /// merge when its path filters let one of the files through. `changed` + /// empty means the files aren't known: it is taken to run. + pub fn runs_for(&self, changed: &[String]) -> bool { + if !matches!(self.on, On::Merge(_)) || changed.is_empty() { + return true; + } + let paths_ok = + self.paths.is_empty() || changed.iter().any(|f| filter_selects(&self.paths, f)); + let ignore_ok = self.paths_ignore.is_empty() + || changed + .iter() + .any(|f| !filter_selects(&self.paths_ignore, f)); + paths_ok && ignore_ok + } + + /// Whether only some merges start it (a path filter). + pub fn filtered(&self) -> bool { + matches!(self.on, On::Merge(_)) && !(self.paths.is_empty() && self.paths_ignore.is_empty()) + } + + /// Whether the workflow is named for its environment (`Deploy + /// Production`, `deploy-staging.yml`), not one service's deploy that has + /// a job in it. + fn named_for_env(&self) -> bool { + let base = self.file.rsplit('/').next().unwrap_or(&self.file); + Env::of(&self.name) == Some(self.env) || Env::of(base) == Some(self.env) + } + pub fn line(&self) -> String { format!( "{} deploys {} (`{}`, {})", @@ -176,12 +255,45 @@ pub struct Mechanics { } impl Mechanics { - /// The deploy of `env`: one started by merge, else tag, else dispatch. + /// The deploy of `env`. A workflow every merge starts goes before one a + /// path filter limits to some files (another service's deploy with a + /// job for this environment); then one named for the environment + /// (`Deploy Production`); then started by merge, else tag, else + /// dispatch; then one whose name says it deploys. pub fn deploy(&self, env: Env) -> Option<&Deploy> { - let of = |f: fn(&On) -> bool| self.deploys.iter().find(|d| d.env == env && f(&d.on)); - of(|o| matches!(o, On::Merge(_))) - .or_else(|| of(|o| matches!(o, On::Tag(_)))) - .or_else(|| of(|o| matches!(o, On::Dispatch))) + let rank = |d: &Deploy| { + let on = match d.on { + On::Merge(_) => 0, + On::Tag(_) => 1, + On::Dispatch => 2, + }; + ( + d.filtered(), + !d.named_for_env(), + on, + !(is_deploy_text(&d.name) || is_deploy_text(&d.file)), + ) + }; + self.deploys + .iter() + .filter(|d| d.env == env) + .min_by_key(|d| rank(d)) + } + + /// How the repository releases this change (`changed`, the files the + /// pull request changes): a merge deploy whose path filters let none of + /// them through never runs for it, so it is not this change's deploy. A + /// filter that does let them through then counts as every merge's. + pub fn for_change(&self, changed: &[String]) -> Mechanics { + let mut m = self.clone(); + m.deploys.retain(|d| d.runs_for(changed)); + if !changed.is_empty() { + for d in m.deploys.iter_mut() { + d.paths.clear(); + d.paths_ignore.clear(); + } + } + m } pub fn source(&self, env: Env) -> Option<&ContentSource> { @@ -377,6 +489,14 @@ pub fn workflow_deploys(path: &str, text: &str) -> Vec { if ons.is_empty() { return Vec::new(); } + // The push trigger's path filters: GitHub reads them for branch pushes + // only, never for a tag. + let push = doc + .get("on") + .or_else(|| doc.get(serde_yaml::Value::Bool(true))) + .and_then(|o| o.get("push")); + let push_paths = yaml_list(push.and_then(|p| p.get("paths"))); + let push_ignore = yaml_list(push.and_then(|p| p.get("paths-ignore"))); let file_env = Env::of(&name).or_else(|| Env::of(path.rsplit('/').next().unwrap_or(path))); let workflow_deploys = is_deploy_text(&name) || is_deploy_text(path); let mut out: Vec = Vec::new(); @@ -401,11 +521,22 @@ pub fn workflow_deploys(path: &str, text: &str) -> Vec { let cond = job.get("if").map(yaml_str).unwrap_or_default(); for on in &ons { if job_allows(&cond, on) { + let merge = matches!(on, On::Merge(_)); let d = Deploy { env, name: name.clone(), file: path.to_string(), on: on.clone(), + paths: if merge { + push_paths.clone() + } else { + Vec::new() + }, + paths_ignore: if merge { + push_ignore.clone() + } else { + Vec::new() + }, }; if !out.contains(&d) { out.push(d); @@ -626,10 +757,10 @@ pub fn checks_of(c: &super::fix_location::OutsideChange) -> Vec<(Vec, Ve .collect() } -/// A release with no migration: production's deploy (the next tag under -/// one approval, a dispatch, or the merge), the cache purge when the -/// repository has a purge workflow, then the page checks after them. -pub fn release_only_steps(m: &Mechanics, checks: &[(Vec, Vec)]) -> Vec { +/// The deploys a merge goes through, in order: staging's when a workflow +/// deploys staging, then production's (the next tag under one approval, a +/// dispatch, or the merge), which waits for staging's to succeed. +pub fn deploy_steps(m: &Mechanics) -> Vec { let migration = Release { migrations: vec![PlannedMigration { file: String::new(), @@ -637,21 +768,53 @@ pub fn release_only_steps(m: &Mechanics, checks: &[(Vec, Vec)]) }], ..Default::default() }; - // The deploy and purge steps exactly as a migrating release has them. + // The deploy steps exactly as a migrating release has them. let mut out: Vec = steps(&migration, m) .into_iter() - .filter(|s| (s.kind == Kind::Deploy && s.env == Env::Production) || s.kind == Kind::Purge) + .filter(|s| { + s.kind == Kind::Deploy && (s.env == Env::Production || m.deploy(s.env).is_some()) + }) .collect(); + let mut prev: Option = None; for s in out.iter_mut() { - s.after.clear(); + s.after = prev.clone().into_iter().collect(); + prev = Some(s.id.clone()); } - if let (Some(d), Some(p)) = ( - out.iter() - .find(|s| s.kind == Kind::Deploy) - .map(|s| s.id.clone()), - out.iter_mut().find(|s| s.kind == Kind::Purge), - ) { - p.after = vec![d]; + out +} + +/// The release a merge is followed through when the plan armed none: the +/// deploys that run for it, and only those a workflow does (a repository +/// that deploys outside its workflows has nothing to follow here). +pub fn follow_steps(m: &Mechanics) -> Vec { + deploy_steps(m) + .into_iter() + .filter(|s| s.status != Status::NoAccess) + .collect() +} + +/// A release with no migration: the deploys ([`deploy_steps`]), the cache +/// purge when the repository has a purge workflow, then the page checks +/// after them. +pub fn release_only_steps(m: &Mechanics, checks: &[(Vec, Vec)]) -> Vec { + let migration = Release { + migrations: vec![PlannedMigration { + file: String::new(), + phase: "expand".to_string(), + }], + ..Default::default() + }; + let mut out = deploy_steps(m); + let prod = out + .iter() + .find(|s| s.kind == Kind::Deploy && s.env == Env::Production) + .map(|s| s.id.clone()); + if let Some(mut p) = steps(&migration, m) + .into_iter() + .find(|s| s.kind == Kind::Purge) + { + p.after = prod.into_iter().collect(); + out.push(p); } let last = out.last().map(|s| s.id.clone()); for (i, (urls, find)) in checks.iter().enumerate() { @@ -2188,6 +2351,43 @@ jobs: .contains("Production deploys on a `v*` tag")); } + #[test] + fn path_filters_read_as_github_reads_them() { + assert!(glob_matches("services/api/**", "services/api/src/a.ts")); + assert!(glob_matches("**/*.md", "README.md")); + assert!(glob_matches("**/*.md", "docs/a/b.md")); + assert!(glob_matches("src/*.ts", "src/a.ts")); + assert!(!glob_matches("src/*.ts", "src/x/a.ts")); + assert!(!glob_matches("services/api/**", "apps/web/page.tsx")); + let d = |paths: &[&str], ignore: &[&str]| Deploy { + env: Env::Production, + name: "Deploy".into(), + file: ".github/workflows/deploy.yml".into(), + on: On::Merge("main".into()), + paths: paths.iter().map(|p| p.to_string()).collect(), + paths_ignore: ignore.iter().map(|p| p.to_string()).collect(), + }; + let web = ["apps/web/page.tsx".to_string()]; + let docs = ["docs/a.md".to_string()]; + assert!(!d(&["services/api/**"], &[]).runs_for(&web)); + assert!(d(&["apps/**", "!apps/web/**.md"], &[]).runs_for(&web)); + assert!(!d(&["apps/**", "!apps/web/**"], &[]).runs_for(&web)); + assert!(!d(&[], &["docs/**"]).runs_for(&docs)); + assert!(d(&[], &["docs/**"]).runs_for(&web)); + // Files unknown: taken to run. A tag never reads a path filter. + assert!(d(&["services/api/**"], &[]).runs_for(&[])); + let mut tag = d(&["services/api/**"], &[]); + tag.on = On::Tag("v*".into()); + assert!(tag.runs_for(&web)); + // Read from the workflow: the push trigger's filters, on merge only. + let text = "name: Deploy api\non:\n push:\n branches: [main]\n tags: ['v*']\n paths: ['services/api/**']\njobs:\n production:\n environment: production\n runs-on: ubuntu-latest\n steps:\n - run: ./deploy\n"; + let ds = workflow_deploys(".github/workflows/api.yml", text); + let merge = ds.iter().find(|d| matches!(d.on, On::Merge(_))).unwrap(); + assert_eq!(merge.paths, vec!["services/api/**".to_string()]); + let tagged = ds.iter().find(|d| matches!(d.on, On::Tag(_))).unwrap(); + assert!(tagged.paths.is_empty()); + } + #[test] fn one_migration_that_sets_and_removes_is_sent_back() { let patch = "+export default defineMigration({\n+ migrate: { object(node) {\n+ return [at('newFlag', setIfMissing(node.oldA || node.oldB)), at('oldA', unset()), at('oldB', unset())]\n+ }}\n+})"; diff --git a/services/worker/src/passes/release_run.rs b/services/worker/src/passes/release_run.rs index fdb5d845a..e2dc01ef3 100644 --- a/services/worker/src/passes/release_run.rs +++ b/services/worker/src/passes/release_run.rs @@ -36,7 +36,7 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use tracing::{info, warn}; -use super::release_plan::{self, Kind, On, Planned, Status, Step}; +use super::release_plan::{self, Env, Kind, On, Planned, Status, Step}; use crate::clients::github::GitHubClient; use crate::models::ReleaseStepsMessage; use crate::WorkerState; @@ -255,7 +255,33 @@ pub async fn arm( } let mut context = planned.lines(); context.retain(|l| !l.starts_with(|c: char| c.is_ascii_digit())); - let mut steps = planned.steps.clone(); + arm_steps( + state, + team_id, + installation_id, + (owner, repo, pr_number), + run_id, + (head_branch, base_branch), + planned.steps.clone(), + context, + ) + .await; +} + +/// Saves `steps` as the pull request's release (with a fresh tick chain, +/// so any older chain stops) and starts its ticks. Steps unchanged from +/// the saved release keep their progress. +#[allow(clippy::too_many_arguments)] +async fn arm_steps( + state: &WorkerState, + team_id: &str, + installation_id: u64, + (owner, repo, pr_number): (&str, &str, u64), + run_id: &str, + (head_branch, base_branch): (&str, &str), + mut steps: Vec, + context: Vec, +) { if let Ok(Some(old)) = load(state, team_id, owner, repo, pr_number).await { for s in steps.iter_mut() { if let Some(o) = old @@ -365,6 +391,160 @@ pub async fn after_pr( /// Notice key: a ticket's release steps, one comment per ticket. const NOTICE_RELEASE: &str = "release_steps"; +/// The status slot the release keeps in the pull request's one status +/// comment: said only while a step waits on a person's approval. +const SLOT_RELEASE: &str = "release"; + +/// The deploys a merge goes through, laid over the release already armed +/// (`old`): each deploy step that is not done and now names another +/// workflow or trigger (it waited on a deploy that never runs for this +/// change) is pointed at `fresh`'s, a deploy missing from it is added +/// (staging's before production's, which then waits for it), and every +/// other step keeps what it has. `None` when nothing changes. +pub fn refollow(old: &[Step], fresh: &[Step]) -> Option> { + let mut out = old.to_vec(); + for f in fresh.iter().filter(|f| f.kind == Kind::Deploy) { + match out.iter().position(|o| o.id == f.id) { + Some(i) => { + let o = &out[i]; + if o.status == Status::Done || (o.how == f.how && o.workflow == f.workflow) { + continue; + } + let after = o.after.clone(); + out[i] = Step { after, ..f.clone() }; + } + None => { + let mut s = f.clone(); + s.after.retain(|a| out.iter().any(|o| &o.id == a)); + let at = match f.env { + // Before the first production deploy, which then waits + // for staging's. + Env::Staging => out + .iter() + .position(|o| o.kind == Kind::Deploy && o.env == Env::Production), + Env::Production => None, + }; + match at { + Some(at) => { + if !out[at].after.contains(&s.id) { + out[at].after.push(s.id.clone()); + } + out.insert(at, s); + } + None => out.push(s), + } + } + } + } + (out != old).then_some(out) +} + +/// A merged pull request, whoever merged it: its release follows the +/// deploys that run for the files it changed. A release the plan armed is +/// re-pointed where it waited on a deploy that never runs for this change +/// ([`refollow`]); a pull request with none gets its deploys followed +/// ([`release_plan::follow_steps`]). Each finished step is said on the run +/// page in one line; a step that needs a person's approval is said once on +/// the pull request. Safe to call again: an unchanged release is left as +/// it is, its tick chain running. +pub async fn follow_merge( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + installation_id: u64, + (owner, repo, pr): (&str, &str, u64), + run_id: &str, +) { + let p = match github.get_pull_request(owner, repo, pr).await { + Ok(p) => p, + Err(e) => { + warn!(pr, error = %e, "release: could not read the merged pull request"); + return; + } + }; + let merge_sha = p["merge_commit_sha"].as_str().unwrap_or(""); + if !p["merged"].as_bool().unwrap_or(false) || merge_sha.is_empty() { + return; + } + let base = p["base"]["ref"].as_str().unwrap_or(""); + let head = p["head"]["ref"].as_str().unwrap_or(""); + let changed: Vec = match github.list_pull_files(owner, repo, pr).await { + Ok(f) => f.into_iter().map(|(path, _)| path).collect(), + Err(e) => { + warn!(pr, error = %e, "release: could not list the merged pull request's files"); + Vec::new() + } + }; + let m = super::outside_work::load(github, owner, repo, merge_sha, &[], false) + .await + .release + .for_change(&changed); + let fresh = release_plan::follow_steps(&m); + let old = load(state, team_id, owner, repo, pr).await.ok().flatten(); + let (steps, mut context) = match &old { + None if fresh.is_empty() => return, + None => (fresh, Vec::new()), + Some(o) => match refollow(&o.steps, &fresh) { + None => return, + Some(s) => (s, o.context.clone()), + }, + }; + // The deploy line names the deploys this release now waits on. + context.retain(|l| !l.starts_with("How it deploys:")); + let lines = release_plan::note_lines(&release_plan::Release::default(), &steps, &m); + context.splice( + 0..0, + lines + .into_iter() + .filter(|l| !l.starts_with(|c: char| c.is_ascii_digit())), + ); + let names: Vec = steps + .iter() + .filter(|s| s.kind == Kind::Deploy && !s.status.finished()) + .map(|s| format!("{} ({})", s.env.word(), s.how)) + .collect(); + info!( + pr, + run_id, + steps = steps.len(), + "release: following the merge's deploys" + ); + if !run_id.is_empty() && !names.is_empty() { + super::add_progress_note( + state, + team_id, + run_id, + &format!("Following the merge's deploys: {}", names.join("; then ")), + ) + .await; + } + arm_steps( + state, + team_id, + installation_id, + (owner, repo, pr), + run_id, + (head, base), + steps, + context, + ) + .await; +} + +/// The one short line said on the pull request while a release step waits +/// for a person's approval; `None` when none waits. +pub fn approval_line(steps: &[Step]) -> Option { + let s = steps.iter().find(|s| s.status == Status::Approval)?; + let what = match (&s.trigger, s.env) { + (Some(On::Tag(p)), _) => format!("The production release tag (`{p}`)"), + (_, env) => format!("The {} step \"{}\"", env.word(), s.what), + }; + Some(format!( + "{what} waits for a person's approval on the Agent permissions page, as the team's release \ + settings ask. CoderHelm does the rest once it is approved." + )) +} + async fn load( state: &WorkerState, team: &str, @@ -474,6 +654,7 @@ pub async fn run(state: &WorkerState, msg: ReleaseStepsMessage) -> Result<(), Bo let gate = crate::agent::policy::gate(state, ctx, None).with_wait(Wait::Return); let store = crate::agent::policy::store(state); let before = rec.lines(); + let asked_before = approval_line(&rec.steps); for i in 0..rec.steps.len() { match next(&rec.steps, i, merged) { Next::Wait | Next::Held(_) => {} @@ -625,6 +806,21 @@ pub async fn run(state: &WorkerState, msg: ReleaseStepsMessage) -> Result<(), Bo } } } + // A step waiting on a person's approval is said once, in the pull + // request's one status comment; once decided the line is dropped. + let asked = approval_line(&rec.steps); + if asked != asked_before { + let say = match &asked { + Some(line) => common::conversation::Say::status(SLOT_RELEASE, line.clone()), + None => { + common::conversation::Say::status(SLOT_RELEASE, "The release approval was decided.") + .for_nobody() + } + }; + if let Err(e) = super::conversation::github(&github, owner, repo, pr, say).await { + warn!(pr, error = %e, "release: could not update the approval line"); + } + } if let (Some(d), false) = (again, rec.parked) { let mut next_msg = msg.clone(); next_msg.attempts += 1;