Skip to content

Commit ce18d85

Browse files
committed
Plan check before the first PR; each fix round gets its own budget and never fails an open PR
A complex ticket's plan listed several new files. The first implement pass changed one, the proof check listed the rest as "gaps under Open items" and the PR opened anyway. CoderHelm's reviewer then asked for changes three times; each round re-entered implement inside what was left of one worker invocation, the third was killed mid-way, the stuck-run sweep marked the run failed while its PR was open and green, and nothing said what the round had pushed. Plan coverage (plan_coverage.rs): - The plan's task checklist is compared with the branch's diff, task by task. Missing tasks get up to two implement rounds aimed at exactly them, then a continuation in a fresh invocation (bounded); a continuation keeps its branch and is told what is left. - Planned work still missing stops the run before any PR, with a plain status naming the tasks; the branch is copied to <branch>-wip so a later run's reset can't lose it. Only tasks the plan marks optional may be left out, and the PR names them under Open items with the reason. - The proof judge sees the checklist and reports planned_work; it gets a fix round and is never downgraded to Open items. - tasks.md marks only the tasks the branch did. - A continuation no longer resets its own branch to base. Fix rounds (common::run_round, passes/round.rs): - CI fix, review fix and feedback rounds each run with their own deadline, measured from the invocation they run in, recorded on the run as `round`. A round with too little of its invocation left is parked and runs first in a fresh one; a round that uses its budget with work left continues there (up to three steps). - A round that can't finish leaves the run completed with `round_incomplete` (why, the commits it pushed, the files): "Pull request open; the last fix round didn't finish: <reason>". Feedback and resume errors on a run with an open PR end the same way instead of failed. - The stuck-run sweep waits for a round's own deadline, and a stuck run with an open PR becomes completed with round_incomplete, never failed. No lost work: every coder write is already its own commit on the branch; the coder is told to write each task's files as soon as the task is done, the deadline note asks it to write any finished file before stopping, and an unfinished round records the commits it pushed. API: Run.round_incomplete (OpenAPI), and POST /api/runs/{id}/retry resumes the unfinished round on the same run ("resuming"), giving one automated-fix slot back.
1 parent f1633c8 commit ce18d85

19 files changed

Lines changed: 3443 additions & 204 deletions

File tree

‎docs/api/openapi.json‎

Lines changed: 119 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1977,6 +1977,30 @@
19771977
],
19781978
"type": "object"
19791979
},
1980+
"PushedCommit": {
1981+
"description": "A commit a fix round pushed before it stopped.",
1982+
"properties": {
1983+
"message": {
1984+
"description": "Its subject line.",
1985+
"examples": [
1986+
"WEB-42: Add the gallery tabs"
1987+
],
1988+
"type": "string"
1989+
},
1990+
"sha": {
1991+
"description": "The commit's SHA.",
1992+
"examples": [
1993+
"4f2a9c1e7b3d5a6c8e0f1a2b3c4d5e6f7a8b9c0d"
1994+
],
1995+
"type": "string"
1996+
}
1997+
},
1998+
"required": [
1999+
"sha",
2000+
"message"
2001+
],
2002+
"type": "object"
2003+
},
19802004
"Quarantine": {
19812005
"description": "The tests quarantined for the calling repository.",
19822006
"properties": {
@@ -2657,6 +2681,87 @@
26572681
],
26582682
"type": "object"
26592683
},
2684+
"RoundIncomplete": {
2685+
"description": "The last fix round on the run's open pull request didn't finish. The\nrun's status stays `completed` (the pull request is open); this says\nwhich round stopped, why, and what it pushed.",
2686+
"properties": {
2687+
"at": {
2688+
"description": "When it stopped (RFC 3339).",
2689+
"examples": [
2690+
"2026-10-22T15:40:02Z"
2691+
],
2692+
"type": "string"
2693+
},
2694+
"can_resume": {
2695+
"description": "Whether `POST /api/runs/{run_id}/retry` resumes the round on the same\npull request.",
2696+
"examples": [
2697+
true
2698+
],
2699+
"type": "boolean"
2700+
},
2701+
"files": {
2702+
"description": "The files those commits changed.",
2703+
"examples": [
2704+
[
2705+
"src/blocks/gallery/tabs.tsx"
2706+
]
2707+
],
2708+
"items": {
2709+
"type": "string"
2710+
},
2711+
"type": "array"
2712+
},
2713+
"kind": {
2714+
"description": "The round: `ci_fix` (CI failed and CoderHelm was fixing it),\n`review_fix` (CoderHelm's reviewer asked for changes) or `feedback`\n(a person's review or comments).",
2715+
"examples": [
2716+
"review_fix"
2717+
],
2718+
"type": [
2719+
"string",
2720+
"null"
2721+
]
2722+
},
2723+
"number": {
2724+
"description": "Which fix of the run it was (1 for the first; 0 when not numbered).",
2725+
"examples": [
2726+
3
2727+
],
2728+
"format": "int32",
2729+
"minimum": 0,
2730+
"type": "integer"
2731+
},
2732+
"pushed": {
2733+
"description": "The commits the round pushed to the pull request's branch before it\nstopped, oldest first.",
2734+
"items": {
2735+
"$ref": "#/components/schemas/PushedCommit"
2736+
},
2737+
"type": "array"
2738+
},
2739+
"reason": {
2740+
"description": "Why it stopped, in plain words.",
2741+
"examples": [
2742+
"the review fix round ran out of its time budget 3 times in a row"
2743+
],
2744+
"type": "string"
2745+
},
2746+
"summary": {
2747+
"description": "The run's status as a person reads it.",
2748+
"examples": [
2749+
"Pull request open; the last fix round didn't finish: the review fix round ran out of its time budget 3 times in a row."
2750+
],
2751+
"type": "string"
2752+
}
2753+
},
2754+
"required": [
2755+
"number",
2756+
"reason",
2757+
"summary",
2758+
"pushed",
2759+
"files",
2760+
"at",
2761+
"can_resume"
2762+
],
2763+
"type": "object"
2764+
},
26602765
"Run": {
26612766
"description": "One run, in full.",
26622767
"properties": {
@@ -3036,6 +3141,17 @@
30363141
"null"
30373142
]
30383143
},
3144+
"round_incomplete": {
3145+
"oneOf": [
3146+
{
3147+
"type": "null"
3148+
},
3149+
{
3150+
"$ref": "#/components/schemas/RoundIncomplete",
3151+
"description": "Set when the run's pull request is open but the last fix round on it\n(a CI fix, a review fix or a feedback round) didn't finish. Null\notherwise. Resume it with `POST /api/runs/{run_id}/retry`."
3152+
}
3153+
]
3154+
},
30393155
"run_id": {
30403156
"description": "The run's id, a ULID: the same id as in the path.",
30413157
"examples": [
@@ -3140,7 +3256,7 @@
31403256
"description": "What a run action did.",
31413257
"properties": {
31423258
"status": {
3143-
"description": "`retrying` after a retry, `cancelled` after a cancel.",
3259+
"description": "`retrying` after a retry, `resuming` when a retry resumed the run's\nunfinished fix round, `cancelled` after a cancel.",
31443260
"examples": [
31453261
"retrying"
31463262
],
@@ -6347,7 +6463,7 @@
63476463
},
63486464
"/api/runs/{run_id}/retry": {
63496465
"post": {
6350-
"description": "Starts the run's ticket again as a new run. Only a run that is `failed`, `needs_input`, `needs_outside_change`, `cancelled` or `closed` can be retried; the old run becomes `retried`, so retrying it twice is refused with `400`. Find the new run with `GET /api/runs?q=<ticket id>`.",
6466+
"description": "Starts the run's ticket again as a new run. Only a run that is `failed`, `needs_input`, `needs_outside_change`, `cancelled` or `closed` can be retried; the old run becomes `retried`, so retrying it twice is refused with `400`. Find the new run with `GET /api/runs?q=<ticket id>`.\n\nA `completed` run whose `round_incomplete` is set (its pull request is open but the last fix round on it didn't finish) is resumed instead: the same run picks the round up again on the same pull request, with a fresh time budget, and the answer's status is `resuming`.",
63516467
"operationId": "retryRun",
63526468
"parameters": [
63536469
{
@@ -6373,7 +6489,7 @@
63736489
}
63746490
}
63756491
},
6376-
"description": "The ticket is queued again.",
6492+
"description": "The ticket is queued again (`retrying`), or the unfinished round is resumed on the same run (`resuming`).",
63776493
"headers": {
63786494
"RateLimit-Limit": {
63796495
"description": "Requests this key may make in a minute.",

‎lambda/stuck-run-cleanup/handler.py‎

Lines changed: 126 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,15 @@
1212
checkpoint, else its newest pass trace. A run that reached none of them
1313
stopped before its first pass, and the message says so instead of
1414
"during unknown pass".
15+
16+
Fix rounds (services/common/src/run_round.rs): a CI fix, review fix or
17+
feedback round on an open pull request has its own time budget, recorded on
18+
the run as `round` with a `deadline_at`. The sweep leaves a run alone until
19+
that deadline (plus a grace period) has passed, however long the run itself
20+
has existed. And a stuck run whose pull request is open is never marked
21+
failed: it is completed with `round_incomplete` saying the last round didn't
22+
finish, so the person sees "Pull request open; the last fix round didn't
23+
finish" and can resume it.
1524
"""
1625

1726
import logging
@@ -37,6 +46,17 @@
3746
NOT_A_PASS = {"", "unknown", "cancelled", "closed", "done", "awaiting_ci"}
3847
BEFORE_FIRST_PASS = "before its first pass"
3948

49+
# Mirrors services/common/src/run_round.rs (a test there reads these lines).
50+
ROUND_FIELD = "round"
51+
INCOMPLETE_FIELD = "round_incomplete"
52+
ROUND_BUDGET_SECONDS = 750
53+
ROUND_SWEEP_GRACE_SECONDS = 300
54+
ROUND_LABELS = {
55+
"ci_fix": "CI fix round",
56+
"review_fix": "review fix round",
57+
"feedback": "feedback round",
58+
}
59+
4060
_dynamodb = None
4161

4262

@@ -76,6 +96,83 @@ def failure_message(pass_name):
7696
)
7797

7898

99+
def _parse_time(value):
100+
try:
101+
t = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
102+
except (TypeError, ValueError):
103+
return None
104+
return t if t.tzinfo else t.replace(tzinfo=timezone.utc)
105+
106+
107+
def round_in_budget(run, now):
108+
"""True while the run's fix round is inside its own budget (plus grace).
109+
110+
A round's clock starts when the round does, never when the run started:
111+
a run that is days old can be working a fresh round.
112+
"""
113+
rnd = run.get(ROUND_FIELD) or {}
114+
if not isinstance(rnd, dict) or rnd.get("state", "running") != "running":
115+
return False
116+
deadline = _parse_time(rnd.get("deadline_at"))
117+
if deadline is None:
118+
started = _parse_time(rnd.get("started_at"))
119+
if started is None:
120+
return False
121+
deadline = started + timedelta(seconds=ROUND_BUDGET_SECONDS)
122+
return now < deadline + timedelta(seconds=ROUND_SWEEP_GRACE_SECONDS)
123+
124+
125+
def has_pull_request(run):
126+
try:
127+
number = int(run.get("pr_number") or 0)
128+
except (TypeError, ValueError):
129+
number = 0
130+
return number > 0 or bool((run.get("pr_url") or "").strip())
131+
132+
133+
def round_kind(run, pass_name):
134+
"""The round a stuck run was working: the one it recorded, else the one
135+
its pass points to (the same mapping as run_round::Kind::of_pass)."""
136+
rnd = run.get(ROUND_FIELD) or {}
137+
kind = rnd.get("kind") if isinstance(rnd, dict) else ""
138+
if kind in ROUND_LABELS:
139+
return kind
140+
p = (pass_name or "").split(":")[0]
141+
if p in ("ci_fix", "test"):
142+
return "ci_fix"
143+
if p == "feedback":
144+
return "feedback"
145+
return "review_fix"
146+
147+
148+
def incomplete_reason(kind, pass_name):
149+
label = ROUND_LABELS.get(kind, "fix round")
150+
where = f" during the {pass_name} pass" if pass_name else ""
151+
return f"the {label} stopped{where} without reporting back (time limit)"
152+
153+
154+
def incomplete_record(run, pass_name, now_iso):
155+
"""The `round_incomplete` map for a stuck run whose pull request is open."""
156+
rnd = run.get(ROUND_FIELD) or {}
157+
if not isinstance(rnd, dict):
158+
rnd = {}
159+
kind = round_kind(run, pass_name)
160+
return {
161+
"kind": kind,
162+
"number": rnd.get("number", 0),
163+
"reason": incomplete_reason(kind, pass_name),
164+
"pushed": [],
165+
"files": [],
166+
"at": now_iso,
167+
"feedback": rnd.get("feedback", ""),
168+
"scoped": rnd.get("scoped", True),
169+
}
170+
171+
172+
def status_line(reason):
173+
return f"Pull request open; the last fix round didn't finish: {reason}."
174+
175+
79176
def _checkpoint_pass(team_id, run_id):
80177
if not CHECKPOINTS_TABLE:
81178
return ""
@@ -137,16 +234,21 @@ def handler(event, context):
137234
":awaiting": SWEPT_STATUSES[1],
138235
},
139236
"ProjectionExpression": (
140-
"team_id, run_id, created_at, updated_at, title, current_pass, pass_history, #s"
237+
"team_id, run_id, created_at, updated_at, title, current_pass, pass_history, #s, "
238+
"#round, pr_number, pr_url"
141239
),
142240
}
241+
scan_kwargs["ExpressionAttributeNames"]["#round"] = ROUND_FIELD
143242

144243
while True:
145244
resp = runs_table.scan(**scan_kwargs)
146245
for item in resp.get("Items", []):
147246
updated = item.get("updated_at", item.get("created_at", ""))
148247
status = item.get("status", "")
149248
cutoff = running_cutoff if status == "running" else awaiting_cutoff
249+
if status == "running" and round_in_budget(item, now):
250+
# Its fix round is still inside its own budget.
251+
continue
150252
if updated and updated < cutoff:
151253
stuck_runs.append(item)
152254

@@ -179,9 +281,29 @@ def handler(event, context):
179281

180282
names = {"#s": "status"}
181283
values = {":now": datetime.now(timezone.utc).isoformat(), ":orig": orig_status}
182-
# A stuck "running" run is a hard failure; a stuck "awaiting_ci" run is
183-
# finalized as completed (its PR exists — hand it to a human).
184-
if orig_status == "awaiting_ci":
284+
# A stuck "running" run is a hard failure, unless its pull request is
285+
# open: then a fix round on it stopped, and the run says so instead
286+
# of failing. A stuck "awaiting_ci" run is finalized as completed (its
287+
# PR exists — hand it to a human).
288+
if orig_status == "running" and has_pull_request(run):
289+
now_iso = datetime.now(timezone.utc).isoformat()
290+
record = incomplete_record(run, pass_name, now_iso)
291+
names["#round"] = ROUND_FIELD
292+
names["#inc"] = INCOMPLETE_FIELD
293+
update = (
294+
"SET #s = :new, status_run_id = :sri, #inc = :inc, current_pass = :cp, "
295+
"updated_at = :now REMOVE #round"
296+
)
297+
values.update(
298+
{
299+
":new": "completed",
300+
":sri": f"completed#{run_id}",
301+
":inc": record,
302+
":cp": "done",
303+
}
304+
)
305+
logger.warning(f"Run {run_id}: {status_line(record['reason'])}")
306+
elif orig_status == "awaiting_ci":
185307
update = "SET #s = :new, status_run_id = :sri, error_message = :err, updated_at = :now"
186308
values.update(
187309
{

‎lambda/tests/test_stuck_run_cleanup.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,5 +59,54 @@ def test_closed_is_a_state_not_a_pass(self):
5959
self.assertEqual(sweep.last_known_pass(run), "implement")
6060

6161

62+
class Rounds(unittest.TestCase):
63+
NOW = sweep.datetime(2026, 10, 26, 15, 0, tzinfo=sweep.timezone.utc)
64+
65+
def test_a_round_inside_its_own_budget_is_not_swept(self):
66+
# The run is days old; its round started a few minutes ago.
67+
run = {
68+
"created_at": "2026-10-20T09:00:00+00:00",
69+
"round": {"state": "running", "deadline_at": "2026-10-26T15:05:00+00:00"},
70+
}
71+
self.assertTrue(sweep.round_in_budget(run, self.NOW))
72+
# Past the deadline and the grace period, it is.
73+
late = self.NOW + sweep.timedelta(seconds=300 + sweep.ROUND_SWEEP_GRACE_SECONDS + 1)
74+
self.assertFalse(sweep.round_in_budget(run, late))
75+
76+
def test_a_round_without_a_deadline_uses_its_start_and_the_budget(self):
77+
run = {"round": {"state": "running", "started_at": "2026-10-26T14:55:00+00:00"}}
78+
self.assertTrue(sweep.round_in_budget(run, self.NOW))
79+
80+
def test_a_parked_round_or_no_round_has_no_budget_to_wait_for(self):
81+
self.assertFalse(sweep.round_in_budget({}, self.NOW))
82+
parked = {"round": {"state": "pending", "deadline_at": "2026-10-26T16:00:00+00:00"}}
83+
self.assertFalse(sweep.round_in_budget(parked, self.NOW))
84+
85+
def test_a_stuck_run_with_an_open_pr_is_not_failed(self):
86+
run = {
87+
"pr_number": 41,
88+
"current_pass": "implement",
89+
"round": {"kind": "review_fix", "number": 3, "feedback": "Add the tabs"},
90+
}
91+
self.assertTrue(sweep.has_pull_request(run))
92+
rec = sweep.incomplete_record(run, "implement", "2026-10-26T15:00:00+00:00")
93+
self.assertEqual(rec["kind"], "review_fix")
94+
self.assertEqual(rec["number"], 3)
95+
self.assertEqual(rec["feedback"], "Add the tabs")
96+
line = sweep.status_line(rec["reason"])
97+
self.assertTrue(line.startswith("Pull request open; the last fix round didn't finish:"))
98+
self.assertNotIn("failed", line.lower())
99+
100+
def test_the_round_kind_falls_back_to_the_pass(self):
101+
self.assertEqual(sweep.round_kind({}, "ci_fix:2"), "ci_fix")
102+
self.assertEqual(sweep.round_kind({}, "feedback"), "feedback")
103+
self.assertEqual(sweep.round_kind({}, "implement"), "review_fix")
104+
105+
def test_no_pr_means_no_pr(self):
106+
self.assertFalse(sweep.has_pull_request({}))
107+
self.assertFalse(sweep.has_pull_request({"pr_number": 0, "pr_url": ""}))
108+
self.assertTrue(sweep.has_pull_request({"pr_url": "https://example.com/pull/1"}))
109+
110+
62111
if __name__ == "__main__":
63112
unittest.main()

0 commit comments

Comments
 (0)