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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/incidents/xx_waits_never_outlive_their_event.md
Original file line number Diff line number Diff line change
@@ -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).
34 changes: 34 additions & 0 deletions services/common/src/change_wait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down Expand Up @@ -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 {
Expand Down
14 changes: 11 additions & 3 deletions services/common/src/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
143 changes: 143 additions & 0 deletions services/common/src/run_wake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, AttributeValue>, 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<HashMap<String, AttributeValue>> {
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<String, AttributeValue>,
) -> 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::*;
Expand Down Expand Up @@ -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());
Expand Down
5 changes: 1 addition & 4 deletions services/gateway/src/routes/alerts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:<region>:<account>:<name>` → account, when well-formed.
Expand Down
86 changes: 77 additions & 9 deletions services/gateway/src/routes/github_webhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<WorkerMessage> {
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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}
}
Loading