Skip to content
Merged
5 changes: 5 additions & 0 deletions docs/incidents/dj_new_run_ends_earlier_waits.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# dj. `dj_new_run_ends_earlier_waits`

**What happened:** A booking ticket's run asked a person which booking page to embed and waited. Ten minutes later a comment on the ticket answered it and started a fresh run, which built the pages and opened its pull request. The first run went on waiting, reminded once a day, though its question was long settled. An alarm did the same: each firing started a run beside the one still asking, and two of those were still waiting days after a third had finished the fix. A run waiting on a person was not counted as live, so a new trigger took the ticket over, and nothing ended the old wait.

**The guarantee:** When a fresh run of a ticket takes its claim, every earlier run of that ticket in the same repository that is still waiting on a person stops waiting (`one_run::earlier_waits`, `passes::one_run::end_earlier_waits`). It becomes `retried`, points at the new run, and its page says where the work went. The write only applies while that run still waits. A run that ended any other way is left as it is, and a run of the same ticket in another repository is its own.
5 changes: 5 additions & 0 deletions docs/incidents/dq_unfinished_stop_ships.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# dq. `dq_unfinished_stop_ships`

**What happened:** A run on a large ticket finished 23 of its 38 planned tasks, then spent nine steps reading the same files and writing nothing, because the files it was told were missing already had their planned form. The guard ended it with "CoderHelm stopped this run and handed it to you: it continued 7 times without finishing another task". Another run did the same on one README line: each step re-read the file, thought to the output limit and wrote nothing. The measuring and the cut replies were fixed on their own, and a stuck task now climbs the supervisor's ladder. But the guard's count of continuations without a finished task still ended the run one step after the ladder deferred the first stuck task, in words that hand the work to a person, and the stop stayed on the run, so the draft it shipped could not take a CI fix round.

**The guarantee:** A run whose planned tasks stop moving changes approach first: the ladder (one task, fresh context with edits in place, a re-split, the strongest model, then the task deferred) runs before the guard's count is spent. When the count is spent, the run ships what is done with the rest deferred, and says so. That stop is taken back once the work is on its pull request, so CI's errors and comments start the next round. A CoderHelm limit never hands unfinished work to a person.
5 changes: 5 additions & 0 deletions docs/incidents/fa_stacked_pr_targets_its_base.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# fa. `fa_stacked_pr_targets_its_base`

**What happened:** Two tickets asked for the same change (one for the work, a sibling to merge and deploy it), and two runs built it from the default branch an hour apart. Their one-commit-per-file histories had several commits with the same patch id, so the first ticket's kept branch read as copying the sibling's open pull request. Five retries continued that same kept branch, which still held the same four commits, and stopped before the pull request step each time: the rebase didn't apply, there were too many commits to replay, and the merge failed. A person had to step in.

**The guarantee:** A pull request a run reuses (its own open one, or a reopened one) moves onto the branch the run is stacked on, so its diff shows only this change and matches its description. A base that isn't another open pull request's branch is left alone. A branch that holds another open pull request's own commits (the same hashes) is already built on it: the run takes that branch as its base and doesn't rebuild or force push it again.
5 changes: 5 additions & 0 deletions docs/incidents/fd_red_ci_not_the_changes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# fd. `fd_red_ci_not_the_changes`

**What happened:** A pull request's "E2E on preview" check, a job no workflow webhook reported, was recorded from GitHub's aggregate as an event that named nothing. For eight days every fix round read "Workflow 'unknown' failed (run_id: 0)": no check to compare against the base branch, no job log, nothing to re-run. On another pull request a preview deploy failed on the cloud account's limit (`TooManyUniqueTargetGroupsPerLoadBalancer`); the fix rounds changed nothing, a re-run met the same limit, and the run took its own work out and failed.

**The guarantee:** An event written without a webhook carries the failing checks read from GitHub, the way a webhook writes them: the workflow's name, its run id, its conclusion and the failing jobs (`resume::synthetic_payloads`). No failure is described as a workflow named "unknown" with run id 0 (`resume::collect_ci_failure_info`). A failure whose log shows a limit of the cloud account (`resume::looks_account_limit`) is not the change's: no fix round or re-run is spent on it, nothing is taken out, and the pull request says so and names the repository's cleanup workflow when it has one.
5 changes: 5 additions & 0 deletions docs/incidents/fe_round_work_round_trips.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# fe. `fe_round_work_round_trips`

**What happened:** A pull request touched a route folder spelled `%5Fmarkdown`. Landing the fix round read that file back through a contents URL built with the path as it is; GitHub decoded `%5F` to `_` and answered 404 for a file that was there. The 404 was read as "its work branch wasn't there, so it had saved nothing", and the branch holding the work was deleted, twice. On two other pull requests a fix round ran out of its time budget three steps in a row; the run page said "Resume continues from there", but the next round reset the WIP branch to the pull request's head and did the same work again (20, then 17, then 4 checkpoint commits thrown away on one run).

**The guarantee:** Every contents URL percent-encodes each path segment and the ref (`clients::github::contents_url`), so a path holding `%`, `#`, `?`, a space or brackets is the file it names. A file GitHub won't give back is not a missing branch (`round::fault_of`): the WIP branch and its work are kept, and the CI fix loop deletes the branch only for a fault that calls for a clean start. A new CI or review fix round on a head where a round left unfinished work goes on from that WIP branch, told it is continuing (`round::carried`, `round::picks_up`); a head that moved since starts fresh.
5 changes: 5 additions & 0 deletions docs/incidents/rg_registered_where_the_kind_grows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# rg. `rg_registered_where_the_kind_grows`

**What happened:** Two new-feature runs drafted their pull requests and were blocked "new items aren't registered everywhere their siblings are" for places that register nothing. One run added a validation helper beside a studio's document schemas, and the rule wanted it in the documents index, the desk structure and a one-off data migration that lists, once, the types it rewrote. The other added a `heading` component beside the site's UI components, and the rule wanted it in the site's `package.json`, which only names packages such as `@radix-ui/react-accordion` as dependencies. People closed both drafts. The rule called a file a registry when it named most of a sample of eight siblings, and told places apart by folder names, so a backfill kept in another folder or a generated types file still counted, and a real index of migrations never did.

**The guarantee:** A registry is told from a file that merely names the items by what the file is, never by its folder or a list of names. It lists the kind: more than half of all its existing siblings, by path or as whole strings. It is part of the program: not prose, a test or its fixtures, a file the repository's generators write, or a file whose head says it is generated. And it grew with the kind: when it was written it named fewer of the siblings than it does now. A file that lists them but never grew is noted for a person, and one whose history can't be read isn't checked, so neither blocks. Only a checked registry blocks, and the coder is first told to add the entry itself.
17 changes: 14 additions & 3 deletions lambda/stuck-run-cleanup/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@
REMINDED_FIELD = "wait_reminded_at"
WAIT_REMIND_AFTER_HOURS = 24
QUESTIONS_FIELD = "questions"
# A judged question's default and deadline (worker stop_judge::keep_ask_deadline)
# and the sweep's claim on it: settle_waiting reads them, so the scan must too.
# The scan once left them out, every deadline read as absent, and no default
# was ever taken.
WAIT_FIELDS = ("ask_default", "ask_deadline", "ask_default_taken_at")
# The worker's queue: the reminder and the notice for a named wait go out as
# a `run_waiting` message (services/common/contract/worker_messages.json).
TICKET_QUEUE_URL = os.environ.get("TICKET_QUEUE_URL", "")
Expand Down Expand Up @@ -250,10 +255,15 @@ def said_nothing(run):


def wait_since(run):
"""When the current wait started: its waiting_on, else the last update."""
"""When the current wait started: its waiting_on's `since`, else when its
questions were asked, else when the run was created. Never the last
update: every note moves updated_at, the reminder's own note included,
so a wait counted from it was due its "one" reminder again every day."""
wait = _json(run.get(WAITING_ON_FIELD)) or {}
since = _parse_time(wait.get("since")) if isinstance(wait, dict) else None
return since or _parse_time(run.get("updated_at") or run.get("created_at"))
asked = _json(run.get(QUESTIONS_FIELD)) or {}
asked_at = _parse_time(asked.get("asked_at")) if isinstance(asked, dict) else None
return since or asked_at or _parse_time(run.get("created_at") or run.get("updated_at"))


def reminder_due(run, now):
Expand Down Expand Up @@ -672,7 +682,8 @@ def handler(event, context):
"ProjectionExpression": (
"team_id, run_id, created_at, updated_at, title, current_pass, pass_history, #s, "
"step_queued_at, ceil_passes, ceil_continuations, ceil_worked_secs, ceil_spend_usd, "
"#round, pr_number, pr_url, error_message, #q, #w, #r, #oc, #notes"
"#round, pr_number, pr_url, error_message, #q, #w, #r, #oc, #notes, "
+ ", ".join(WAIT_FIELDS)
),
}
scan_kwargs["ExpressionAttributeNames"]["#round"] = ROUND_FIELD
Expand Down
89 changes: 89 additions & 0 deletions lambda/tests/test_stuck_run_cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,95 @@ def test_a_passed_question_deadline_goes_ahead_with_the_default_once(self):
self.assertEqual(out["waiting_defaulted"], 0)
self.assertNotIn("deadline", [m["why"] for m in sent])

def _sweep_projected(self, runs):
"""The sweep against a table that returns only the fields its scan
names, as DynamoDB does."""
updates, sent = [], []

class Table:
def scan(self, **kw):
names = kw.get("ExpressionAttributeNames", {})
fields = {names.get(f.strip(), f.strip()) for f in kw["ProjectionExpression"].split(",")}
return {"Items": [{k: v for k, v in r.items() if k in fields} for r in runs]}

def update_item(self, **kw):
updates.append(kw)

class Db:
class meta:
class client:
class exceptions:
ConditionalCheckFailedException = KeyError

def Table(self, _name):
return Table()

class Sqs:
def send_message(self, **kw):
sent.append(sweep.json.loads(kw["MessageBody"]))

sweep._dynamodb, sweep._sqs = Db(), Sqs()
old_url, sweep.TICKET_QUEUE_URL = sweep.TICKET_QUEUE_URL, "https://sqs/q"
try:
out = sweep.handler({}, None)
finally:
sweep._dynamodb, sweep._sqs, sweep.TICKET_QUEUE_URL = None, None, old_url
return out, updates, sent

def test_a_stated_default_is_taken_from_what_the_scan_reads(self):
# A run asked which page to embed, said what it would build if no one
# answered in a day, and kept the default and deadline on its record.
# The sweep's scan didn't read those fields, so the default was never
# taken and the run sat waiting, reminded, for days.
run = {
"team_id": "T",
"run_id": "R",
"status": "needs_input",
"created_at": "2026-11-14T15:30:06+00:00",
"updated_at": "2026-11-14T15:38:59+00:00",
"questions": '{"questions":[{"id":"q1","question":"Which booking page?"}],'
'"asked_at":"2026-11-14T15:38:59+00:00"}',
"ask_default": "Build with the live program page",
"ask_deadline": "2026-11-15T15:38:57.195130843+00:00",
"ask_question": "Which booking page?",
}
out, updates, sent = self._sweep_projected([run])
self.assertEqual(out["waiting_defaulted"], 1)
self.assertEqual(out["waiting_reminded"], 0)
self.assertEqual(sent, [{"type": "run_waiting", "team_id": "T", "run_id": "R", "why": "deadline"}])
# Taken once: a record that says so is reminded at most, never defaulted again.
out, _, sent = self._sweep_projected([dict(run, ask_default_taken_at=self.NOW.isoformat())])
self.assertEqual(out["waiting_defaulted"], 0)
self.assertNotIn("deadline", [m["why"] for m in sent])

def test_a_question_is_reminded_once_however_often_its_record_changes(self):
# A run asked before waits were recorded (questions, no waiting_on).
# Each reminder's note moved updated_at, the wait counted from
# updated_at, so the next day it was due again: 15 reminders in 15
# days, one every 24 hours and ten minutes.
run = {
"team_id": "T",
"run_id": "R",
"status": "needs_input",
"created_at": "2026-11-02T21:03:11+00:00",
"questions": '{"questions":[{"id":"q1","question":"Which branch?"}],'
'"asked_at":"2026-11-02T21:12:00+00:00"}',
}
first = sweep.datetime(2026, 11, 6, 16, 41, 19, tzinfo=sweep.timezone.utc)
self.assertTrue(sweep.reminder_due(dict(run, updated_at="2026-11-02T21:12:01+00:00"), first))
# The reminder is sent; its note moves updated_at a second later.
after = dict(
run,
wait_reminded_at="2026-11-06T16:41:18+00:00",
updated_at="2026-11-06T16:41:19+00:00",
)
for days in (1, 2, 14):
self.assertFalse(sweep.reminder_due(after, first + sweep.timedelta(days=days, minutes=10)))
self.assertEqual(sweep.wait_since(after).isoformat(), "2026-11-02T21:12:00+00:00")
out, updates, sent = self._sweep_projected([after])
self.assertEqual(out["waiting_reminded"], 0)
self.assertEqual(sent, [])

def test_without_a_pull_request_it_waits_for_a_retry(self):
wait = sweep.named_wait({"error_message": "stopped"}, "now")
self.assertIn("Retry", wait["action"])
Expand Down
32 changes: 32 additions & 0 deletions services/common/src/one_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,38 @@ pub fn held_note(ticket_id: &str, source: &TicketSource) -> String {
)
}

/// The ticket's earlier runs that still wait on a person (`needs_input`)
/// when fresh run `me` of it starts in `repo` (`owner/name`): `runs` is the
/// ticket's runs as `(run_id, status, repo)`. A waiting run is not live, so a
/// new trigger (a ticket edit, the alert firing again, a hand-queued ticket)
/// starts a fresh run beside it, and the old one went on waiting and being
/// reminded for days, its question already moot. Only runs older than `me`
/// (run ids sort by creation) in the same repository: a ticket worked in two
/// repositories has a run in each.
pub fn earlier_waits<'a>(
me: &str,
repo: &str,
runs: &'a [(String, String, String)],
) -> Vec<&'a str> {
runs.iter()
.filter(|(id, status, r)| {
id.as_str() < me
&& status == crate::run_status::NEEDS_INPUT
&& r.eq_ignore_ascii_case(repo)
})
.map(|(id, _, _)| id.as_str())
.collect()
}

/// The note on an earlier waiting run when a fresh run of its ticket ends
/// its wait.
pub fn ended_wait_note(new_run: &str) -> String {
format!(
"A newer run of this ticket started ({new_run}): this run no longer waits, and the \
ticket's work goes on there."
)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
6 changes: 4 additions & 2 deletions services/common/src/repo_read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,10 @@ pub struct GitHubHost<'a> {
pub auth: String,
}

/// A path's segments percent-encoded for a URL.
fn path_url(p: &str) -> String {
/// A path's segments percent-encoded for a URL: a file whose name holds
/// `%`, `#`, `?`, a space or brackets is the file GitHub serves, never one
/// it decodes to another name (`%5Fmarkdown` read as `_markdown`).
pub fn path_url(p: &str) -> String {
p.split('/')
.map(|s| enc(s).replace('+', "%20"))
.collect::<Vec<_>>()
Expand Down
8 changes: 5 additions & 3 deletions services/gateway/src/routes/alerts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1526,14 +1526,16 @@ async fn start_run(
return Ok(Outcome::DailyCap);
}

let context_hash = common::ticket_context_hash(&alert.title, &alert.body, &[]);
// A firing is the alert opening again, never an edit of its ticket
// (`trigger_gate::alert_firing`).
let (content, reopened) = super::trigger_gate::alert_firing();
match super::trigger_gate::gate_ticket_trigger(
state,
&route.team_id,
tid,
Some(&context_hash),
false,
content,
false,
reopened,
None,
false,
)
Expand Down
17 changes: 14 additions & 3 deletions services/gateway/src/routes/plans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4113,7 +4113,11 @@ async fn github_read_file(
path: &str,
branch: &str,
) -> String {
let url = format!("https://api.github.com/repos/{owner}/{name}/contents/{path}?ref={branch}");
let url = format!(
"https://api.github.com/repos/{owner}/{name}/contents/{}?ref={}",
common::repo_read::path_url(path),
urlencoding::encode(branch)
);
let resp = http
.get(&url)
.header("Authorization", format!("Bearer {token}"))
Expand Down Expand Up @@ -4152,9 +4156,16 @@ async fn github_list_directory(
branch: &str,
) -> String {
let url = if path.is_empty() {
format!("https://api.github.com/repos/{owner}/{name}/contents?ref={branch}")
format!(
"https://api.github.com/repos/{owner}/{name}/contents?ref={}",
urlencoding::encode(branch)
)
} else {
format!("https://api.github.com/repos/{owner}/{name}/contents/{path}?ref={branch}")
format!(
"https://api.github.com/repos/{owner}/{name}/contents/{}?ref={}",
common::repo_read::path_url(path),
urlencoding::encode(branch)
)
};
let resp = http
.get(&url)
Expand Down
3 changes: 2 additions & 1 deletion services/gateway/src/routes/tests_setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ impl Gh<'_> {
async fn file(&self, repo: &str, path: &str, git_ref: &str) -> Result<Option<String>, String> {
let (status, v) = self
.get(&format!(
"/repos/{repo}/contents/{path}?ref={}",
"/repos/{repo}/contents/{}?ref={}",
common::repo_read::path_url(path),
urlencoding::encode(git_ref)
))
.await?;
Expand Down
Loading
Loading