diff --git a/docs/incidents/xx_waits_never_outlive_their_event.md b/docs/incidents/xx_waits_never_outlive_their_event.md new file mode 100644 index 00000000..c8bd4686 --- /dev/null +++ b/docs/incidents/xx_waits_never_outlive_their_event.md @@ -0,0 +1,5 @@ +# xx. `xx_waits_never_outlive_their_event` + +**What happened:** Two waits went on after what they waited for had happened. A run stopped because the change it built on closed without merging was told that reopening the change takes it back to waiting by itself. The change was reopened, and the run kept waiting on a person until the 15-minute sweep: the reopen webhook went on to the review triggers and returned, and the check a pull request event sent read only the runs still waiting for a merge, not the runs that change's close had stopped. On an alert route that waits out a quiet window before posting the recovery, the run waiting on a person for that alert stayed waiting after the recovery posted. Only a recovery posted at once closed it; the later post, made by the worker's episode check, never reached the run. + +**The guarantee:** A pull request closed or reopened sends the team's change check before any return a reopen reaches, and the check names that change. It reads the runs still waiting for a merge and the runs stopped by that change's close, so a reopen takes the stopped run back to waiting at once and a merge sends it on. The 15-minute sweep stays the backstop for every team. A recovery closes its waiting run through one path, `common::run_wake::alert_cleared`, whether it posts at once (the gateway's `alert_delivery`) or after the quiet window (the worker's episode check). diff --git a/services/common/src/change_wait.rs b/services/common/src/change_wait.rs index 4b18ced3..c37e6888 100644 --- a/services/common/src/change_wait.rs +++ b/services/common/src/change_wait.rs @@ -294,6 +294,20 @@ pub fn waits_on_close(action: &str) -> bool { a.starts_with("Reopen ") && a.contains(CLOSED_ASK) } +/// Whether the pull request `pr` of `repo` that moved (a merge, a close, a +/// reopen as GitHub reports it) is the change `dep` waits on. An empty repo +/// or no number (the sweep) reads every dependency. +pub fn moved_is(dep: &Dependency, repo: &str, pr: u64) -> bool { + repo.is_empty() || pr == 0 || (dep.pr == pr && dep.repo.eq_ignore_ascii_case(repo)) +} + +/// Whether a pull request event `action` asks the team's waiting runs to +/// read their change again: a close (merged or not) settles a wait, and a +/// reopen takes a run stopped by that close back to waiting at once. +pub fn event_moves_change(action: &str) -> bool { + matches!(action, "closed" | "reopened") +} + /// The reason a run stops when its dependency closed without merging. pub fn closed_reason(dep: &Dependency) -> String { format!( @@ -328,6 +342,26 @@ mod after_close_tests { assert_eq!(crate::rendered::person_text(&a), None, "{a}"); } + #[test] + fn a_reopen_or_close_reaches_only_the_runs_of_that_change() { + assert!(event_moves_change("reopened")); + assert!(event_moves_change("closed")); + for other in ["opened", "synchronize", "edited", "labeled", ""] { + assert!(!event_moves_change(other), "{other}"); + } + let dep = Dependency { + ticket: "WEB-7".into(), + repo: "acme/bookstore-web".into(), + pr: 12, + ..Default::default() + }; + assert!(moved_is(&dep, "Acme/Bookstore-Web", 12)); + assert!(!moved_is(&dep, "acme/bookstore-web", 13)); + assert!(!moved_is(&dep, "acme/other", 12)); + // The sweep names no change: every dependency is read. + assert!(moved_is(&dep, "", 0)); + } + #[test] fn only_the_closed_change_stop_is_read_as_its_change_closing() { let dep = Dependency { diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index a3915979..af6ea148 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -238,9 +238,11 @@ pub enum WorkerMessage { /// sends one too). #[serde(rename = "role_reads_wait")] RoleReadsWait(RoleReadsWaitMessage), - /// A pull request of the team merged or closed: its runs waiting for - /// another change (`awaiting_change`, `crate::change_wait`) read their - /// dependency again (the self-heal sweep checks every 15 minutes too). + /// A pull request of the team merged, closed or reopened: its runs + /// waiting for another change (`awaiting_change`, `crate::change_wait`) + /// read their dependency again, and a run stopped because that change + /// closed waits for it again (the self-heal sweep checks every 15 + /// minutes too). #[serde(rename = "change_wait_check")] ChangeWaitCheck(ChangeWaitCheckMessage), /// One plugin run: a brief, a schedule or a release (see @@ -952,6 +954,12 @@ pub struct RunWaitingMessage { #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] pub struct ChangeWaitCheckMessage { pub team_id: String, + /// `owner/repo` of the pull request that moved (empty: any). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub repo: String, + /// The pull request that moved (0: any). + #[serde(default)] + pub pr: u64, } /// Re-check the role of a run waiting for the install's "AWS role reads" diff --git a/services/common/src/run_wake.rs b/services/common/src/run_wake.rs index a1f9e948..881c0de2 100644 --- a/services/common/src/run_wake.rs +++ b/services/common/src/run_wake.rs @@ -250,6 +250,125 @@ pub async fn put_back( } } +/// The ticket id of an alert's runs for its fingerprint (stable across +/// repeats), as the gateway gives it when the alert starts a run. +pub fn alert_ticket_id(fingerprint: &str) -> String { + format!( + "ALERT-{}", + crate::content_hash(fingerprint)[..8].to_uppercase() + ) +} + +fn text<'a>(item: &'a HashMap, k: &str) -> &'a str { + item.get(k) + .and_then(|v| v.as_s().ok()) + .map(String::as_str) + .unwrap_or("") +} + +/// The newest run of `ticket_id` for the team. +pub async fn newest_of_ticket( + dynamo: &aws_sdk_dynamodb::Client, + runs_table: &str, + team_id: &str, + ticket_id: &str, +) -> Option> { + let out = dynamo + .query() + .table_name(runs_table) + .index_name("ticket-index") + .key_condition_expression("team_id = :tid AND ticket_id = :ticket") + .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":ticket", AttributeValue::S(ticket_id.to_string())) + .send() + .await + .ok()?; + out.items() + .iter() + .max_by(|a, b| text(a, "run_id").cmp(text(b, "run_id"))) + .cloned() +} + +/// Why a waiting alert run closes when its alert cleared. +pub const ALERT_CLEARED_WHY: &str = "the alert cleared by itself, so nothing is left to fix"; + +/// Closes the waiting alert run `item` whose alert cleared by itself (only +/// while it still waits). Returns whether it closed. +pub async fn close_cleared( + dynamo: &aws_sdk_dynamodb::Client, + runs_table: &str, + team_id: &str, + item: &HashMap, +) -> bool { + use crate::run_ending::EndWrite; + let run_id = text(item, "run_id").to_string(); + let why = ALERT_CLEARED_WHY; + let now = chrono::Utc::now().to_rfc3339(); + let closed = dynamo + .update_item() + .table_name(runs_table) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.clone())) + .update_expression( + "SET #status = :s, status_run_id = :sri, updated_at = :t, \ + progress_notes = list_append(if_not_exists(progress_notes, :empty), :n)", + ) + .condition_expression("#status = :waiting") + .expression_attribute_names("#status", "status") + .run_status( + ":s", + &crate::run_ending::gate( + &run_id, + &crate::run_ending::RunEnd::Stopped(crate::run_ending::Stopped { + reason: crate::run_ending::Stop::ClosedBy { + who: "CoderHelm".into(), + why: why.into(), + }, + tried: Default::default(), + }), + ), + ) + .expression_attribute_values(":waiting", AttributeValue::S(WAITING.into())) + .expression_attribute_values(":empty", AttributeValue::L(vec![])) + .expression_attribute_values( + ":n", + AttributeValue::L(vec![AttributeValue::M(HashMap::from([ + ( + "message".to_string(), + AttributeValue::S(format!("Closed: {why}.")), + ), + ("timestamp".to_string(), AttributeValue::S(now.clone())), + ]))]), + ) + .expression_attribute_values(":t", AttributeValue::S(now)) + .send() + .await; + if closed.is_ok() { + tracing::info!(run_id, "Alert cleared: its waiting run closed"); + } + closed.is_ok() +} + +/// The alert whose runs' ticket is `ticket_id` cleared: its newest run, when +/// it waits on a person, closes ([`alert_wake`] with `cleared`, then +/// [`close_cleared`]). The one path every recovery takes, whether it posts +/// at once or after a route's quiet window. Returns whether a run closed. +pub async fn alert_cleared( + dynamo: &aws_sdk_dynamodb::Client, + runs_table: &str, + team_id: &str, + ticket_id: &str, +) -> bool { + let Some(item) = newest_of_ticket(dynamo, runs_table, team_id, ticket_id).await else { + return false; + }; + let wait = crate::run_wait::WaitingOn::of_item(&item).unwrap_or_default(); + match alert_wake(text(&item, "status"), &wait.handback, true) { + Some(AlertWake::Close) => close_cleared(dynamo, runs_table, team_id, &item).await, + _ => false, + } +} + #[cfg(test)] mod tests { use super::*; @@ -282,6 +401,30 @@ mod tests { ); } + /// A recovery closes its waiting run whatever the run waits on, and + /// whichever way it posts (at once, or after the route's quiet window): + /// both find the run by the same ticket. + #[test] + fn a_cleared_alert_closes_its_waiting_run_however_the_recovery_posts() { + for why in crate::handback::HUMAN_ONLY { + assert_eq!( + alert_wake(WAITING, why.code(), true), + Some(AlertWake::Close), + "{why:?}" + ); + } + assert_eq!(alert_wake(WAITING, "", true), Some(AlertWake::Close)); + // Only a run that waits: a finished or running one is left alone. + assert_eq!(alert_wake("completed", "", true), None); + assert_eq!(alert_wake("running", "", true), None); + let fp = "cloudwatch:example-alarm:eu-west-1"; + let t = alert_ticket_id(fp); + assert!(t.starts_with("ALERT-") && t.len() == 14, "{t}"); + assert_eq!(t, alert_ticket_id(fp)); + assert_ne!(t, alert_ticket_id("cloudwatch:other-alarm:eu-west-1")); + assert_eq!(crate::rendered::person_text(ALERT_CLEARED_WHY), None); + } + #[test] fn a_wake_whose_run_was_not_queued_goes_back_to_waiting() { let s = |v: &str| AttributeValue::S(v.into()); diff --git a/services/gateway/src/routes/alerts.rs b/services/gateway/src/routes/alerts.rs index 08fceabf..49fa18fd 100644 --- a/services/gateway/src/routes/alerts.rs +++ b/services/gateway/src/routes/alerts.rs @@ -387,10 +387,7 @@ pub fn ticket_body(topic_arn: &str, alert: &Alert, instructions: &str) -> String /// Pure: the run's ticket id for an alert fingerprint (stable across repeats). pub fn ticket_id(fingerprint: &str) -> String { - format!( - "ALERT-{}", - common::content_hash(fingerprint)[..8].to_uppercase() - ) + common::run_wake::alert_ticket_id(fingerprint) } /// Pure: `arn:aws:sns:::` → account, when well-formed. diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index c5d1e5bc..418bce4e 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -1983,6 +1983,25 @@ pub(crate) fn rerequest_key(delivery_id: &str, payload: &Value) -> String { } /// Track PR merges for CoderHelm branches — updates run status to "merged". +/// The worker message that has a team's runs waiting on another change read +/// the pull request of `payload` again, for an event that moves it (a +/// close, merged or not, or a reopen). `None` for any other action. +pub fn change_wait_check(action: &str, payload: &Value, team_id: &str) -> Option { + if !common::change_wait::event_moves_change(action) { + return None; + } + Some(WorkerMessage::ChangeWaitCheck( + common::messages::ChangeWaitCheckMessage { + team_id: team_id.to_string(), + repo: payload["repository"]["full_name"] + .as_str() + .unwrap_or("") + .to_string(), + pr: payload["pull_request"]["number"].as_u64().unwrap_or(0), + }, + )) +} + async fn handle_pull_request( state: &AppState, payload: &Value, @@ -2064,6 +2083,17 @@ async fn handle_pull_request( return send_review_job(state, message, head, 0).await; } + // Runs waiting on this change read it again at once + // (`common::change_wait`): a merge resumes them, a close stops them for + // a person, and a reopen takes a run that close stopped back to waiting. + // Before the returns below, since a reopen goes on to the review + // triggers. The worker's 15-minute sweep is the backstop. + if let Some(check) = change_wait_check(action, payload, team_id) { + if let Err(e) = send_to_queue(state, &state.config.ticket_queue_url, &check).await { + warn!(error = ?e, "Could not ask waiting runs to read their change again"); + } + } + // The scorecard: one of CoderHelm's pull requests opened or reopened. if action == "opened" || action == "reopened" { super::scorecard::on_pull_request(state, team_id, payload, action, None).await; @@ -2108,15 +2138,6 @@ async fn handle_pull_request( if action != "closed" { return Ok(StatusCode::OK); } - // Runs waiting for another change to merge read their dependency again - // (`common::change_wait`): a merge resumes them, a close stops them for - // a person. The worker does nothing for a team with no waiting run. - let check = WorkerMessage::ChangeWaitCheck(common::messages::ChangeWaitCheckMessage { - team_id: team_id.to_string(), - }); - if let Err(e) = send_to_queue(state, &state.config.ticket_queue_url, &check).await { - warn!(error = ?e, "Could not ask waiting runs to read their dependency again"); - } // A merge: the open pull requests based on its branch move to its base // (the worker reads the pull request and the repository's setting). if let Some(m) = stack_merged_message(payload, installation_id, team_id, merged) { @@ -6907,3 +6928,50 @@ mod ci_wake_tests { assert!(prs_headed_at(&json!({"message": "Not Found"}), "c0ffee1").is_empty()); } } + +#[cfg(test)] +mod change_wait_check_tests { + use super::{change_wait_check, WorkerMessage}; + use serde_json::json; + + fn event(action: &str) -> serde_json::Value { + json!({ + "action": action, + "repository": {"full_name": "acme/bookstore-web", "name": "bookstore-web", + "owner": {"login": "acme"}}, + "pull_request": {"number": 12, "merged": false}, + }) + } + + /// A reopened change reaches the runs waiting on it as GitHub reports + /// it, not at the next sweep; a close (merged or not) does too. + #[test] + fn a_reopen_or_close_asks_the_waiting_runs_at_once() { + for action in ["reopened", "closed"] { + match change_wait_check(action, &event(action), "T1") { + Some(WorkerMessage::ChangeWaitCheck(m)) => { + assert_eq!(m.team_id, "T1"); + assert_eq!(m.repo, "acme/bookstore-web"); + assert_eq!(m.pr, 12); + } + other => panic!("{action}: {other:?}"), + } + } + for action in ["opened", "synchronize", "labeled", "edited"] { + assert!(change_wait_check(action, &event(action), "T1").is_none()); + } + } + + /// The check is sent before the reopen goes on to the review triggers + /// (which return), so no early return skips it. + #[test] + fn the_check_is_sent_before_any_return_a_reopen_reaches() { + let src = include_str!("github_webhook.rs"); + let handler = src.split("async fn handle_pull_request(").nth(1).unwrap(); + let check = handler + .find("change_wait_check(action, payload, team_id)") + .unwrap(); + let review = handler.find("return handle_review_trigger(").unwrap(); + assert!(check < review); + } +} diff --git a/services/gateway/src/routes/run_wake.rs b/services/gateway/src/routes/run_wake.rs index 1bc5c96a..1fd3dd41 100644 --- a/services/gateway/src/routes/run_wake.rs +++ b/services/gateway/src/routes/run_wake.rs @@ -296,21 +296,13 @@ async fn run_item(state: &AppState, team_id: &str, run_id: &str) -> Option /// The newest run of `ticket_id`, whatever its status. async fn newest_of_ticket(state: &AppState, team_id: &str, ticket_id: &str) -> Option { - let out = state - .dynamo - .query() - .table_name(&state.config.runs_table_name) - .index_name("ticket-index") - .key_condition_expression("team_id = :tid AND ticket_id = :ticket") - .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) - .expression_attribute_values(":ticket", AttributeValue::S(ticket_id.to_string())) - .send() - .await - .ok()?; - out.items() - .iter() - .max_by(|a, b| text(a, "run_id").cmp(text(b, "run_id"))) - .cloned() + run_wake::newest_of_ticket( + &state.dynamo, + &state.config.runs_table_name, + team_id, + ticket_id, + ) + .await } /// The answer to approval `approval_id` sends the run that waited for it @@ -400,70 +392,27 @@ pub async fn alert_delivery( ticket_id: &str, cleared: bool, ) -> bool { + // A clear takes the one path every recovery takes, whether it posts at + // once or after the route's quiet window (`run_wake::alert_cleared`). + if cleared { + return run_wake::alert_cleared( + &state.dynamo, + &state.config.runs_table_name, + team_id, + ticket_id, + ) + .await; + } let Some(item) = newest_of_ticket(state, team_id, ticket_id).await else { return false; }; let wait = WaitingOn::of_item(&item).unwrap_or_default(); - match run_wake::alert_wake(text(&item, "status"), &wait.handback, cleared) { + match run_wake::alert_wake(text(&item, "status"), &wait.handback, false) { Some(run_wake::AlertWake::Resume) => { wake_one(state, team_id, &item, "its alert fired again").await } - Some(run_wake::AlertWake::Close) => close_cleared(state, team_id, &item).await, - None => false, - } -} - -/// Closes a waiting alert run whose alert cleared by itself. -async fn close_cleared(state: &AppState, team_id: &str, item: &Item) -> bool { - let run_id = text(item, "run_id").to_string(); - let why = "the alert cleared by itself, so nothing is left to fix"; - let closed = state - .dynamo - .update_item() - .table_name(&state.config.runs_table_name) - .key("team_id", AttributeValue::S(team_id.to_string())) - .key("run_id", AttributeValue::S(run_id.clone())) - .update_expression( - "SET #status = :s, status_run_id = :sri, updated_at = :t, \ - progress_notes = list_append(if_not_exists(progress_notes, :empty), :n)", - ) - .condition_expression("#status = :waiting") - .expression_attribute_names("#status", "status") - .run_status( - ":s", - &common::run_ending::gate( - &run_id, - &common::run_ending::RunEnd::Stopped(common::run_ending::Stopped { - reason: common::run_ending::Stop::ClosedBy { - who: "CoderHelm".into(), - why: why.into(), - }, - tried: Default::default(), - }), - ), - ) - .expression_attribute_values(":waiting", AttributeValue::S(run_wake::WAITING.into())) - .expression_attribute_values(":empty", AttributeValue::L(vec![])) - .expression_attribute_values( - ":n", - AttributeValue::L(vec![AttributeValue::M(HashMap::from([ - ( - "message".to_string(), - AttributeValue::S(format!("Closed: {why}.")), - ), - ( - "timestamp".to_string(), - AttributeValue::S(chrono::Utc::now().to_rfc3339()), - ), - ]))]), - ) - .expression_attribute_values(":t", AttributeValue::S(chrono::Utc::now().to_rfc3339())) - .send() - .await; - if closed.is_ok() { - info!(run_id, "Alert cleared: its waiting run closed"); + _ => false, } - closed.is_ok() } #[cfg(test)] diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index accbe160..f556fb27 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -1150,7 +1150,7 @@ async fn handle_message_inner(state: Arc, message: models::WorkerMe passes::webhooks::run_waiting(&state, &msg).await; } models::WorkerMessage::ChangeWaitCheck(msg) => { - passes::change_wait::check_all(&state, Some(&msg.team_id)).await; + passes::change_wait::check_change(&state, &msg).await; } models::WorkerMessage::RoleReadsWait(msg) => { passes::role_wait::check(&state, &msg).await; diff --git a/services/worker/src/passes/alert_episodes.rs b/services/worker/src/passes/alert_episodes.rs index 6c93b33a..5ef5445c 100644 --- a/services/worker/src/passes/alert_episodes.rs +++ b/services/worker/src/passes/alert_episodes.rs @@ -98,6 +98,16 @@ pub async fn run(state: &WorkerState, msg: AlertEpisodeCheckMessage) { match applied.decision { Decision::Cleared(ended) => { episodes::post_cleared(&posting, &msg.team_id, &ended).await; + // The recovery is final: its run waiting on a person closes the + // way a recovery posted at once closes it (the gateway's + // `run_wake::alert_delivery` takes the same path). + common::run_wake::alert_cleared( + &state.dynamo, + &state.config.runs_table_name, + &msg.team_id, + &common::run_wake::alert_ticket_id(&msg.fingerprint), + ) + .await; } Decision::Remind => { let Some(ep) = applied.episode else { return }; diff --git a/services/worker/src/passes/change_wait.rs b/services/worker/src/passes/change_wait.rs index 2ae5637f..d67cc4f6 100644 --- a/services/worker/src/passes/change_wait.rs +++ b/services/worker/src/passes/change_wait.rs @@ -211,6 +211,23 @@ pub struct Checked { /// as "needs you" (closed without merging), or left waiting with its /// page saying why (the dependency's run stopped). pub async fn check_all(state: &WorkerState, team: Option<&str>) -> Checked { + check_scoped(state, team, "", 0).await +} + +/// A pull request of the team moved (a merge, a close, a reopen as GitHub +/// reports it): the team's waiting runs read their change again, and a run +/// stopped because this change closed goes back to waiting at once when it +/// is reopened (or on when it merged). The sweep is the backstop. +pub async fn check_change( + state: &WorkerState, + msg: &common::messages::ChangeWaitCheckMessage, +) -> Checked { + check_scoped(state, Some(&msg.team_id), &msg.repo, msg.pr).await +} + +/// [`check_all`], with the stopped runs read only for the change `repo` +/// `pr` that moved (empty and 0: every change). +async fn check_scoped(state: &WorkerState, team: Option<&str>, repo: &str, pr: u64) -> Checked { let mut out = Checked::default(); // Read to the last page either way: one team's waiting runs by the // status index, or every team's runs by key (a capped scan of the runs @@ -263,10 +280,9 @@ pub async fn check_all(state: &WorkerState, team: Option<&str>) -> Checked { } } // Runs that stopped because their change closed: reopened, they wait - // for it again; merged, they go on (the 15-minute sweep reads them). - if team.is_none() { - out.resumed += check_closed(state).await; - } + // for it again; merged, they go on (a pull request event for the team + // reads them at once; the 15-minute sweep reads every team's). + out.resumed += check_closed(state, team, repo, pr).await; info!( waiting = out.waiting, resumed = out.resumed, @@ -279,14 +295,23 @@ pub async fn check_all(state: &WorkerState, team: Option<&str>) -> Checked { /// Every run that stopped because the change it waited for closed: when /// that change is reopened the run waits for it again, and when it merged /// the run goes on. Returns how many went back. -async fn check_closed(state: &WorkerState) -> usize { +async fn check_closed(state: &WorkerState, team: Option<&str>, repo: &str, pr: u64) -> usize { let filter = super::team_runs::Filter { expr: "#s = :n AND attribute_exists(#w)", names: vec![("#s", "status"), ("#w", cw::FIELD)], values: vec![(":n", attr_s(common::run_wake::WAITING))], projection: None, }; - let items = super::team_runs::matching(state, "Runs whose change closed", &filter).await; + let items = match team { + Some(t) => match super::team_runs::of_team(state, t, &filter).await { + Ok(items) => items, + Err(e) => { + warn!(error = %e, "Runs whose change closed couldn't be listed"); + Vec::new() + } + }, + None => super::team_runs::matching(state, "Runs whose change closed", &filter).await, + }; let mut back = 0; for item in items { if s(&item, "status") != common::run_status::NEEDS_INPUT { @@ -302,6 +327,10 @@ async fn check_closed(state: &WorkerState) -> usize { let Some(dep) = Dependency::from_json(s(&item, cw::FIELD)) else { continue; }; + // An event reads only the runs of the change it reports. + if !cw::moved_is(&dep, repo, pr) { + continue; + } let Some((o, r)) = dep.repo.split_once('/') else { continue; }; diff --git a/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs b/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs index 0a2c1777..88d71f52 100644 --- a/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs +++ b/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs @@ -255,7 +255,7 @@ fn a_limit_wait_wakes_when_the_limit_allows_runs_again() { fn a_reopened_change_takes_its_run_back() { assert!(!CHANGE_WAIT.contains("then press Retry")); assert!(CHANGE_WAIT.contains("action: cw::closed_action(&dep),")); - assert!(CHANGE_WAIT.contains("out.resumed += check_closed(state).await;")); + assert!(CHANGE_WAIT.contains("out.resumed += check_closed(state, team, repo, pr).await;")); assert_eq!( common::change_wait::after_close(Some(("open", false))), Some(common::change_wait::AfterClose::Reopened) diff --git a/services/worker/src/passes/incidents/xx_waits_never_outlive_their_event.rs b/services/worker/src/passes/incidents/xx_waits_never_outlive_their_event.rs new file mode 100644 index 00000000..42bc3975 --- /dev/null +++ b/services/worker/src/passes/incidents/xx_waits_never_outlive_their_event.rs @@ -0,0 +1,126 @@ +//! xx. Two waits went on after what they waited for had happened. A run +//! stopped because the change it built on closed was told that reopening +//! the change takes it back to waiting by itself. The change was reopened, +//! but only the 15-minute sweep read stopped runs: the reopen webhook went +//! to the review triggers and returned, and the check a pull request event +//! sent skipped stopped runs. On an alert route that waits out a quiet +//! window before posting the recovery, the run that waited on a person for +//! that alert stayed waiting after the recovery posted: only a recovery +//! posted at once closed it, and the later post (the worker's episode +//! check) never reached the run. +//! +//! Guarantees: a pull request closed or reopened sends the team's change +//! check before any return a reopen reaches, naming the change, and that +//! check reads the runs stopped by that change's close (the sweep stays the +//! backstop for every team). A recovery closes its waiting run through one +//! path, `common::run_wake::alert_cleared`, whether it posts at once (the +//! gateway's `alert_delivery`) or after the quiet window (the worker's +//! episode check). + +use common::change_wait::{self as cw, Dependency}; +use common::run_wake::{self, AlertWake}; + +const GITHUB_WEBHOOK: &str = include_str!("../../../../gateway/src/routes/github_webhook.rs"); +const GATEWAY_WAKE: &str = include_str!("../../../../gateway/src/routes/run_wake.rs"); +const COMMON_WAKE: &str = include_str!("../../../../common/src/run_wake.rs"); +const CHANGE_WAIT: &str = include_str!("../change_wait.rs"); +const EPISODES: &str = include_str!("../alert_episodes.rs"); +const MAIN: &str = include_str!("../../main.rs"); + +fn fn_src<'a>(src: &'a str, head: &str) -> &'a str { + let start = src.find(head).unwrap_or_else(|| panic!("{head} is gone")); + let rest = &src[start..]; + let end = [ + "\nfn ", + "\npub fn ", + "\nasync fn ", + "\npub async fn ", + "\n#[cfg(test)]", + ] + .iter() + .filter_map(|h| rest[1..].find(h).map(|i| i + 1)) + .min() + .unwrap_or(rest.len()); + &rest[..end] +} + +/// The reopen GitHub reports reaches the run stopped by that change's close +/// at once; the sweep is only the backstop. +#[test] +fn a_reopened_change_takes_its_run_back_when_github_reports_it() { + assert!(cw::event_moves_change("reopened")); + assert!(cw::event_moves_change("closed")); + let dep = Dependency { + ticket: "WEB-7".into(), + repo: "acme/bookstore-web".into(), + pr: 12, + ..Default::default() + }; + assert!(cw::moved_is(&dep, "acme/bookstore-web", 12)); + assert!(!cw::moved_is(&dep, "acme/bookstore-web", 99)); + assert!(cw::moved_is(&dep, "", 0), "the sweep reads every change"); + assert_eq!( + cw::after_close(Some(("open", false))), + Some(cw::AfterClose::Reopened) + ); + + // The webhook sends the check before the reopen returns to the review + // triggers. + let handler = GITHUB_WEBHOOK + .split("async fn handle_pull_request(") + .nth(1) + .unwrap(); + let check = handler + .find("change_wait_check(action, payload, team_id)") + .expect("the pull request handler sends the change check"); + assert!(check < handler.find("return handle_review_trigger(").unwrap()); + assert!(check < handler.find("if action != \"closed\"").unwrap()); + + // The worker's check reads the stopped runs of that team for that + // change, not only the sweep. + assert!(MAIN.contains("passes::change_wait::check_change(&state, &msg).await;")); + let scoped = fn_src(CHANGE_WAIT, "async fn check_scoped("); + assert!(scoped.contains("check_closed(state, team, repo, pr)")); + assert!(!scoped.contains("if team.is_none()")); + let closed = fn_src(CHANGE_WAIT, "async fn check_closed("); + assert!(closed.contains("super::team_runs::of_team(state, t, &filter)")); + assert!(closed.contains("cw::moved_is(&dep, repo, pr)")); + assert!(CHANGE_WAIT.contains("check_scoped(state, team, \"\", 0)")); +} + +/// A recovery posted after the quiet window closes the waiting run the +/// way a recovery posted at once does: one path. +#[test] +fn a_later_recovery_closes_its_waiting_run_through_the_same_path() { + for why in common::handback::HUMAN_ONLY { + assert_eq!( + run_wake::alert_wake(run_wake::WAITING, why.code(), true), + Some(AlertWake::Close), + "{why:?}" + ); + } + // Both posts end in the one close. + let gateway = fn_src(GATEWAY_WAKE, "pub async fn alert_delivery("); + assert!(gateway.contains("run_wake::alert_cleared(")); + assert!(!GATEWAY_WAKE.contains("async fn close_cleared(")); + let cleared = EPISODES + .split("Decision::Cleared(ended) =>") + .nth(1) + .unwrap(); + let cleared = &cleared[..cleared.find("Decision::Remind =>").unwrap()]; + assert!(cleared.contains("episodes::post_cleared(")); + assert!(cleared.contains("common::run_wake::alert_cleared(")); + assert!(cleared.contains("common::run_wake::alert_ticket_id(&msg.fingerprint)")); + // The close is written once, in common. + let shared = fn_src(COMMON_WAKE, "pub async fn alert_cleared("); + assert!(shared.contains("alert_wake(text(&item, \"status\"), &wait.handback, true)")); + assert!(shared.contains("close_cleared(dynamo, runs_table, team_id, &item)")); + assert_eq!( + COMMON_WAKE.matches("pub async fn close_cleared(").count(), + 1 + ); + // The gateway's ticket for an alert is the one the worker looks up. + let alerts = include_str!("../../../../gateway/src/routes/alerts.rs"); + let ticket = fn_src(alerts, "pub fn ticket_id("); + assert!(ticket.contains("common::run_wake::alert_ticket_id(fingerprint)")); +}