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
2 changes: 1 addition & 1 deletion docs/api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -6286,7 +6286,7 @@
"detail": {
"description": "Why, or what is still open. May be empty.",
"examples": [
"Open on the pull request: the link check couldn't reach /pricing. Mark it ready once that is dealt with, push a fix or comment on it, and CoderHelm picks it up from there."
"Open on the pull request: the link check couldn't reach /pricing. Push a fix or comment on it, and CoderHelm picks it up from there."
],
"type": "string"
},
Expand Down
5 changes: 5 additions & 0 deletions docs/incidents/wz_waits_go_on_by_themselves.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# wz. `wz_waits_go_on_by_themselves`

**What happened:** A second pass over what CoderHelm showed people found texts that still handed people work CoderHelm does, or promised what didn't happen. A run stopped for a person said "Look at what stopped the run, put it right, then press Retry", and a comment on its ticket was only kept as context, so a person's answer left the run waiting. A merged-ticket stop told people to reply on the ticket as if the reply started a run. A wrong-repo note said "set the repo and re-run" without saying where, after a reason cut in the middle of a word. A tests-and-scope note quoted the coding model's instruction ("Put it back with `restore_file` (omit `from_ref`)"). A fix round wrote that it had no tool to edit the pull request's description and that someone had to paste in the new sections. An outside-change report asked a person to add pull request labels CoderHelm adds itself, and to "run the command yourself". The updater said "press Update again" when AWS was busy, and the access check said to delete a failed stack and press Update again.

**The guarantee:** A run that waits on a person goes on by itself when what it waits for arrives: a comment or reply on its ticket, access granted on GitHub or a repository turned on, or the usage limit raised or reset by a new month. A change it waited for that closed and is reopened takes the run back to waiting, and its merge lets it go on. An answered approval resumes the same run. An alert run resumes when its alert fires again and closes when it clears; its wait says what to do first, then Retry on the run page. Its action names the one thing to do, where, and that the run goes on by itself; only a decision about the run itself (an approval, a person's own stop) waits for that decision. Notes a person reads never carry the coding model's instructions. Every fix round can have the description rebuilt. Pull request labels are CoderHelm's to add. The updater waits out a busy stack or AWS throttling and starts the update again by itself, and a failed stack in another account gets one action for an AWS admin. Tests hold each text to `common::rendered::person_text`.
11 changes: 9 additions & 2 deletions lambda/tests/test_updater_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -706,11 +706,18 @@ def test_a_policy_that_differs_is_never_skipped(self):
u.native_poll(self.store, self.env, base.NOW)
self.assertEqual(len(self.sent), 1, "told once")

def test_an_update_while_stuck_is_refused_in_words(self):
def test_an_update_while_stuck_waits_and_starts_by_itself(self):
# Not a refusal that asks for another press: the update waits like
# one AWS throttled, and starts by itself once the rollback is done.
self.release(json.loads(base.TEMPLATE))
u.fetch_template = lambda url, opener=None: json.dumps(json.loads(base.TEMPLATE)).encode()
with self.assertRaisesRegex(ValueError, "still stuck"):
with self.assertRaises(u.AwsBusy) as busy:
u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update")
self.assertIn("earlier update's rollback", busy.exception.cause)
self.assertNotIn("press update", busy.exception.cause.lower())
# Its failure record, if AWS stays busy past the bound, asks nothing.
d = u.explain_failure(busy.exception.cause, "v1.1.0", "v1.0.0", u.PREPARE, retry_at=base.NOW)
self.assertTrue(d["fix"].startswith("Nothing to do: CoderHelm starts it again by itself"), d["fix"])

def test_an_update_whose_rollback_stops_ends_rolled_back_once_recovered(self):
self.release(json.loads(base.TEMPLATE))
Expand Down
31 changes: 31 additions & 0 deletions lambda/tests/test_updater_busy.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,37 @@ def test_the_status_route_answers_while_aws_is_busy(self):
row = next(h for h in r["history"] if h["id"] == hid)
self.assertEqual((row["status"], row["reason"]), ("preparing", "AWS is busy, retrying (attempt 1)"))

def test_a_busy_stack_waits_and_the_update_starts_by_itself(self):
# "AWS is still working on the install's stack; press Update again
# once it has finished": now a wait, tried again by itself.
self.cfn.stack_status = "UPDATE_IN_PROGRESS"
r = u.handle({"action": "update_now", "version": "v1.1.0", "actor": ADMIN}, ROLE_ENV, self.store, NOW,
fetch=lambda repo: [], probe=lambda env, p: {"results": []})
self.assertEqual(r["request"]["status"], "waiting")
self.assertTrue(no_press(r["request"]["waiting_for"]))
later = NOW + u.BUSY_LIMIT + timedelta(minutes=1)
req = u.follow_request(self.store, ROLE_ENV, later)
row = self.store.get(req["failed_id"])
self.assertIn("still working on the install's stack", row["summary"])
self.assertTrue(row["fix"].startswith("Nothing to do: CoderHelm starts it again by itself"), row["fix"])
self.assertTrue(no_press(row["reason"]))
self.cfn.stack_status = "UPDATE_COMPLETE"
req = u.follow_request(self.store, ROLE_ENV, later + u.BUSY_RETRY_AFTER)
self.assertEqual(req["status"], "started")

def test_an_update_rolled_back_for_throttling_starts_again_by_itself(self):
hid = self.prepared()
later = NOW + timedelta(minutes=20)
u.native_finish(self.store, ROLE_ENV, later, hid, "rolled_back",
"Resource handler returned message: Rate exceeded (Service: Lambda, Status Code: 429)")
row = self.store.get(hid)
at = later + u.BUSY_RETRY_AFTER
self.assertEqual(row["retry_at"], at.isoformat())
self.assertEqual(row["fix"], f"Nothing to do: CoderHelm starts it again by itself at {at.strftime('%H:%M')} UTC.")
self.assertTrue(no_press(row["reason"]))
req = self.store.get("UPDATE_REQUEST")
self.assertEqual((req["status"], req["version"], req["failed_id"]), ("waiting", "v1.1.0", hid))

def test_no_throttling_message_hands_the_retry_to_a_person(self):
raw = "ClientError: An error occurred (Throttling) when calling the DescribeChangeSet operation: Rate exceeded"
for phase in (u.PREPARE, u.ROLLED_BACK):
Expand Down
57 changes: 49 additions & 8 deletions lambda/updater/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,27 @@ def busy_why(e):
return f"{type(e).__name__}: {str(e)[:250]}"


STACK_BUSY = "AWS is still working on the install's stack"


def stack_busy_why(st):
Comment thread
coderhelm[bot] marked this conversation as resolved.
Resolved
"""What a stack that can't take a change yet says, for the update's wait
and its failure record: still working, or finishing an earlier rollback
(which CoderHelm finishes by itself)."""
if st == STUCK:
return f"{STACK_BUSY} ({st}): CoderHelm is finishing an earlier update's rollback by itself"
return f"{STACK_BUSY} ({st})"


def busy_text(raw):
"""True when `raw` (an error's text) says AWS turned calls away for being
busy, or its stack was still working: never the release, and never a
person's job to press again."""
low = (raw or "").lower()
return ("rate exceeded" in low or "throttl" in low or "too many requests" in low
or STACK_BUSY.lower() in low or throttled(Exception(raw or "")))


def retry_time(at):
if isinstance(at, str):
try:
Expand Down Expand Up @@ -2563,11 +2584,15 @@ def native_propose(store, env, version, mode, extra=None, cfn=None, opener=None)
raise ValueError(f"{version} is not a version this install ran before, so it can't be rolled back to")
stack = cfn.describe_stacks(StackName=env["NATIVE_STACK"])["Stacks"][0]
st = stack.get("StackStatus") or ""
if (st == STUCK or st.endswith("_IN_PROGRESS")) and mode == "update":
# Not a refusal: a wait like AWS throttling, tried again by itself
# (busy_request) until the stack is free.
raise AwsBusy(stack_busy_why(st))
if st == STUCK:
raise ValueError("the install's stack is still stuck after an earlier update's rollback stopped; CoderHelm finishes "
"that rollback by itself (Settings, System says how far it is), then press Update again")
"that rollback by itself first (Settings, System says how far it is)")
if st.endswith("_IN_PROGRESS"):
raise ValueError(f"AWS is still working on the install's stack ({st}); press Update again once it has finished")
raise ValueError(f"AWS is still working on the install's stack ({st}); this change can start once it has finished")
overrides = {}
if mode == "domain" and extra:
attach = extra.get("DOMAIN_ACTION") != "remove"
Expand Down Expand Up @@ -5867,15 +5892,23 @@ def _cause(raw, access=None, phase=None, retry_at=None):
if m or "accessdenied" in low or "access denied" in low:
return ("CoderHelm's update role isn't allowed to do something this release needs",
_NEXT_RELEASE + " If that one fails the same way, send the technical details to CoderHelm support.")
if "rate exceeded" in low or "throttl" in low or "too many requests" in low or throttled(Exception(text)):
if STACK_BUSY.lower() in low:
# The stack was still busy for the whole wait: tried again by itself.
what = f"AWS was still working on the install's stack for {int(BUSY_LIMIT.total_seconds() // 60)} minutes while CoderHelm waited"
if retry_at:
return (what, f"Nothing to do: CoderHelm starts it again by itself {retry_time(retry_at)}.")
return (what, "It wasn't the release or the install: run the same change again once the stack has finished.")
if busy_text(text):
# Never the release, and never a person's job to press again.
if phase == PREPARE:
what = f"AWS was busy and kept turning calls away for {int(BUSY_LIMIT.total_seconds() // 60)} minutes while CoderHelm retried"
if retry_at:
return (what, f"Nothing to do: CoderHelm starts it again by itself {retry_time(retry_at)}.")
return (what, "It wasn't the release or the install: try it again once AWS is less busy, in a few minutes.")
return ("AWS was busy and turned some calls away",
"It wasn't the release or the install: try it again once AWS is less busy, in a few minutes.")
else:
what = "AWS was busy and turned some calls away"
if retry_at:
return (what, f"Nothing to do: CoderHelm starts it again by itself {retry_time(retry_at)}.")
# Only a rollback or a switch a person started ends here (an update
# always gets its own retry: native_finish, busy_request).
return (what, "It wasn't the release or the install: try it again once AWS is less busy, in a few minutes.")
if "limitexceeded" in low or "limit exceeded" in low or "quota" in low:
return ("your AWS account reached one of its limits",
"Raise the limit the technical details name (AWS console, Service Quotas) or remove what you don't use, then press Update again.")
Expand Down Expand Up @@ -5935,6 +5968,14 @@ def native_finish(store, env, now, hid, status, reason, phase=None):
if status != "succeeded":
entry = store.get(hid, {}) or {}
phase = phase or (ROLLED_BACK if status == "rolled_back" else STOPPED)
if phase in (PREPARE, ROLLED_BACK) and not entry.get("retry_at") and busy_text(str(reason or "")):
# AWS turned calls away and the stack is back as it was: the
# update starts again by itself, never a person's press.
at = busy_retry_at(entry, now)
if at:
entry["retry_at"] = at.isoformat()
store.put(hid, entry)
busy_retry_later(store, now, entry, at, hid)
access = entry.get("access")
denied = deploy_role_denied(reason) if phase != PREPARE else ""
if denied or PREFLIGHT_MARK.lower() in str(reason or "").lower():
Expand Down
89 changes: 89 additions & 0 deletions services/common/src/change_wait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,48 @@ pub fn settle(pr: Option<(&str, bool)>, dep_run_status: Option<&str>) -> Settled
}
}

/// What a run that stopped because its dependency closed does when the
/// dependency's pull request moves again: reopened, it waits for the merge
/// again; merged, it goes on as any merge does. `None` while it stays
/// closed (or can't be read).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AfterClose {
Reopened,
Merged,
}

/// [`AfterClose`] for the dependency's pull request as GitHub gives it.
pub fn after_close(pr: Option<(&str, bool)>) -> Option<AfterClose> {
match pr {
Some((_, true)) => Some(AfterClose::Merged),
Some(("open", false)) => Some(AfterClose::Reopened),
_ => None,
}
}

/// What the stopped run asks of a person: reopen the change (the run then
/// waits for it again by itself) or change the ticket (a new run starts by
/// itself).
pub fn closed_action(dep: &Dependency) -> String {
format!(
"Reopen {} {CLOSED_ASK} the run goes back to waiting for its merge by itself once it is \
reopened, and a change to the ticket starts a new run by itself",
dep.label()
)
}

/// The words of [`closed_action`] after the change's label.
const CLOSED_ASK: &str = "on GitHub, or change this ticket;";

/// Whether a run's wait, by its action, is the stop [`closed_action`]
/// wrote: its change closed without merging. A run keeps the change it
/// waited on after it went on, so a later wait of another kind (a question,
/// an approval, a person's own stop) is never read as the change closing.
pub fn waits_on_close(action: &str) -> bool {
let a = action.split_whitespace().collect::<Vec<_>>().join(" ");
a.starts_with("Reopen ") && a.contains(CLOSED_ASK)
}

/// The reason a run stops when its dependency closed without merging.
pub fn closed_reason(dep: &Dependency) -> String {
format!(
Expand All @@ -265,6 +307,53 @@ pub fn stuck_line(dep: &Dependency, why: &str) -> String {
format!("Still waiting for {}: {why}.", dep.label())
}

#[cfg(test)]
mod after_close_tests {
use super::*;

#[test]
fn a_reopened_or_merged_change_takes_the_run_back() {
assert_eq!(
after_close(Some(("open", false))),
Some(AfterClose::Reopened)
);
assert_eq!(
after_close(Some(("closed", true))),
Some(AfterClose::Merged)
);
assert_eq!(after_close(Some(("closed", false))), None);
assert_eq!(after_close(None), None);
let a = closed_action(&Dependency::default());
assert!(!a.contains("press Retry"), "{a}");
assert_eq!(crate::rendered::person_text(&a), None, "{a}");
}

#[test]
fn only_the_closed_change_stop_is_read_as_its_change_closing() {
let dep = Dependency {
ticket: "WEB-7".into(),
repo: "acme/bookstore-web".into(),
pr: 12,
..Default::default()
};
assert!(waits_on_close(&closed_action(&dep)));
assert!(waits_on_close(&closed_action(&Dependency::default())));
// As the wait stores it: one line, cut to its limit.
let stored: String = closed_action(&dep).chars().take(200).collect();
assert!(waits_on_close(&stored), "{stored}");
for other in [
"Write the product decision in a comment on the ticket; the run continues by itself \
when the comment arrives",
crate::run_wake::APPROVAL_ACTION,
"Decide whether the run goes on: press Retry on the run in CoderHelm to start it \
again, or leave it stopped",
"",
] {
assert!(!waits_on_close(other), "{other}");
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
Loading