diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 80192c54..bdf0b056 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -5553,6 +5553,94 @@ }, "type": "object" }, + "RunPause": { + "description": "A run paused on the team's monthly token limit. It resumes by itself\nwhen the month turns (`resumes_at`) or as soon as an admin raises the\nlimit.", + "properties": { + "kind": { + "description": "`token_limit`: a model call was refused, the run keeps its work and\ngoes on from where it stopped. `token_room`: a new run waits because\nwhat is left is less than a run like it takes.", + "examples": [ + "token_limit" + ], + "type": "string" + }, + "limit": { + "description": "The limit's name.", + "examples": [ + "new tokens" + ], + "type": "string" + }, + "line": { + "description": "The one line, with the time in UTC.", + "examples": [ + "Paused: this month's token limit is used up (40.3M of 40M). Resumes by itself on Dec 1, 00:00 UTC when the month turns, or as soon as an admin raises the limit." + ], + "type": "string" + }, + "max": { + "description": "The limit.", + "examples": [ + 40000000 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "need": { + "description": "For `token_room`: what a run like this takes.", + "examples": [ + 0 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "resumes_at": { + "description": "When the month turns and it resumes by itself (RFC 3339, UTC).", + "examples": [ + "2026-12-01T00:00:00+00:00" + ], + "type": "string" + }, + "room": { + "description": "For `token_room`: what is left for new runs.", + "examples": [ + 0 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "settings_path": { + "description": "Where an admin raises the limit.", + "examples": [ + "/settings/budget" + ], + "type": "string" + }, + "used": { + "description": "This month's count of that limit.", + "examples": [ + 40300000 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "kind", + "limit", + "used", + "max", + "room", + "need", + "resumes_at", + "line", + "settings_path" + ], + "type": "object" + }, "RunPrReview": { "description": "CoderHelm's latest review verdict on the run's pull request.", "properties": { @@ -5879,6 +5967,17 @@ "null" ] }, + "pause": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunPause", + "description": "A `needs_input` run paused on the team's monthly token limit: it\nresumes by itself (`resumes_at`), so show it as paused, never as\nwaiting for an answer. Null for every other run." + } + ] + }, "pr_number": { "description": "That pull request's number.", "examples": [ @@ -6290,6 +6389,17 @@ ], "type": "string" }, + "pause": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunPause", + "description": "The run waits on the team's monthly token limit and resumes by\nitself: shown as paused, never as a person's step. Null for every\nother wait." + } + ] + }, "since": { "description": "When the wait started (RFC 3339).", "examples": [ @@ -7257,6 +7367,16 @@ "minimum": 0, "type": "integer" }, + "projected_at": { + "description": "When it runs out at this month's pace (RFC 3339), when that falls\nbefore the month turns. Null otherwise.", + "examples": [ + "2026-11-26T14:00:00+00:00" + ], + "type": [ + "string", + "null" + ] + }, "used": { "description": "What it counts so far this month.", "examples": [ @@ -7265,12 +7385,22 @@ "format": "int64", "minimum": 0, "type": "integer" + }, + "warn_level": { + "description": "The warning level it has crossed: 0, 80, 95 or 100 (percent). The\ndashboard warns admins at 80 and 95, once each a month.", + "examples": [ + 80 + ], + "format": "int32", + "minimum": 0, + "type": "integer" } }, "required": [ "kind", "max", - "used" + "used", + "warn_level" ], "type": "object" }, @@ -14513,7 +14643,7 @@ }, "run.needs_input": { "post": { - "description": "The run asked a question on its ticket or pull request and waits for an answer. `error` holds the question. Sent as `POST` to each endpoint subscribed to `run.needs_input` (or to every event).", + "description": "The run asked a question on its ticket or pull request and waits for an answer. `error` holds the question. Sent only for a wait a person ends: a run paused on the token limit sends `run.paused` instead. Sent as `POST` to each endpoint subscribed to `run.needs_input` (or to every event).", "operationId": "event.run.needs_input", "parameters": [ { @@ -14735,6 +14865,230 @@ ] } }, + "run.paused": { + "post": { + "description": "The team's monthly token limit stopped the run, or left too little room for a new one. It waits with its work kept and goes on by itself when the month turns or an admin raises the limit; nobody needs to act. `status` is `needs_input` and `error` holds the pause line with when it resumes. Sent as `POST` to each endpoint subscribed to `run.paused` (or to every event).", + "operationId": "event.run.paused", + "parameters": [ + { + "description": "The event id (`evt_…`). The same on every retry: use it to skip an event you already handled.", + "example": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "in": "header", + "name": "webhook-id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Unix seconds when this attempt was sent. Refuse a request more than 5 minutes off.", + "example": "1792420307", + "in": "header", + "name": "webhook-timestamp", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Space-separated `v1,` signatures: HMAC-SHA256 of `..` keyed with the endpoint's secret (the bytes after `whsec_`, base64-decoded). Two while a rotated secret still signs; accept the request when any matches.", + "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=", + "in": "header", + "name": "webhook-signature", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "examples": { + "event": { + "value": { + "api_version": "2026-10-26", + "created_at": "2026-10-26T14:31:47.512Z", + "data": { + "branch": null, + "created_at": "2026-10-26T14:02:11.000Z", + "error": "Paused: this month's token limit is used up (40.3M of 40M). Resumes by itself on Dec 1, 00:00 UTC when the month turns, or as soon as an admin raises the limit.", + "pr_number": null, + "pr_url": null, + "repo": "example-org/api", + "run_id": "01JBRUN7Q2X9M3V6T8W1K4HZ5C", + "source": "jira", + "status": "needs_input", + "ticket_id": "ENG-142", + "title": "Add rate limiting to the export endpoint", + "updated_at": "2026-10-26T14:31:47.000Z", + "url": "https://coderhelm.example.com/runs/detail/?id=01JBRUN7Q2X9M3V6T8W1K4HZ5C" + }, + "id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2W", + "team_id": "TEAM#7c1f0e2a", + "type": "run.paused" + } + } + }, + "schema": { + "properties": { + "api_version": { + "const": "2026-10-26", + "description": "The version of this event's shape.", + "type": "string" + }, + "created_at": { + "description": "When it happened.", + "format": "date-time", + "type": "string" + }, + "data": { + "properties": { + "branch": { + "description": "The branch CoderHelm works on.", + "type": [ + "string", + "null" + ] + }, + "created_at": { + "description": "When the run started.", + "format": "date-time", + "type": "string" + }, + "error": { + "description": "Why the run failed or what it needs, in plain words.", + "type": [ + "string", + "null" + ] + }, + "pr_number": { + "description": "The pull request CoderHelm opened, once there is one.", + "type": [ + "integer", + "null" + ] + }, + "pr_url": { + "description": "The pull request's address on GitHub.", + "format": "uri", + "type": [ + "string", + "null" + ] + }, + "repo": { + "description": "`owner/name` of the repository the run works in.", + "type": "string" + }, + "run_id": { + "description": "The run's id. `GET /api/runs/{run_id}` returns the whole run.", + "type": "string" + }, + "source": { + "description": "Where the work came from: `github`, `jira` or `alert` today; more may be added.", + "type": "string" + }, + "status": { + "description": "The run's status when the event happened.", + "enum": [ + "running", + "awaiting_ci", + "needs_input", + "needs_outside_change", + "covered_by_pr", + "no_change", + "completed", + "merged", + "failed", + "cancelled", + "closed" + ], + "type": "string" + }, + "ticket_id": { + "description": "The ticket's key or number at its source (empty for a task without one).", + "type": "string" + }, + "title": { + "description": "The ticket or task title.", + "type": "string" + }, + "updated_at": { + "description": "When the run last changed.", + "format": "date-time", + "type": "string" + }, + "url": { + "description": "The run in the CoderHelm dashboard.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "run_id", + "status", + "title", + "repo", + "source", + "ticket_id", + "pr_number", + "pr_url", + "branch", + "error", + "url", + "created_at", + "updated_at" + ], + "type": "object" + }, + "id": { + "description": "The event's id (`evt_` and a ULID). The same on every retry and every endpoint: use it to ignore an event you already handled. Also sent as the `webhook-id` header.", + "type": "string" + }, + "team_id": { + "description": "The CoderHelm team it belongs to (as `GET /api/me` returns it).", + "type": "string" + }, + "type": { + "const": "run.paused", + "description": "The event type.", + "type": "string" + } + }, + "required": [ + "id", + "type", + "created_at", + "team_id", + "api_version", + "data" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "2XX": { + "description": "Received. Answer within 10 seconds; do the work afterwards." + }, + "410": { + "description": "Gone: the delivery is final (not retried). Any 4xx other than 408 and 429 is final." + }, + "5XX": { + "description": "Retried with backoff for about a day, as are timeouts, 408 and 429." + } + }, + "security": [], + "summary": "A run paused on the token limit", + "tags": [ + "Events: Runs" + ] + } + }, "webhook.test": { "post": { "description": "Sent by Send test event in Settings, Webhooks (or the API), to that endpoint only. Never sent by real work. Sent as `POST` to each endpoint subscribed to `webhook.test` (or to every event).", diff --git a/docs/incidents/vo_pass_errors_recover_not_fail.md b/docs/incidents/vo_pass_errors_recover_not_fail.md index 76574b0c..1bf51410 100644 --- a/docs/incidents/vo_pass_errors_recover_not_fail.md +++ b/docs/incidents/vo_pass_errors_recover_not_fail.md @@ -2,4 +2,4 @@ **What happened:** Any error a pass returned that the run had no special case for ended the run as failed, usually with the raw HTTP error as its reason. Some were passing (a 5xx in the middle of the coder's work), some were states CoderHelm could put right itself (a branch that wasn't there, a base branch someone deleted), and the run tried the same thing again in a fresh step without changing anything until its ceilings ran out. -**The guarantee:** Every pass error takes one recovery path before anything is marked failed. It is classified as transient (tried again after a backoff), a state CoderHelm repairs (repaired, then the same pass resumes from its checkpoint, with no second plan and no repeated ticket or pull request), or something only a person has. The same error again with no progress takes the next repair strategy, never the same one. Only a person's step stops a run, as "needs you" with what to do in plain words. An error nobody classified is tried once more and then stops as "needs you", never as failed. Runs left failed on an error CoderHelm now gets past are resumed by the self-heal sweep, on deploy and every 15 minutes, once per run per deploy. +**The guarantee:** Every pass error takes one recovery path before anything is marked failed. It is classified as transient (tried again after a backoff), a state CoderHelm repairs (repaired, then the same pass resumes from its checkpoint, with no second plan and no repeated ticket or pull request), or something only a person has. The same error again with no progress takes the next repair strategy, never the same one. Only a person's step stops a run, as "needs you" with what to do in plain words. An error nobody classified is CoderHelm's own problem: tried again with longer waits, then parked for the self-heal sweep with an internal alert for its maintainers, never a person's step (see `xg`). Runs left failed on an error CoderHelm now gets past are resumed by the self-heal sweep, on deploy and every 15 minutes, once per run per deploy. diff --git a/docs/incidents/xg_token_limit_pauses_and_resumes.md b/docs/incidents/xg_token_limit_pauses_and_resumes.md new file mode 100644 index 00000000..485198fa --- /dev/null +++ b/docs/incidents/xg_token_limit_pauses_and_resumes.md @@ -0,0 +1,5 @@ +# xg. `xg_token_limit_pauses_and_resumes` + +**What happened:** Several runs on one install planned, then stopped at the start of building. Their page said "CoderHelm met an error it doesn't know how to repair, and stopped without trying again: Monthly new tokens limit reached", headed "Look at what stopped the run, put it right, then press Retry" and "Needs a person". The limit is counted per UTC month, but when the month turned nothing resumed them; they waited for hours until a person pressed Retry. The error classifier knew only the older wording of the limit ("limit exceeded"), so the refusal every model call now gives ("limit reached") read as an error nobody knew. No warning came before the limit, and new runs kept starting into it. The same night another run stopped with the same frame because the ticket's branch held a teammate's commits and had no pull request. + +**The guarantee:** A model call the team's token limit refuses is a typed pause, never an unknown error and never a person's step. The run keeps its plan, branch and finished steps; its continuation is kept, and it resumes in place from the step that was refused when the month turns (a schedule at 00:00 UTC on the 1st) or as soon as an admin raises the limit. The run page and the runs list say it in one line, with when it resumes, and the webhook event is `run.paused`, never `run.needs_input`. A new run whose kind takes more than the room left waits for token room instead of starting, and runs already in progress come first on what is left. Admins are warned at 80% and 95%, once each a month, with the day the limit runs out at this month's pace. A teammate's branch is left as it is: the run works on the next free `-N` and says so once. "An error it doesn't know how to repair ... put it right, then press Retry" can't be produced: an error nobody classified is CoderHelm's own problem, with an internal alert, one plain line and retries with longer waits. Runs an older release stopped this way are found by their stored words and go on by themselves after the deploy. diff --git a/docs/self-host/email.md b/docs/self-host/email.md index 119af792..6405836b 100644 --- a/docs/self-host/email.md +++ b/docs/self-host/email.md @@ -16,7 +16,7 @@ A self-hosted install sends the emails it needs, and nothing else until you turn | Team invites | Essential | The only way an invited person learns how to join. | | Plugin approval requests | Essential | A named approver must approve a plugin draft before it publishes. | | Knowledge source sign-in alerts | Essential | Tells admins a knowledge source stopped syncing. | -| Token limit warnings | Essential | Tells the team before work stops at the monthly limit. Each person can turn these off. | +| Token limit warnings | Essential | Tells the team at 80% and 95% of a monthly limit, once each a month, with the day it runs out at this pace, and when it is reached. Runs that reach it pause and go on by themselves. Each person can turn these off. | | Support ticket updates | Essential | Replies and status changes on tickets someone filed. | | Webhook endpoint turned off | Essential | Tells a team's admins when CoderHelm stopped sending to an endpoint that failed for days. | | Two-factor lockout alerts | Essential | Tells admins and owners when someone's two-factor sign-in was paused after too many wrong codes. | diff --git a/infra/lib/api-stack.ts b/infra/lib/api-stack.ts index c28bf9bf..febd5283 100644 --- a/infra/lib/api-stack.ts +++ b/infra/lib/api-stack.ts @@ -439,6 +439,23 @@ export class ApiStack extends cdk.Stack { ], }); + // The month's turn: the token limit's counters start again at 00:00 UTC + // on the 1st, and runs paused on the limit (or waiting for room) go on + // then, not at the next 15-minute tick. Sent at 00:00 and again at 00:01 + // in case the first lands before the new month's counters are read. + new events.Rule(this, "TokenMonthTurnSchedule", { + ruleName: `${prefix}-token-month-turn`, + description: "Resume runs paused on the token limit when the month turns", + schedule: events.Schedule.cron({ minute: "0,1", hour: "0", day: "1" }), + targets: [ + new targets.SqsQueue(this.ticketQueue, { + message: events.RuleTargetInput.fromObject({ + type: "self_heal_sweep", + }), + }), + ], + }); + // Paused agent work: every 5 min, send again the work kept while a // team's agents were paused once the pause has ended (an until-time // passing needs nobody to click anything). Does nothing when no team is diff --git a/infra/lib/email-stack.ts b/infra/lib/email-stack.ts index 4923edcc..ac81011c 100644 --- a/infra/lib/email-stack.ts +++ b/infra/lib/email-stack.ts @@ -201,7 +201,8 @@ export class EmailStack extends cdk.Stack { }); // Token limit emails: one per limit (new tokens, cache read, cache write) - // at 80% and at 100%. {{limit_name}} names the limit. + // at 80%, 95% and 100%, each once a month. {{limit_name}} names the + // limit; {{pace}} says when it runs out at this month's pace. new ses.CfnTemplate(this, "TokenWarningTemplate", { template: { templateName: `${prefix}-token-warning`, @@ -388,7 +389,7 @@ const TOKEN_WARNING_HTML = EMAIL_WRAPPER(`

{{usage_pct}}% of your {{limit_name}} limit used

Your team has used {{used_tokens}} of its {{limit_tokens}} monthly {{limit_name}} limit for {{month}}. - When it reaches the limit, CoderHelm stops starting new work until the month ends or the limit is raised. + {{pace}}

Review token limits `); @@ -396,7 +397,7 @@ const TOKEN_WARNING_HTML = EMAIL_WRAPPER(` const TOKEN_WARNING_TEXT = `{{usage_pct}}% of your {{limit_name}} limit used Your team has used {{used_tokens}} of its {{limit_tokens}} monthly {{limit_name}} limit for {{month}}. -When it reaches the limit, CoderHelm stops starting new work until the month ends or the limit is raised. +{{pace}} Token limits: __APP_URL__/settings/budget`; @@ -404,7 +405,7 @@ const TOKEN_LIMIT_REACHED_HTML = EMAIL_WRAPPER(`

Monthly {{limit_name}} limit reached

Your team has used {{used_tokens}} of its {{limit_tokens}} monthly {{limit_name}} limit for {{month}}. - CoderHelm won't start new work until the month ends or an admin raises or clears this limit. + Runs pause with their work kept and go on by themselves when the month turns or an admin raises or clears this limit.

Review token limits `); @@ -412,7 +413,7 @@ const TOKEN_LIMIT_REACHED_HTML = EMAIL_WRAPPER(` const TOKEN_LIMIT_REACHED_TEXT = `Monthly {{limit_name}} limit reached Your team has used {{used_tokens}} of its {{limit_tokens}} monthly {{limit_name}} limit for {{month}}. -CoderHelm won't start new work until the month ends or an admin raises or clears this limit. +Runs pause with their work kept and go on by themselves when the month turns or an admin raises or clears this limit. Token limits: __APP_URL__/settings/budget`; diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index d8ad85a7..cd499f74 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -295,7 +295,13 @@ def wait_since(run): def reminder_due(run, now): - """One reminder, WAIT_REMIND_AFTER_HOURS into the wait (run_wait::reminder_due).""" + """One reminder, WAIT_REMIND_AFTER_HOURS into the wait (run_wait::reminder_due). + A run paused on the team's token limit (its wait carries a `pause`) waits + on nobody: it resumes by itself when the month turns or the limit is + raised, so it gets no reminder.""" + wait = _json(run.get(WAITING_ON_FIELD)) or {} + if isinstance(wait, dict) and wait.get("pause"): + return False since = wait_since(run) if since is None or now - since < timedelta(hours=WAIT_REMIND_AFTER_HOURS): return False diff --git a/lambda/tests/test_stuck_run_cleanup.py b/lambda/tests/test_stuck_run_cleanup.py index 1b4b1792..4d8ad0ba 100644 --- a/lambda/tests/test_stuck_run_cleanup.py +++ b/lambda/tests/test_stuck_run_cleanup.py @@ -490,6 +490,22 @@ def test_one_reminder_after_the_wait(self): self.assertIn("attribute_not_exists(#r)", updates[0]["ConditionExpression"]) self.assertEqual(sent[0]["why"], "reminder") + def test_a_run_paused_on_the_token_limit_gets_no_reminder(self): + # It waits on nobody: it resumes by itself when the month turns or + # the limit is raised. + wait = sweep.json.dumps({ + "action": "Paused: this month's token limit is used up (40.3M of 40M).", + "since": "2026-11-01T00:00:00+00:00", + "handback": "usage_limit", + "pause": {"kind": "token_limit", "limit": "new tokens", "used": 40300000, + "max": 40000000, "resumes_at": "2026-12-01T00:00:00+00:00"}, + }) + run = {"team_id": "T", "run_id": "R", "status": "needs_input", "waiting_on": wait} + self.assertFalse(sweep.reminder_due(run, self.NOW + sweep.timedelta(days=5))) + out, updates, sent = self._sweep([run]) + self.assertEqual(out["waiting_reminded"], 0) + self.assertEqual(sent, []) + def test_a_run_with_questions_and_a_fresh_wait_is_left_alone(self): run = { "team_id": "T", diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index b003b6cb..7942e01e 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -413,6 +413,9 @@ pub mod ticket_decisions; pub mod ticket_state; /// A team's monthly token limits: new tokens, cache read, cache write. pub mod token_limits; +/// A run the token limit refuses is paused and resumes by itself; new runs +/// wait for room; runs in progress come first (`token_room::plan_wakes`). +pub mod token_room; /// Whether a tool works right now: one failure, one diagnosis, one report. pub mod tool_health; /// Every tool an agent can be given, with its risk (read, write, consequential). diff --git a/services/common/src/mail/golden/token_limit_reached.html b/services/common/src/mail/golden/token_limit_reached.html index 02ce5148..d718c5c8 100644 --- a/services/common/src/mail/golden/token_limit_reached.html +++ b/services/common/src/mail/golden/token_limit_reached.html @@ -24,7 +24,7 @@

Monthly token limit reached, new work waits

 
-

Your team reached its monthly new tokens limit for October 2026. New work waits until an admin raises the limit or the month ends.

Used10.0M
Limit10M
MonthOctober 2026

To go on now, an admin raises the limit in Settings, Usage.

See usage
+

Your team reached its monthly new tokens limit for October 2026. Runs pause with their work kept and go on by themselves when the month turns or an admin raises the limit.

Used10.0M
Limit10M
MonthOctober 2026

To go on now, an admin raises the limit in Settings, Usage.

See usage

Sent for the self-hosted CoderHelm install at helm.example.org; its links go only there. Questions go to its admin, admin@example.org. CoderHelm never asks for your password or sign-in codes by email.

diff --git a/services/common/src/mail/golden/token_limit_reached.txt b/services/common/src/mail/golden/token_limit_reached.txt index ed7f1dba..8170b05b 100644 --- a/services/common/src/mail/golden/token_limit_reached.txt +++ b/services/common/src/mail/golden/token_limit_reached.txt @@ -3,7 +3,7 @@ Subject: Acme CoderHelm: monthly token limit reached, new work waits Monthly token limit reached, new work waits -Your team reached its monthly new tokens limit for October 2026. New work waits until an admin raises the limit or the month ends. +Your team reached its monthly new tokens limit for October 2026. Runs pause with their work kept and go on by themselves when the month turns or an admin raises the limit. Used: 10.0M Limit: 10M diff --git a/services/common/src/mail/golden/token_warning.html b/services/common/src/mail/golden/token_warning.html index 79c6b437..4f5785fe 100644 --- a/services/common/src/mail/golden/token_warning.html +++ b/services/common/src/mail/golden/token_warning.html @@ -24,7 +24,7 @@

81% of the monthly token limit used

 
-

Your team has used 81% of its monthly new tokens limit for October 2026.

Used8.1M
Limit10M
MonthOctober 2026

At 100% new work waits until an admin raises the limit in Settings, Usage, or the month ends. Work already running finishes.

See usage
+

Your team has used 81% of its monthly new tokens limit for October 2026.

Used8.1M
Limit10M
MonthOctober 2026

At this month's pace the limit runs out on Oct 27, 14:00 UTC. Runs that reach it pause and go on by themselves when the month turns or an admin raises the limit.

To keep runs going now, an admin raises the limit in Settings, Usage.

See usage

Sent for the self-hosted CoderHelm install at helm.example.org; its links go only there. Questions go to its admin, admin@example.org. CoderHelm never asks for your password or sign-in codes by email.

diff --git a/services/common/src/mail/golden/token_warning.txt b/services/common/src/mail/golden/token_warning.txt index 20549ac7..0e28058f 100644 --- a/services/common/src/mail/golden/token_warning.txt +++ b/services/common/src/mail/golden/token_warning.txt @@ -9,7 +9,9 @@ Used: 8.1M Limit: 10M Month: October 2026 -At 100% new work waits until an admin raises the limit in Settings, Usage, or the month ends. Work already running finishes. +At this month's pace the limit runs out on Oct 27, 14:00 UTC. Runs that reach it pause and go on by themselves when the month turns or an admin raises the limit. + +To keep runs going now, an admin raises the limit in Settings, Usage. See usage: https://helm.example.org/settings/usage/ diff --git a/services/common/src/mail/golden_tests.rs b/services/common/src/mail/golden_tests.rs index 3a165682..07ca7953 100644 --- a/services/common/src/mail/golden_tests.rs +++ b/services/common/src/mail/golden_tests.rs @@ -64,7 +64,7 @@ fn cases() -> Vec<(&'static str, &'static str, Value, Option<&'static str>)> { ( "token_warning", "token_warning", - json!({"limit_name": "new tokens", "month": "October 2026", "used": "8.1M", "limit": "10M", "pct": 81, "link": format!("{APP}/settings/usage/")}), + json!({"limit_name": "new tokens", "month": "October 2026", "used": "8.1M", "limit": "10M", "pct": 81, "pace": "At this month's pace the limit runs out on Oct 27, 14:00 UTC. Runs that reach it pause and go on by themselves when the month turns or an admin raises the limit.", "link": format!("{APP}/settings/usage/")}), Some("Acme"), ), ( diff --git a/services/common/src/mail/templates.rs b/services/common/src/mail/templates.rs index 13799278..91a4e582 100644 --- a/services/common/src/mail/templates.rs +++ b/services/common/src/mail/templates.rs @@ -425,12 +425,14 @@ pub const TEMPLATES: &[Template] = &[ p("used", Kind::Line(20)), p("limit", Kind::Line(20)), p("pct", Kind::Number), + p("pace", Kind::Text(300)), p("link", Kind::Link), ], body: &[ Part::Para("Your team has used {pct}% of its monthly {limit_name} limit for {month}."), Part::Facts(&[("Used", "{used}"), ("Limit", "{limit}"), ("Month", "{month}")]), - Part::Para("At 100% new work waits until an admin raises the limit in Settings, Usage, or the month ends. Work already running finishes."), + Part::Para("{pace}"), + Part::Para("To keep runs going now, an admin raises the limit in Settings, Usage."), Part::Button("See usage", "link"), ], install_may_send: true, @@ -448,7 +450,7 @@ pub const TEMPLATES: &[Template] = &[ p("link", Kind::Link), ], body: &[ - Part::Para("Your team reached its monthly {limit_name} limit for {month}. New work waits until an admin raises the limit or the month ends."), + Part::Para("Your team reached its monthly {limit_name} limit for {month}. Runs pause with their work kept and go on by themselves when the month turns or an admin raises the limit."), Part::Facts(&[("Used", "{used}"), ("Limit", "{limit}"), ("Month", "{month}")]), Part::Para("To go on now, an admin raises the limit in Settings, Usage."), Part::Button("See usage", "link"), diff --git a/services/common/src/rendered.rs b/services/common/src/rendered.rs index e95e51ce..89185be4 100644 --- a/services/common/src/rendered.rs +++ b/services/common/src/rendered.rs @@ -117,6 +117,14 @@ const HANDOFFS: &[(&str, &str)] = &[ "the run starts by itself once the change is made", ), ("put it right", "names no one action"), + ( + "doesn't know how to repair", + "an error is typed: CoderHelm's own problem goes on by itself, never a person's step", + ), + ( + "an error it doesn't know", + "an error is typed: CoderHelm's own problem goes on by itself, never a person's step", + ), ( "press update again", "the updater tries again by itself, or names an AWS admin's one action", diff --git a/services/common/src/run_fail.rs b/services/common/src/run_fail.rs index 2ab10aed..06708abd 100644 --- a/services/common/src/run_fail.rs +++ b/services/common/src/run_fail.rs @@ -10,11 +10,13 @@ //! //! - [`Cause::Error`]: an error a pass raised, read by //! `run_recovery::ending`. Only one CoderHelm gets past by itself -//! (transient, or a state it repairs) is written as `failed`, in plain -//! words with the raw error kept apart (`error_detail`): the self-heal -//! sweep resumes it from its checkpoint. Anything else stops the run as -//! "needs you" (`needs_input`, with what a person does and why), and no -//! run shows a raw HTTP dump. +//! (transient, a state it repairs, or an error of its own nobody +//! classified, said as that) is written as `failed`, in plain words with +//! the raw error kept apart (`error_detail`): the self-heal sweep resumes +//! it from its checkpoint. A refusal by the team's token limit waits on +//! the limit as a typed pause (`token_room`) and resumes by itself. Only +//! what a person has stops the run as "needs you" (`needs_input`, with +//! what they do and why), and no run shows a raw HTTP dump. //! - [`Cause::Stopped`]: a stop the pass knew the reason for (red checks, //! its review still open, the run guard), typed. It is written as that //! reason and never read again by the error classifier: red CI was read @@ -190,37 +192,52 @@ pub fn update(run_id: &str, f: &RunFailure<'_>, now: &str) -> Update { "", ) }); + // A wait on the token limit carries its typed pause: the run page + // says when it resumes, and the limit's wake finds it. + let wait = crate::run_wait::WaitingOn { + pause: needs.pause.clone(), + ..wait + }; let why = crate::handback::HandBack::new(needs.why, &needs.detail) .unwrap_or_else(|| crate::handback::HandBack::of(needs.why)); crate::run_wait::needs_input_write(run_id, &wait, &why) }; + // What the ticket hears for a wait: a pause is its one line. + let said_of = |needs: &rr::NeedsYou| match &needs.pause { + Some(p) => p.line.clone(), + None => format!("{} {}.", needs.detail, action_of(needs)), + }; let (write, plain, kind, wait, resumable, said) = match &f.cause { // Only an error a pass raised is read by the classifier. Cause::Error(_) => match rr::ending(&raw) { Ending::Parked(c) => { + // An error nobody classified is CoderHelm's own: said as + // that, with what happens next, never as a person's step. + let plain = if c.kind == rr::Kind::Unknown { + rr::own_problem_line(&c) + } else { + c.plain.clone() + }; let w = re::gate( run_id, &RunEnd::Stopped(re::Stopped { reason: re::Stop::Error { kind: c.kind.code().to_string(), - plain: c.plain.clone(), + plain: plain.clone(), }, tried: re::Tried::default(), }), ); - let said = format!("{} CoderHelm resumes the run by itself.", c.plain); - ( - w, - c.plain.clone(), - c.kind.code().to_string(), - None, - true, - said, - ) + let said = if c.kind == rr::Kind::Unknown { + plain.clone() + } else { + format!("{} CoderHelm resumes the run by itself.", c.plain) + }; + (w, plain, c.kind.code().to_string(), None, true, said) } Ending::NeedsYou(c, needs) => { let (w, wo) = needs_you(&needs); - let said = format!("{} {}.", needs.detail, action_of(&needs)); + let said = said_of(&needs); ( w, needs.detail.clone(), @@ -234,7 +251,7 @@ pub fn update(run_id: &str, f: &RunFailure<'_>, now: &str) -> Update { Cause::NeedsYou { needs, .. } => { let kind = needs.kind; let (w, wo) = needs_you(needs); - let said = format!("{} {}.", needs.detail, action_of(needs)); + let said = said_of(needs); ( w, needs.detail.clone(), @@ -418,30 +435,28 @@ mod tests { assert_eq!(u.names["#legacy"], "error"); } - /// An error nobody classified, or one only a person can get past, never - /// ends a run as failed: it waits on a person, saying what to do. + /// An error nobody classified is CoderHelm's own: parked for the + /// self-heal sweep with one plain line, never a person's step and never + /// "an error it doesn't know how to repair". #[test] - fn an_unclassified_error_never_produces_status_failed() { + fn an_unclassified_error_is_coderhelms_own_never_a_persons() { for reason in [ " ", "boom", "Multi-repo pipeline produced no PRs", "HTTP status client error (422 Unprocessable Entity) for url (https://api.github.com/repos/o/r/pulls): {\"message\":\"Validation Failed\"}", - "Monthly token limit exceeded (5 / 4 tokens). Increase your limit in Settings under Token Limit.", ] { let u = update("R1", &RunFailure { cause: Cause::Error(reason), ..Default::default() }, "now"); - assert_ne!(sv(&u, ":failed"), STATUS, "{reason}"); - assert_eq!(sv(&u, ":failed"), crate::run_status::NEEDS_INPUT, "{reason}"); - assert_eq!(sv(&u, ":sri"), "needs_input#R1"); - assert!(u.expression.contains("#wo = :wo")); - assert_eq!(u.names["#wo"], crate::run_wait::FIELD_WAITING_ON); - let wait: crate::run_wait::WaitingOn = - serde_json::from_str(&sv(&u, ":wo")).unwrap(); - assert!(!wait.action.is_empty() && !wait.handback.is_empty()); - assert!(!sv(&u, ":err").contains("https://"), "{reason}"); - assert!(!sv(&u, ":err").contains('{'), "{reason}"); - assert_ne!(u.status, STATUS); - assert!(!u.resumable); + assert_eq!(u.status, STATUS, "{reason}"); + assert!(u.resumable, "{reason}"); + assert!(!u.expression.contains("#wo"), "nobody is waited on: {reason}"); + for text in [sv(&u, ":err"), u.said.clone()] { + assert!(text.contains("problem of CoderHelm's own"), "{text}"); + assert!(!text.contains("doesn't know how to repair"), "{text}"); + assert!(!text.contains("https://"), "{text}"); + assert!(!text.contains('{'), "{text}"); + assert_eq!(crate::rendered::person_text(&text), None, "{text}"); + } } let parked = update( "R1", @@ -455,6 +470,30 @@ mod tests { assert!(parked.resumable); } + /// A model call the token limit refused waits on the limit, typed: the + /// run's wait carries the pause, the page and the ticket say its one line. + #[test] + fn a_token_limit_refusal_waits_as_a_typed_pause() { + for reason in [ + "Monthly new tokens limit reached (40.3M of 40M). New model calls are stopped until \ + the month turns or an admin raises the limit in Settings, Token Limit.", + "Monthly token limit exceeded (5 / 4 tokens). Increase your limit in Settings under Token Limit.", + ] { + let u = update("R1", &RunFailure { cause: Cause::Error(reason), ..Default::default() }, "now"); + assert_eq!(sv(&u, ":failed"), crate::run_status::NEEDS_INPUT, "{reason}"); + assert_eq!(sv(&u, ":kind"), "token_limit"); + assert!(!u.resumable); + let wait: crate::run_wait::WaitingOn = serde_json::from_str(&sv(&u, ":wo")).unwrap(); + assert_eq!(wait.handback, "usage_limit"); + let p = wait.pause.expect("typed pause"); + assert_eq!(wait.action, p.line); + assert_eq!(u.said, p.line); + assert_eq!(sv(&u, ":err"), p.line); + assert!(p.line.starts_with("Paused: this month's token limit is used up"), "{}", p.line); + assert!(!u.said.contains("Retry") && !u.said.contains("doesn't know"), "{}", u.said); + } + } + /// A red CI ending is a typed stop: written as itself, never read by the /// error classifier, never "an error it doesn't know how to repair", /// never "tried again" without a retry, and never resumed as a pause. diff --git a/services/common/src/run_recovery.rs b/services/common/src/run_recovery.rs index 9d840b99..753af176 100644 --- a/services/common/src/run_recovery.rs +++ b/services/common/src/run_recovery.rs @@ -13,9 +13,14 @@ //! - [`Kind::NeedsPerson`]: something only a person has (the human-only //! list in [`crate::handback`]). Only this kind may stop a run, and then //! as "needs you", naming what the person does. -//! - [`Kind::Unknown`]: anything else. It is treated as repairable but -//! unknown: tried again once, then the run stops as "needs you" with the -//! error said in plain words. +//! - [`Kind::TokenLimit`]: a model call the team's monthly token limit +//! refused (`token_room::refusal`). The run pauses with its checkpoint +//! kept and resumes by itself when the month turns or the limit is +//! raised; it never waits on a person ([`usage_limit`]). +//! - [`Kind::Unknown`]: anything else. It is CoderHelm's own problem: tried +//! again with longer waits each time, then parked for the self-heal sweep +//! with an internal alert for CoderHelm's maintainers and one plain line +//! on the run page. It never stops the run for a person. //! //! The same error met again without progress takes the next repair //! strategy, never the same one twice ([`next`]); the attempts are kept on @@ -39,8 +44,9 @@ pub const FIELD_RESUME_MESSAGE: &str = "resume_message"; /// Tries of a transient error with no progress before the run stops. pub const MAX_TRANSIENT_TRIES: usize = 5; -/// Tries of an error nobody classified before the run stops. -pub const MAX_UNKNOWN_TRIES: usize = 1; +/// Tries of an error nobody classified, with longer waits each time, before +/// the run is parked for the self-heal sweep. +pub const MAX_UNKNOWN_TRIES: usize = 3; /// The longest backoff (SQS takes up to 900 seconds). pub const MAX_BACKOFF_SECS: u32 = 600; @@ -51,6 +57,8 @@ pub enum Kind { Transient, Repairable, NeedsPerson, + /// The team's monthly token limit refused a model call: a pause. + TokenLimit, Unknown, } @@ -60,16 +68,26 @@ impl Kind { Kind::Transient => "transient", Kind::Repairable => "repairable", Kind::NeedsPerson => "needs_person", + Kind::TokenLimit => "token_limit", Kind::Unknown => "unknown", } } - /// Whether a run that stopped on this kind is resumed by the self-heal - /// sweep (and so may be parked as failed): only what CoderHelm can get - /// past by itself. + /// Whether CoderHelm gets past this kind by itself: the self-heal + /// sweep resumes a run that stopped on it. pub fn resumable(self) -> bool { matches!(self, Kind::Transient | Kind::Repairable) } + + /// Whether a run that stopped on this kind is parked as `failed` for + /// the self-heal sweep: what CoderHelm gets past by itself, and an error + /// of its own nobody classified (its maintainers are alerted, and a + /// release may fix it; the sweep resumes it only when this release + /// parked it: [`FIELD_ERROR_KIND`] is `unknown`). A token limit pause + /// is woken by the limit, never parked. + pub fn parks(self) -> bool { + self.resumable() || self == Kind::Unknown + } } /// A state CoderHelm can repair. @@ -287,6 +305,12 @@ pub fn classify(text: &str) -> Classified { return mk(Kind::Unknown, None, None); } + // The team's monthly token limit refused a model call, in either + // wording: a pause that resumes by itself, never a person's step. + if crate::token_room::refusal(raw).is_some() { + return mk(Kind::TokenLimit, None, Some(HumanOnly::UsageLimit)); + } + // Only a person has it. if let Some(h) = crate::handback::human_only_in(raw) { return mk(Kind::NeedsPerson, None, Some(h)); @@ -725,6 +749,9 @@ pub enum Next { Repair { repair: Repair, strategy: Strategy }, /// Stop as "needs you". NeedsYou(NeedsYou), + /// CoderHelm's own problem, tried again with no luck: the run is parked + /// for the self-heal sweep, with an internal alert ([`own_problem_line`]). + Park, } /// A run stopped for a person: what they do, and why, in plain words. @@ -741,6 +768,9 @@ pub struct NeedsYou { /// stop was decided (kept as the run's `error_kind`, never read again /// from the words). pub kind: Kind, + /// A wait on the token limit, typed: the run resumes by itself + /// (`token_room`). `None` for every other wait. + pub pause: Option, } /// The backoff before try `n` (0-based) of a transient error. @@ -757,6 +787,7 @@ pub fn next(c: &Classified, ledger: &Ledger, mark: &str) -> Next { Kind::Transient => { if repeats >= MAX_TRANSIENT_TRIES { Next::NeedsYou(NeedsYou { + pause: None, kind: c.kind, why: HumanOnly::Unrepaired, action: crate::run_wake::by_comment( @@ -789,49 +820,67 @@ pub fn next(c: &Classified, ledger: &Ledger, mark: &str) -> Next { None => Next::NeedsYou(unrepaired(c, &repair, repeats)), } } + Kind::TokenLimit => Next::NeedsYou(usage_limit(&c.plain)), Kind::Unknown => { if repeats >= MAX_UNKNOWN_TRIES { - Next::NeedsYou(unknown_stop(c, repeats)) + Next::Park } else { Next::Retry { - delay_secs: backoff_secs(0), + delay_secs: backoff_secs(repeats), } } } } } -/// The stop for an error nobody classified. `retries`: the retries the -/// ledger holds for it. "Tried again" is said only for those: a stop that -/// made none says so, never a retry that didn't happen. -pub fn unknown_stop(c: &Classified, retries: usize) -> NeedsYou { - let tried = match retries { - 0 => "and stopped without trying again".to_string(), - 1 => "tried again once, and met it again".to_string(), - n => format!("tried again {n} times, and met it each time"), - }; - NeedsYou { - kind: c.kind, - why: HumanOnly::Unrepaired, - action: unrepaired_action(), - detail: format!( - "CoderHelm met an error it doesn't know how to repair, {tried}: {}", - c.plain - ), +/// The one plain line for an error nobody classified: CoderHelm's own +/// problem (`person_only::OwnProblem`), with what happens next. Never a +/// person's step: its maintainers get an internal alert and the run goes on +/// by itself. +pub fn own_problem_line(c: &Classified) -> String { + format!( + "{} This is a problem of CoderHelm's own: its maintainers were alerted, and the run \ + goes on by itself from its checkpoint.", + c.plain + ) +} + +/// The wait for the team's token limit: a typed pause ([`crate::token_room::Pause`]) +/// read from the refusal's own words, at `now`. The run resumes by itself +/// when the month turns or an admin raises the limit; nobody is asked to do +/// anything. +pub fn usage_limit_at(reason: &str, now: chrono::DateTime) -> NeedsYou { + match crate::token_room::refusal(reason) { + Some(r) => paused(crate::token_room::Pause::limit_reached(&r, now)), + None => { + let c = Classified { + kind: Kind::NeedsPerson, + repair: None, + person: Some(HumanOnly::UsageLimit), + plain: plain_words(reason.trim(), Kind::NeedsPerson, None, None), + signature: signature(reason, None), + }; + needs_person(&c) + } } } -/// The wait for the team's usage limit: what a person does, and the limit's -/// own words. The one ending every run at the limit takes. +/// [`usage_limit_at`] now. The one ending every run at the limit takes. pub fn usage_limit(reason: &str) -> NeedsYou { - let c = Classified { - kind: Kind::NeedsPerson, - repair: None, - person: Some(HumanOnly::UsageLimit), - plain: plain_words(reason.trim(), Kind::NeedsPerson, None, None), - signature: signature(reason, None), - }; - needs_person(&c) + usage_limit_at(reason, chrono::Utc::now()) +} + +/// The wait for a typed pause on the token limit (a refused call, or a new +/// run with too little room left): its one line is both what the run page +/// says and why. +pub fn paused(p: crate::token_room::Pause) -> NeedsYou { + NeedsYou { + kind: Kind::TokenLimit, + why: HumanOnly::UsageLimit, + action: p.line.clone(), + detail: p.line.clone(), + pause: Some(p), + } } /// The action for an error CoderHelm couldn't get past by itself: the one @@ -880,6 +929,7 @@ fn needs_person(c: &Classified) -> NeedsYou { why, action: person_action(why), detail: c.plain.clone(), + pause: None, } } @@ -926,6 +976,7 @@ fn unrepaired(c: &Classified, repair: &Repair, tried: usize) -> NeedsYou { c.plain, if tried == 1 { "" } else { "s" } ), + pause: None, } } @@ -935,13 +986,12 @@ fn unrepaired(c: &Classified, repair: &Repair, tried: usize) -> NeedsYou { /// error nobody classified never ends a run as `failed`. pub fn ending(reason: &str) -> Ending { let c = classify(reason); - if c.kind.resumable() { + if c.kind.parks() { Ending::Parked(c) } else { - // No ledger here: nothing was tried again. let needs = match c.kind { - Kind::NeedsPerson => needs_person(&c), - _ => unknown_stop(&c, 0), + Kind::TokenLimit => usage_limit(reason), + _ => needs_person(&c), }; Ending::NeedsYou(c, needs) } @@ -1042,7 +1092,7 @@ mod tests { assert!(!n.detail.contains("api.github.com")); break; } - Next::Retry { .. } => panic!("a repairable error is repaired"), + Next::Retry { .. } | Next::Park => panic!("a repairable error is repaired"), } } assert_eq!( @@ -1078,48 +1128,75 @@ mod tests { assert!(delays.iter().all(|d| *d <= MAX_BACKOFF_SECS)); } + /// An error nobody classified is CoderHelm's own: tried again with + /// longer waits, then parked for the self-heal sweep. It never stops the + /// run for a person. #[test] - fn an_unclassified_error_is_retried_once_then_needs_you_never_failed() { + fn an_unclassified_error_is_retried_with_backoff_then_parked_never_a_person() { let c = classify("Something nobody has seen before: frobnicator returned 7"); assert_eq!(c.kind, Kind::Unknown); let mut l = Ledger::default(); - assert!(matches!(next(&c, &l, "m"), Next::Retry { .. })); - l.record(&c, "retry", "m", "t"); - match next(&c, &l, "m") { - Next::NeedsYou(n) => { - assert_eq!(n.why, HumanOnly::Unrepaired); - assert!(n.detail.contains("frobnicator returned")); + let mut delays = Vec::new(); + loop { + match next(&c, &l, "m") { + Next::Retry { delay_secs } => { + delays.push(delay_secs); + l.record(&c, "retry", "m", "t"); + } + Next::Park => break, + other => panic!("an unknown error never waits on a person: {other:?}"), } - other => panic!("{other:?}"), } + assert_eq!(delays, vec![30, 60, 120]); assert!(matches!( ending("Something nobody has seen before"), - Ending::NeedsYou(..) + Ending::Parked(..) )); + let line = own_problem_line(&c); + assert!(line.contains("frobnicator returned"), "{line}"); + assert_eq!(crate::rendered::person_text(&line), None, "{line}"); + assert!(!line.contains("doesn't know how to repair"), "{line}"); } - /// "Tried again" is written only when the ledger holds a retry. + /// A model call the token limit refused, in either wording, is a typed + /// pause: never an unknown error, never a person's step. #[test] - fn tried_again_is_said_only_for_a_recorded_retry() { - let c = classify("Something nobody has seen before: frobnicator returned 7"); - match ending("Something nobody has seen before: frobnicator returned 7") { - Ending::NeedsYou(_, n) => { - assert!(!n.detail.contains("tried again"), "{}", n.detail); - assert!(n.detail.contains("without trying again"), "{}", n.detail); - } - other => panic!("{other:?}"), - } - let mut l = Ledger::default(); - l.record(&c, "retry", "m", "t"); - match next(&c, &l, "m") { - Next::NeedsYou(n) => assert!(n.detail.contains("tried again once"), "{}", n.detail), - other => panic!("{other:?}"), + fn a_token_limit_refusal_is_a_pause() { + for reason in [ + "Monthly new tokens limit reached (40.3M of 40M). New model calls are stopped until \ + the month turns or an admin raises the limit in Settings, Token Limit.", + "Implement failed: Monthly cache write tokens limit reached (8.8M of 8M). New model \ + calls are stopped.", + "Monthly token limit exceeded (5 / 4 tokens). Increase your limit in Settings under \ + Token Limit.", + ] { + let c = classify(reason); + assert_eq!(c.kind, Kind::TokenLimit, "{reason}"); + assert!(!c.kind.parks(), "{reason}"); + let n = match next(&c, &Ledger::default(), "m") { + Next::NeedsYou(n) => n, + other => panic!("{other:?}"), + }; + assert_eq!(n.why, HumanOnly::UsageLimit); + let p = n.pause.clone().expect("typed"); + assert_eq!(n.action, p.line); + assert!(n.action.starts_with("Paused: this month's"), "{}", n.action); + assert!(!n.action.contains("Retry"), "{}", n.action); + assert!(matches!(ending(reason), Ending::NeedsYou(_, ref e) if e.pause.is_some())); } - let n = usage_limit( - "Monthly new tokens limit reached (5M of 4M). New model calls are stopped.", + let at = chrono::DateTime::parse_from_rfc3339("2026-11-30T21:00:00Z") + .unwrap() + .with_timezone(&chrono::Utc); + let n = usage_limit_at( + "Monthly new tokens limit reached (40.3M of 40M). New model calls are stopped.", + at, + ); + assert_eq!(n.kind, Kind::TokenLimit); + assert_eq!( + n.action, + "Paused: this month's token limit is used up (40.3M of 40M). Resumes by itself on \ + Dec 1, 00:00 UTC when the month turns, or as soon as an admin raises the limit." ); - assert_eq!(n.why, HumanOnly::UsageLimit); - assert!(n.action.contains("usage limit")); } #[test] diff --git a/services/common/src/run_wait.rs b/services/common/src/run_wait.rs index 1016288d..27f2d37a 100644 --- a/services/common/src/run_wait.rs +++ b/services/common/src/run_wait.rs @@ -61,6 +61,11 @@ pub struct WaitingOn { /// (`handback::HumanOnly::code`), set by [`NeedsInput::needs_input`]. #[serde(default, skip_serializing_if = "String::is_empty")] pub handback: String, + /// A wait on the team's token limit, typed (`token_room::Pause`): the + /// run resumes by itself when the month turns or the limit is raised, + /// and the run page shows it as paused, never as a person's step. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pause: Option, } fn is_zero(n: &usize) -> bool { @@ -92,6 +97,7 @@ impl WaitingOn { questions: 0, since: now(), handback: String::new(), + pause: None, }) } @@ -105,6 +111,7 @@ impl WaitingOn { questions: 0, since: now(), handback: String::new(), + pause: None, } } diff --git a/services/common/src/token_limits.rs b/services/common/src/token_limits.rs index 588e2cbb..027e46b5 100644 --- a/services/common/src/token_limits.rs +++ b/services/common/src/token_limits.rs @@ -295,10 +295,12 @@ pub fn warning_sk(month: &str, kind: LimitKind, level: u8) -> String { } } -/// The warning level a limit has crossed: 100, 80, or none. +/// The warning level a limit has crossed: 100, 95, 80, or none. Each is +/// sent once a month ([`warning_sk`]). pub fn warning_level(u: &LimitUse) -> Option { match u.pct() { p if p >= 100 => Some(100), + p if p >= 95 => Some(95), p if p >= 80 => Some(80), _ => None, } @@ -617,7 +619,9 @@ mod tests { }; assert_eq!(warning_level(&u(79, 100)), None); assert_eq!(warning_level(&u(80, 100)), Some(80)); - assert_eq!(warning_level(&u(99, 100)), Some(80)); + assert_eq!(warning_level(&u(94, 100)), Some(80)); + assert_eq!(warning_level(&u(95, 100)), Some(95)); + assert_eq!(warning_level(&u(99, 100)), Some(95)); assert_eq!(warning_level(&u(100, 100)), Some(100)); assert_eq!(warning_level(&u(500, 100)), Some(100)); assert_eq!( diff --git a/services/common/src/token_room.rs b/services/common/src/token_room.rs new file mode 100644 index 00000000..8ef485db --- /dev/null +++ b/services/common/src/token_room.rs @@ -0,0 +1,914 @@ +//! A run the team's monthly token limit refuses is paused, never stopped. +//! +//! A model call refused by the limit ("Monthly new tokens limit reached +//! (85.2M of 85M) ...") was read by the error classifier as an error nobody +//! knew, so the run stopped as "met an error it doesn't know how to repair +//! ... then press Retry" and waited on a person for hours after the month +//! had turned. The classifier only knew the older wording ("limit +//! exceeded"); the refusal every model call now gives says "limit reached". +//! +//! Now the limit is a typed state, read in one place ([`refusal`]): +//! +//! - [`PauseKind::TokenLimit`]: a run whose model call the limit refused. +//! It keeps its plan, branch and finished steps; its continuation (the +//! same run, from its checkpoint) is kept on the record and sent when the +//! month turns or an admin raises the limit. +//! - [`PauseKind::TokenRoom`]: a new run that would not fit in what is left +//! of the month's limit, by what runs of its kind took lately +//! ([`estimate`]). It waits instead of starting and dying half way. +//! +//! Runs already in progress come first on the room left ([`plan_wakes`]): +//! a half-finished run is woken before a queued new one, and a new run only +//! takes room the runs in progress don't need ([`start_room`]). +//! +//! A pause is said in one line ([`Pause::line`]) with the time it resumes +//! by itself (the run page shows that time in the viewer's own zone), never +//! as a person's to-do. + +use chrono::{DateTime, Datelike, Duration, TimeZone, Utc}; +use serde::{Deserialize, Serialize}; + +use crate::token_limits::{short_tokens, LimitKind, TokenLimits}; +use crate::usage::UsageTotals; + +/// Where an admin raises the limit (the dashboard's page). +pub const SETTINGS_PATH: &str = "/settings/budget"; + +/// Run attribute: when the token wake last claimed the run (RFC 3339), so +/// two sweeps never send its continuation twice. +pub const FIELD_WOKEN_AT: &str = "token_woken_at"; + +/// A claim older than this is taken again (the send it guarded failed). +pub const CLAIM_STALE_MINS: i64 = 10; + +/// Finished runs of one kind read for an estimate, newest first. +pub const ESTIMATE_RUNS: usize = 20; +/// Fewer finished runs of the kind than this: every kind's runs are read. +pub const MIN_SAME_KIND: usize = 3; + +/// What a paused run waits on. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PauseKind { + /// A model call was refused: this month's limit is used up. + TokenLimit, + /// A new run waits: what is left is less than a run like it takes. + TokenRoom, +} + +/// A run waiting on the token limit, typed (kept in the run's +/// `waiting_on`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Pause { + pub kind: PauseKind, + /// The limit's name ("new tokens"). + pub limit: String, + /// This month's count of that limit, and the limit. + pub used: u64, + pub max: u64, + /// For [`PauseKind::TokenRoom`]: what is left for new runs, and what a + /// run like this takes. + #[serde(default, skip_serializing_if = "is_zero")] + pub room: u64, + #[serde(default, skip_serializing_if = "is_zero")] + pub need: u64, + /// For [`PauseKind::TokenRoom`]: the run had started (it waits before a + /// costly step, not before its first), so it goes first on the room + /// left when it is woken. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub in_progress: bool, + /// When the month turns (RFC 3339, UTC): it resumes by itself then. + pub resumes_at: String, + /// The one line ([`Pause::line`]), with the time in UTC. + #[serde(default)] + pub line: String, + /// Where an admin raises the limit. + #[serde(default)] + pub settings_path: String, +} + +fn is_zero(n: &u64) -> bool { + *n == 0 +} + +/// A limit refusal read back from its words: the limit's name and the two +/// numbers. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refusal { + pub limit: String, + pub used: u64, + pub max: u64, +} + +/// "85.2M", "250K", "1.5K", "900", "1,200": a count as the limit messages +/// write it. +pub fn parse_count(s: &str) -> Option { + let s = s.trim().trim_end_matches(['.', ',']).replace(',', ""); + let (num, mult) = match s.chars().last()? { + 'M' | 'm' => (&s[..s.len() - 1], 1_000_000f64), + 'K' | 'k' => (&s[..s.len() - 1], 1_000f64), + _ => (s.as_str(), 1f64), + }; + let v: f64 = num.trim().parse().ok()?; + (v >= 0.0).then(|| (v * mult).round() as u64) +} + +/// The refusal in `text`, wherever it sits (a pass error, a run's stored +/// error, the words of a stop that wrapped it). Both wordings are read: +/// every model call's "Monthly {limit} limit reached (85.2M of 85M)" +/// (`token_limits::call_refused_reason`) and the start check's "Monthly +/// {limit} limit exceeded (5 / 4 tokens)". +pub fn refusal(text: &str) -> Option { + let low = text.to_ascii_lowercase(); + let mut from = 0; + while let Some(i) = low[from..].find("monthly ") { + let at = from + i + "monthly ".len(); + from = at; + let rest = &low[at..]; + let Some((limit, after)) = [" limit reached (", " limit exceeded ("] + .iter() + .find_map(|m| rest.find(m).map(|j| (&rest[..j], &rest[j + m.len()..]))) + else { + continue; + }; + if limit.is_empty() || limit.len() > 40 || limit.contains('.') { + continue; + } + let Some(close) = after.find(')') else { + continue; + }; + // The original case for the numbers ("85.2M"). + let start = text.len() - after.len(); + let inside = &text[start..start + close]; + let Some((a, b)) = inside + .split_once(" of ") + .or_else(|| inside.split_once(" / ")) + else { + continue; + }; + let b = b.split_whitespace().next().unwrap_or(""); + if let (Some(used), Some(max)) = (parse_count(a), parse_count(b)) { + return Some(Refusal { + limit: limit.trim().to_string(), + used, + max, + }); + } + } + None +} + +/// 00:00 UTC on the first day of the month after `now`'s: when the month's +/// counters start again. +pub fn month_turn(now: DateTime) -> DateTime { + let (y, m) = if now.month() == 12 { + (now.year() + 1, 1) + } else { + (now.year(), now.month() + 1) + }; + Utc.with_ymd_and_hms(y, m, 1, 0, 0, 0) + .single() + .unwrap_or(now + Duration::days(31)) +} + +/// 00:00 UTC on the first day of `now`'s month. +pub fn month_start(now: DateTime) -> DateTime { + Utc.with_ymd_and_hms(now.year(), now.month(), 1, 0, 0, 0) + .single() + .unwrap_or(now) +} + +/// "Dec 1, 00:00 UTC". +pub fn utc_label(t: DateTime) -> String { + t.format("%b %-d, %H:%M UTC").to_string() +} + +/// "this month's token limit" (the new tokens limit, or the old single +/// one), else "this month's cache read tokens limit". +fn limit_phrase(limit: &str) -> String { + match limit.trim() { + "" | "new tokens" | "token" => "this month's token limit".to_string(), + other => format!("this month's {other} limit"), + } +} + +impl Pause { + /// The pause for a refused model call at `now`. + pub fn limit_reached(r: &Refusal, now: DateTime) -> Pause { + Pause { + kind: PauseKind::TokenLimit, + limit: r.limit.clone(), + used: r.used, + max: r.max, + room: 0, + need: 0, + in_progress: false, + resumes_at: month_turn(now).to_rfc3339(), + line: String::new(), + settings_path: SETTINGS_PATH.to_string(), + } + .with_line() + } + + /// The wait of a new run with `room` left for it and `need` to run. + pub fn no_room( + limit: &str, + used: u64, + max: u64, + room: u64, + need: u64, + now: DateTime, + ) -> Pause { + Pause { + kind: PauseKind::TokenRoom, + limit: limit.to_string(), + used, + max, + room, + need, + in_progress: false, + resumes_at: month_turn(now).to_rfc3339(), + line: String::new(), + settings_path: SETTINGS_PATH.to_string(), + } + .with_line() + } + + /// The wait of a run already under way, before a costly step: `room` + /// left and `need` for the rest of it. + pub fn no_room_mid_run( + limit: &str, + used: u64, + max: u64, + room: u64, + need: u64, + now: DateTime, + ) -> Pause { + Pause { + in_progress: true, + ..Pause::no_room(limit, used, max, room, need, now) + } + .with_line() + } + + /// Whether the run had started: it goes first when woken. + pub fn mid_run(&self) -> bool { + self.kind == PauseKind::TokenLimit || self.in_progress + } + + fn with_line(mut self) -> Self { + self.line = self.line(); + self + } + + /// When it resumes by itself. + pub fn resumes(&self) -> Option> { + DateTime::parse_from_rfc3339(&self.resumes_at) + .ok() + .map(|t| t.with_timezone(&Utc)) + } + + /// The one line the run page, the ticket and the run's record say. + pub fn line(&self) -> String { + let when = self + .resumes() + .map(utc_label) + .unwrap_or_else(|| "the first of next month".to_string()); + match self.kind { + PauseKind::TokenLimit => format!( + "Paused: {} is used up ({} of {}). Resumes by itself on {when} when the month \ + turns, or as soon as an admin raises the limit.", + limit_phrase(&self.limit), + short_tokens(self.used), + short_tokens(self.max) + ), + PauseKind::TokenRoom if self.in_progress => format!( + "Waiting for token room: {} has {} left and the rest of this run takes about {}. \ + Goes on by itself on {when} when the month turns, or as soon as an admin raises \ + the limit.", + limit_phrase(&self.limit), + short_tokens(self.room), + short_tokens(self.need) + ), + PauseKind::TokenRoom => format!( + "Waiting for token room: {} has {} left and a run like this takes about {}. \ + Starts by itself on {when} when the month turns, or as soon as an admin raises \ + the limit.", + limit_phrase(&self.limit), + short_tokens(self.room), + short_tokens(self.need) + ), + } + } + + /// Whether the month it waited out has turned at `now`. + pub fn month_turned(&self, now: DateTime) -> bool { + self.resumes().is_some_and(|t| now >= t) + } +} + +/// Whether the run record `item` waits on the token limit: its wait +/// carries a pause, or it waits on the usage limit, or (stopped by an older +/// release) a refused call is in its stored words. Such a run goes on by +/// itself, in place, from its checkpoint (the worker's `token_room`). +pub fn waits_on_limit( + item: &std::collections::HashMap, +) -> bool { + let s = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .map(|x| x.as_str()) + .unwrap_or("") + }; + if s("status") != crate::run_status::NEEDS_INPUT { + return false; + } + let wait = crate::run_wait::WaitingOn::of_item(item).unwrap_or_default(); + wait.pause.is_some() + || wait.handback == crate::handback::HumanOnly::UsageLimit.code() + || [ + s(crate::run_recovery::FIELD_ERROR_DETAIL), + s("error_message"), + wait.detail.as_str(), + ] + .iter() + .any(|t| refusal(t).is_some()) +} + +// ── What a run takes, and the room left ───────────────────────────────────── + +/// One run's record, as the estimate and the room read it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RunUse { + pub run_id: String, + /// The run's kind: its ticket source (`jira`, `github`, `alert`). + pub kind: String, + pub status: String, + pub updated_at: String, + /// What the run used so far. + pub used: UsageTotals, + /// Paused on the limit mid-run (it is in progress). + pub paused_mid_run: bool, +} + +/// Runs that finished their work: what they used is what a run takes. +const FINISHED: [&str; 5] = [ + "completed", + "success", + "merged", + "no_change", + "covered_by_pr", +]; + +impl RunUse { + /// Working now, or paused half way: it has a claim on the room left. + pub fn in_progress(&self) -> bool { + crate::run_status::IN_FLIGHT.contains(&self.status.as_str()) || self.paused_mid_run + } + + fn finished(&self) -> bool { + FINISHED.contains(&self.status.as_str()) && self.used.total() > 0 + } +} + +fn median(mut v: Vec) -> u64 { + if v.is_empty() { + return 0; + } + v.sort_unstable(); + v[v.len() / 2] +} + +/// What a run of `kind` takes: each part the median of the newest +/// [`ESTIMATE_RUNS`] finished runs of that kind (every kind's when fewer than +/// [`MIN_SAME_KIND`] of it finished). `None` with no finished run to go by: +/// nothing is held back on a guess. +pub fn estimate(history: &[RunUse], kind: &str) -> Option { + let mut done: Vec<&RunUse> = history.iter().filter(|r| r.finished()).collect(); + done.sort_by(|a, b| b.updated_at.cmp(&a.updated_at)); + let same: Vec<&RunUse> = done.iter().copied().filter(|r| r.kind == kind).collect(); + let pick: Vec<&RunUse> = if same.len() >= MIN_SAME_KIND { + same + } else { + done + }; + let pick: Vec<&RunUse> = pick.into_iter().take(ESTIMATE_RUNS).collect(); + if pick.is_empty() { + return None; + } + let part = |f: fn(&UsageTotals) -> u64| median(pick.iter().map(|r| f(&r.used)).collect()); + Some(UsageTotals { + tokens_in_uncached: part(|u| u.tokens_in_uncached), + cache_read: part(|u| u.cache_read), + cache_write: part(|u| u.cache_write), + tokens_out: part(|u| u.tokens_out), + }) +} + +fn add(a: UsageTotals, b: UsageTotals) -> UsageTotals { + UsageTotals { + tokens_in_uncached: a.tokens_in_uncached + b.tokens_in_uncached, + cache_read: a.cache_read + b.cache_read, + cache_write: a.cache_write + b.cache_write, + tokens_out: a.tokens_out + b.tokens_out, + } +} + +fn less(a: UsageTotals, b: UsageTotals) -> UsageTotals { + UsageTotals { + tokens_in_uncached: a.tokens_in_uncached.saturating_sub(b.tokens_in_uncached), + cache_read: a.cache_read.saturating_sub(b.cache_read), + cache_write: a.cache_write.saturating_sub(b.cache_write), + tokens_out: a.tokens_out.saturating_sub(b.tokens_out), + } +} + +/// What the runs in progress still need: for each, what a run of its kind +/// takes less what it used so far. They come first on the room left. +pub fn reserved(history: &[RunUse], except: &[&str]) -> UsageTotals { + history + .iter() + .filter(|r| r.in_progress() && !except.contains(&r.run_id.as_str())) + .filter_map(|r| estimate(history, &r.kind).map(|e| less(e, r.used))) + .fold(UsageTotals::default(), add) +} + +/// Whether a new run that takes `need` fits in what is left of each set +/// limit after `reserve` (what the runs in progress still need). `None`: +/// it fits; else the wait, for the first limit it doesn't fit. +pub fn start_room( + limits: &TokenLimits, + month: &UsageTotals, + reserve: &UsageTotals, + need: &UsageTotals, + now: DateTime, +) -> Option { + for u in limits.uses(month) { + let want = u.kind.used(need); + if want == 0 { + continue; + } + let room = u.max.saturating_sub(u.used); + let free = room.saturating_sub(u.kind.used(reserve)); + if want > free { + return Some(Pause::no_room( + u.kind.label(), + u.used, + u.max, + free, + want, + now, + )); + } + } + None +} + +/// Before a costly step of a run under way that used `spent` so far: +/// the wait when what is left of a set limit is less than what the rest of +/// a run of its kind takes (`need` less `spent`). Runs in progress come +/// first, so nothing is held for the others. `None`: it goes on. +pub fn step_room( + limits: &TokenLimits, + month: &UsageTotals, + need: &UsageTotals, + spent: &UsageTotals, + now: DateTime, +) -> Option { + let rest = less(*need, *spent); + for u in limits.uses(month) { + let want = u.kind.used(&rest); + if want == 0 { + continue; + } + let room = u.max.saturating_sub(u.used); + if want > room { + return Some(Pause::no_room_mid_run( + u.kind.label(), + u.used, + u.max, + room, + want, + now, + )); + } + } + None +} + +/// A run waiting on the limit, as the wake reads it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Waiting { + pub run_id: String, + pub kind: String, + /// Paused mid-run (its pause is [`PauseKind::TokenLimit`], or an older + /// stop on the limit with no pause written). + pub mid_run: bool, + /// It waits for room ([`PauseKind::TokenRoom`]): it is woken only when + /// what it needs fits, so it never wakes to wait again. + pub room_wait: bool, + /// When it started waiting: the oldest goes first. + pub since: String, + pub used: UsageTotals, +} + +/// Which waiting runs start now, in order, given the team's limits, the +/// month's counts and `history` (for what runs take and what the runs in +/// progress still need). Nothing while a limit is still reached. Runs +/// paused half way go first, oldest first, each holding what it still +/// needs; then new runs, oldest first. A run waiting for room (half way or +/// new) starts only when what it needs fits in what is left after those +/// holds. +pub fn plan_wakes( + limits: &TokenLimits, + month: &UsageTotals, + history: &[RunUse], + waiting: &[Waiting], + max: usize, +) -> Vec { + if limits.reached(month).is_some() { + return Vec::new(); + } + let mut order: Vec<&Waiting> = waiting.iter().collect(); + order.sort_by(|a, b| b.mid_run.cmp(&a.mid_run).then(a.since.cmp(&b.since))); + // The waiting runs' own needs are added as each is woken. + let ids: Vec<&str> = waiting.iter().map(|w| w.run_id.as_str()).collect(); + let mut reserve = reserved(history, &ids); + let mut out = Vec::new(); + for w in order { + if out.len() >= max { + break; + } + let need = estimate(history, &w.kind).map(|e| less(e, w.used)); + if w.mid_run && !w.room_wait { + // Refused half way: it goes on, and its need is held. + reserve = add(reserve, need.unwrap_or_default()); + out.push(w.run_id.clone()); + continue; + } + let need = need.unwrap_or_default(); + if start_room(limits, month, &reserve, &need, Utc::now()).is_none() { + reserve = add(reserve, need); + out.push(w.run_id.clone()); + } + } + out +} + +// ── Warnings ──────────────────────────────────────────────────────────────── + +/// When the limit runs out at this month's pace (`used` since the month +/// started, at `now`), if before the month turns. `None` once it is used +/// up, with nothing used, or when the pace doesn't reach it this month. +pub fn projected_out(used: u64, max: u64, now: DateTime) -> Option> { + if used == 0 || used >= max { + return None; + } + let elapsed = (now - month_start(now)).num_seconds().max(3_600) as f64; + let per_sec = used as f64 / elapsed; + let secs = ((max - used) as f64 / per_sec).ceil(); + if !secs.is_finite() || secs > 40.0 * 86_400.0 { + return None; + } + let at = now + Duration::seconds(secs as i64); + (at < month_turn(now)).then_some(at) +} + +/// The warning's line about the pace, for the email and the banner. +pub fn pace_line(used: u64, max: u64, now: DateTime) -> String { + match projected_out(used, max, now) { + Some(at) => format!( + "At this month's pace the limit runs out on {}. Runs that reach it pause and go on by \ + themselves when the month turns or an admin raises the limit.", + utc_label(at) + ), + None => "At this month's pace the limit lasts until the month turns. Runs that reach it \ + pause and go on by themselves when the month turns or an admin raises the limit." + .to_string(), + } +} + +/// Whether `kind` is one of the set limits a refusal names (the label the +/// refusal carries). +pub fn kind_of_label(limits: &TokenLimits, label: &str) -> Option { + limits + .limits + .iter() + .map(|l| l.kind) + .find(|k| k.label() == label.trim()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::token_limits::Limit; + + fn at(s: &str) -> DateTime { + DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc) + } + + fn new_limit(max: u64) -> TokenLimits { + TokenLimits { + limits: vec![Limit { + kind: LimitKind::NewTokens, + max, + }], + legacy: false, + } + } + + fn new_tokens(n: u64) -> UsageTotals { + UsageTotals { + tokens_in_uncached: n / 2, + tokens_out: n - n / 2, + ..Default::default() + } + } + + fn run(id: &str, kind: &str, status: &str, at: &str, used: u64) -> RunUse { + RunUse { + run_id: id.into(), + kind: kind.into(), + status: status.into(), + updated_at: at.into(), + used: new_tokens(used), + paused_mid_run: false, + } + } + + #[test] + fn both_wordings_of_a_refusal_are_read_wherever_they_sit() { + let call = crate::token_limits::call_refused_reason(&crate::token_limits::LimitUse { + kind: LimitKind::NewTokens, + max: 40_000_000, + used: 40_300_000, + }); + assert_eq!( + refusal(&call), + Some(Refusal { + limit: "new tokens".into(), + used: 40_300_000, + max: 40_000_000 + }) + ); + // Wrapped by a pass and by the old stop. + let wrapped = format!( + "CoderHelm met an error it doesn't know how to repair, and stopped without trying \ + again: Implement failed: {call}" + ); + assert_eq!(refusal(&wrapped).unwrap().used, 40_300_000); + assert_eq!( + refusal( + "Monthly token limit exceeded (5 / 4 tokens). Increase your limit in Settings." + ), + Some(Refusal { + limit: "token".into(), + used: 5, + max: 4 + }) + ); + assert_eq!( + refusal("Monthly cache read tokens limit exceeded (60 / 50 cache read tokens)."), + Some(Refusal { + limit: "cache read tokens".into(), + used: 60, + max: 50 + }) + ); + assert_eq!(refusal("A monthly report failed to load."), None); + assert_eq!( + refusal("Monthly new tokens limit reached (lots of more)."), + None + ); + } + + #[test] + fn the_month_turns_at_midnight_utc_on_the_first() { + assert_eq!( + month_turn(at("2026-11-30T23:59:59Z")), + at("2026-12-01T00:00:00Z") + ); + assert_eq!( + month_turn(at("2026-12-14T08:00:00Z")), + at("2027-01-01T00:00:00Z") + ); + assert_eq!( + month_start(at("2026-11-30T23:59:59Z")), + at("2026-11-01T00:00:00Z") + ); + } + + #[test] + fn a_pause_says_one_line_with_when_it_resumes() { + let r = Refusal { + limit: "new tokens".into(), + used: 40_300_000, + max: 40_000_000, + }; + let p = Pause::limit_reached(&r, at("2026-11-30T21:10:00Z")); + assert_eq!( + p.line, + "Paused: this month's token limit is used up (40.3M of 40M). Resumes by itself on \ + Dec 1, 00:00 UTC when the month turns, or as soon as an admin raises the limit." + ); + assert_eq!(p.resumes_at, "2026-12-01T00:00:00+00:00"); + assert_eq!(p.settings_path, SETTINGS_PATH); + assert!(!p.month_turned(at("2026-11-30T23:59:00Z"))); + assert!(p.month_turned(at("2026-12-01T00:00:30Z"))); + assert_eq!(crate::rendered::person_text(&p.line), None, "{}", p.line); + assert!(!p.line.to_lowercase().contains("retry")); + + let q = Pause::no_room( + "new tokens", + 38_000_000, + 40_000_000, + 1_200_000, + 3_400_000, + at("2026-11-20T10:00:00Z"), + ); + assert!(q.line.starts_with("Waiting for token room: this month's token limit has 1.2M left and a run like this takes about 3.4M."), "{}", q.line); + assert_eq!(crate::rendered::person_text(&q.line), None, "{}", q.line); + let back: Pause = serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap(); + assert_eq!(back, q); + } + + #[test] + fn a_run_takes_what_runs_of_its_kind_took_lately() { + let h = vec![ + run("1", "jira", "completed", "2026-11-01", 2_000_000), + run("2", "jira", "completed", "2026-11-02", 3_000_000), + run("3", "jira", "merged", "2026-11-03", 4_000_000), + run("4", "github", "completed", "2026-11-04", 9_000_000), + run("5", "jira", "failed", "2026-11-05", 50_000_000), + ]; + assert_eq!(estimate(&h, "jira").unwrap().uncached_total(), 3_000_000); + // Too few of its kind: every kind's. + assert_eq!(estimate(&h, "github").unwrap().uncached_total(), 4_000_000); + assert_eq!(estimate(&[], "jira"), None); + } + + #[test] + fn a_new_run_waits_when_the_room_left_is_short() { + let limits = new_limit(40_000_000); + let h = vec![ + run("1", "jira", "completed", "2026-11-01", 3_000_000), + run("2", "jira", "completed", "2026-11-02", 3_000_000), + run("3", "jira", "completed", "2026-11-03", 3_000_000), + ]; + let need = estimate(&h, "jira").unwrap(); + let now = at("2026-11-20T10:00:00Z"); + assert!(start_room( + &limits, + &new_tokens(30_000_000), + &UsageTotals::default(), + &need, + now + ) + .is_none()); + let p = start_room( + &limits, + &new_tokens(38_000_000), + &UsageTotals::default(), + &need, + now, + ) + .expect("2M left, 3M needed"); + assert_eq!(p.kind, PauseKind::TokenRoom); + assert_eq!((p.room, p.need), (2_000_000, 3_000_000)); + } + + #[test] + fn runs_in_progress_hold_their_room_first() { + let limits = new_limit(40_000_000); + let mut h = vec![ + run("1", "jira", "completed", "2026-11-01", 3_000_000), + run("2", "jira", "completed", "2026-11-02", 3_000_000), + run("3", "jira", "completed", "2026-11-03", 3_000_000), + // Half way: it still needs 2M. + run("live", "jira", "running", "2026-11-20", 1_000_000), + ]; + let need = estimate(&h, "jira").unwrap(); + let now = at("2026-11-20T10:00:00Z"); + let reserve = reserved(&h, &["new"]); + assert_eq!(reserve.uncached_total(), 2_000_000); + // 4M left: enough for the new run alone, not with the live run's 2M. + let month = new_tokens(36_000_000); + assert!(start_room(&limits, &month, &UsageTotals::default(), &need, now).is_none()); + assert!(start_room(&limits, &month, &reserve, &need, now).is_some()); + // A run paused half way holds its room the same way. + h[3].status = "needs_input".into(); + h[3].paused_mid_run = true; + assert_eq!(reserved(&h, &["new"]).uncached_total(), 2_000_000); + } + + #[test] + fn the_wake_starts_runs_paused_half_way_before_new_ones() { + let limits = new_limit(40_000_000); + let h = vec![ + run("1", "jira", "completed", "2026-11-01", 3_000_000), + run("2", "jira", "completed", "2026-11-02", 3_000_000), + run("3", "jira", "completed", "2026-11-03", 3_000_000), + ]; + let w = |id: &str, mid: bool, since: &str| Waiting { + run_id: id.into(), + kind: "jira".into(), + mid_run: mid, + room_wait: !mid, + since: since.into(), + used: if mid { + new_tokens(1_000_000) + } else { + UsageTotals::default() + }, + }; + let waiting = vec![ + w("new-old", false, "2026-11-10"), + w("half", true, "2026-11-15"), + w("new-young", false, "2026-11-12"), + ]; + // Still at the limit: nothing. + assert!(plan_wakes(&limits, &new_tokens(40_000_000), &h, &waiting, 50).is_empty()); + // 5M left: the half-way run (2M) first, then one new run (3M). + assert_eq!( + plan_wakes(&limits, &new_tokens(35_000_000), &h, &waiting, 50), + vec!["half".to_string(), "new-old".to_string()] + ); + // A new month: every run. + assert_eq!( + plan_wakes(&limits, &UsageTotals::default(), &h, &waiting, 50).len(), + 3 + ); + } + + #[test] + fn a_run_under_way_waits_before_a_costly_step_it_cant_finish() { + let limits = new_limit(40_000_000); + let need = new_tokens(3_000_000); + let now = at("2026-11-20T10:00:00Z"); + // 1M spent, 2M to go, 1.5M left: it waits before the step. + let p = step_room( + &limits, + &new_tokens(38_500_000), + &need, + &new_tokens(1_000_000), + now, + ) + .expect("waits"); + assert!(p.in_progress && p.mid_run()); + assert_eq!((p.room, p.need), (1_500_000, 2_000_000)); + assert!( + p.line.contains("the rest of this run takes about 2M"), + "{}", + p.line + ); + assert_eq!(crate::rendered::person_text(&p.line), None, "{}", p.line); + // 3M left: it goes on. + assert!(step_room( + &limits, + &new_tokens(37_000_000), + &need, + &new_tokens(1_000_000), + now + ) + .is_none()); + } + + /// A run that waits for room before building is woken only when the + /// rest of it fits: it never wakes to wait again. + #[test] + fn a_run_waiting_for_room_wakes_only_when_it_fits() { + let limits = new_limit(40_000_000); + let h = vec![ + run("1", "jira", "completed", "2026-11-01", 3_000_000), + run("2", "jira", "completed", "2026-11-02", 3_000_000), + run("3", "jira", "completed", "2026-11-03", 3_000_000), + ]; + let waiting = vec![Waiting { + run_id: "half".into(), + kind: "jira".into(), + mid_run: true, + room_wait: true, + since: "2026-11-15".into(), + used: new_tokens(1_000_000), + }]; + // 1.5M left, 2M to go: it waits. + assert!(plan_wakes(&limits, &new_tokens(38_500_000), &h, &waiting, 50).is_empty()); + // 2.5M left: it goes on. + assert_eq!( + plan_wakes(&limits, &new_tokens(37_500_000), &h, &waiting, 50), + vec!["half".to_string()] + ); + } + + #[test] + fn the_pace_says_when_the_limit_runs_out() { + // 80% used in 20 days of a 30-day month: out on day 25. + let now = at("2026-11-21T00:00:00Z"); + let out = projected_out(32_000_000, 40_000_000, now).unwrap(); + assert_eq!(out, at("2026-11-26T00:00:00Z")); + assert!(pace_line(32_000_000, 40_000_000, now).contains("Nov 26, 00:00 UTC")); + // A slow month never gets there. + assert_eq!(projected_out(1_000_000, 40_000_000, now), None); + assert_eq!(projected_out(40_000_000, 40_000_000, now), None); + } +} diff --git a/services/common/src/webhooks/catalog.rs b/services/common/src/webhooks/catalog.rs index b8613598..35cf2305 100644 --- a/services/common/src/webhooks/catalog.rs +++ b/services/common/src/webhooks/catalog.rs @@ -310,7 +310,15 @@ pub const EVENTS: &[EventType] = &[ name: "run.needs_input", group: "Runs", summary: "A run is waiting for a person", - description: "The run asked a question on its ticket or pull request and waits for an answer. `error` holds the question.", + description: "The run asked a question on its ticket or pull request and waits for an answer. `error` holds the question. Sent only for a wait a person ends: a run paused on the token limit sends `run.paused` instead.", + fields: RUN_FIELDS, + feature: None, + }, + EventType { + name: "run.paused", + group: "Runs", + summary: "A run paused on the token limit", + description: "The team's monthly token limit stopped the run, or left too little room for a new one. It waits with its work kept and goes on by itself when the month turns or an admin raises the limit; nobody needs to act. `status` is `needs_input` and `error` holds the pause line with when it resumes.", fields: RUN_FIELDS, feature: None, }, @@ -501,6 +509,11 @@ pub fn example_data(name: &str) -> Value { false, Some("Should the limit apply per API key or per team?"), ), + "run.paused" => run_example( + "needs_input", + false, + Some("Paused: this month's token limit is used up (40.3M of 40M). Resumes by itself on Dec 1, 00:00 UTC when the month turns, or as soon as an admin raises the limit."), + ), "pull_request.opened" => json!({ "run_id": EXAMPLE_RUN_ID, "repo": "example-org/api", diff --git a/services/common/src/webhooks/event.rs b/services/common/src/webhooks/event.rs index 565a1d39..4433edb2 100644 --- a/services/common/src/webhooks/event.rs +++ b/services/common/src/webhooks/event.rs @@ -76,8 +76,15 @@ const SECRET_PREFIXES: &[&str] = &[ "eyJ", ]; +/// Plain words that follow "token" in CoderHelm's own sentences ("this +/// month's token limit is used up"): never a credential, so never redacted. +const PLAIN_AFTER_TOKEN: &[&str] = &[ + "limit", "limits", "room", "usage", "budget", "count", "counts", +]; + /// One text value with anything that looks like a credential replaced by -/// `[redacted]`: tokens by their prefix, the word after `Bearer`/`token`, +/// `[redacted]`: tokens by their prefix, the word after `Bearer`/`token` +/// (unless it is a plain word such as "limit"), /// `user:password@` in addresses, `key=value` pairs whose key names a /// secret, and whole private-key blocks. Long text is cut. pub fn scrub_text(s: &str) -> String { @@ -111,7 +118,8 @@ pub fn scrub_text(s: &str) -> String { let token = SECRET_PREFIXES .iter() .any(|p| bare.starts_with(p) && bare.len() >= p.len() + 8); - if redact_next || token || secretish_kv || creds_in_url { + let plain = PLAIN_AFTER_TOKEN.contains(&lower.as_str()); + if (redact_next && !plain) || token || secretish_kv || creds_in_url { out.push("[redacted]".into()); } else { out.push(word.to_string()); @@ -379,6 +387,13 @@ mod tests { .unwrap() .starts_with("git push failed: remote: Invalid token [redacted]")); assert!(e.data["long"].as_str().unwrap().chars().count() <= MAX_TEXT + 1); + // A pause line keeps its words: "token limit" is no credential. + let line = "Paused: this month's token limit is used up (40.3M of 40M)."; + assert_eq!(scrub_text(line), line); + assert_eq!( + scrub_text("Invalid token abc123def456"), + "Invalid token [redacted]" + ); // Catalog examples pass through unchanged: real data isn't damaged. for t in catalog::EVENTS { let ex = catalog::example_data(t.name); diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 0feadf30..d9bbb7aa 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -794,6 +794,10 @@ pub struct RunSummary { /// above and what started it. Show this instead of an internal /// `ticket_id` such as `E2E-FIX-…`. pub trigger: run_trigger::RunTrigger, + /// A `needs_input` run paused on the team's monthly token limit: it + /// resumes by itself (`resumes_at`), so show it as paused, never as + /// waiting for an answer. Null for every other run. + pub pause: Option, } /// A page of runs. @@ -933,6 +937,7 @@ pub async fn list_runs( duration_s: num_of(item, "duration_s"), current_pass: str_of(item, "current_pass"), created_at: str_of(item, "created_at"), + pause: pause_of(item), }) .collect(); @@ -984,6 +989,48 @@ pub struct RunWaitingOn { /// When the wait started (RFC 3339). #[schema(example = "2026-10-22T14:15:25Z")] pub since: Option, + /// The run waits on the team's monthly token limit and resumes by + /// itself: shown as paused, never as a person's step. Null for every + /// other wait. + pub pause: Option, +} + +/// A run paused on the team's monthly token limit. It resumes by itself +/// when the month turns (`resumes_at`) or as soon as an admin raises the +/// limit. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct RunPause { + /// `token_limit`: a model call was refused, the run keeps its work and + /// goes on from where it stopped. `token_room`: a new run waits because + /// what is left is less than a run like it takes. + #[schema(example = "token_limit")] + pub kind: String, + /// The limit's name. + #[schema(example = "new tokens")] + pub limit: String, + /// This month's count of that limit. + #[schema(example = 40300000)] + pub used: u64, + /// The limit. + #[schema(example = 40000000)] + pub max: u64, + /// For `token_room`: what is left for new runs. + #[schema(example = 0)] + pub room: u64, + /// For `token_room`: what a run like this takes. + #[schema(example = 0)] + pub need: u64, + /// When the month turns and it resumes by itself (RFC 3339, UTC). + #[schema(example = "2026-12-01T00:00:00+00:00")] + pub resumes_at: String, + /// The one line, with the time in UTC. + #[schema( + example = "Paused: this month's token limit is used up (40.3M of 40M). Resumes by itself on Dec 1, 00:00 UTC when the month turns, or as soon as an admin raises the limit." + )] + pub line: String, + /// Where an admin raises the limit. + #[schema(example = "/settings/budget")] + pub settings_path: String, } /// Why a finished run's pull request is still a draft, with what to do @@ -1211,6 +1258,39 @@ pub(crate) fn merge_standing_of(item: &run_search::Item) -> Option Option { + let waiting = item + .get("status") + .and_then(|v| v.as_s().ok()) + .map(String::as_str) + == Some(common::run_status::NEEDS_INPUT); + waiting + .then(|| common::run_wait::WaitingOn::of_item(item)) + .flatten() + .and_then(|w| w.pause) + .map(run_pause) +} + +fn run_pause(p: common::token_room::Pause) -> RunPause { + RunPause { + kind: match p.kind { + common::token_room::PauseKind::TokenLimit => "token_limit", + common::token_room::PauseKind::TokenRoom => "token_room", + } + .to_string(), + limit: p.limit, + used: p.used, + max: p.max, + room: p.room, + need: p.need, + resumes_at: p.resumes_at, + line: p.line, + settings_path: p.settings_path, + } +} + pub(crate) fn waiting_on_of(item: &run_search::Item) -> Option { let w = common::run_wait::WaitingOn::of_item(item)?; Some(RunWaitingOn { @@ -1218,6 +1298,7 @@ pub(crate) fn waiting_on_of(item: &run_search::Item) -> Option { detail: w.detail, url: Some(w.url).filter(|u| !u.is_empty()), since: Some(w.since).filter(|s| !s.is_empty()), + pause: w.pause.map(run_pause), }) } @@ -6028,12 +6109,24 @@ pub async fn update_budget( } /// The limits were saved: when they now allow runs, the runs that waited -/// for the limit go on by themselves (`run_wake`). +/// for the limit go on by themselves (`run_wake`). Runs paused on the token +/// limit are resumed in place by the worker's limit wake, runs half way +/// first: the sweep is sent now rather than at its next 15-minute tick. async fn wake_after_limit(state: &AppState, team_id: &str) { if super::github_webhook::check_run_budget(state, team_id) .await .is_none() { + if let Err(e) = state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(serde_json::json!({ "type": "self_heal_sweep" }).to_string()) + .send() + .await + { + warn!(team_id, error = %e, "The limit's wake couldn't be sent; the 15-minute sweep starts the paused runs"); + } super::run_wake::wake_team( state, team_id, @@ -6201,6 +6294,14 @@ pub struct UsageLimit { /// What it counts so far this month. #[schema(example = 4310227)] pub used: u64, + /// The warning level it has crossed: 0, 80, 95 or 100 (percent). The + /// dashboard warns admins at 80 and 95, once each a month. + #[schema(example = 80)] + pub warn_level: u8, + /// When it runs out at this month's pace (RFC 3339), when that falls + /// before the month turns. Null otherwise. + #[schema(example = "2026-11-26T14:00:00+00:00")] + pub projected_at: Option, } /// The team's token usage this month. @@ -6293,12 +6394,20 @@ pub fn usage_body( .then(a.model.cmp(&b.model)) }); let uses = limits.uses(&t); + // The pace is this month's: a past month has no day left to run out. + let now = chrono::Utc::now(); + let this_month = now.format("%Y-%m").to_string() == month; let limit_rows: Vec = uses .iter() .map(|u| UsageLimit { kind: u.kind.key().to_string(), max: u.max, used: u.used, + warn_level: common::token_limits::warning_level(u).unwrap_or(0), + projected_at: this_month + .then(|| common::token_room::projected_out(u.used, u.max, now)) + .flatten() + .map(|t| t.to_rfc3339()), }) .collect(); let (max_tokens, counted, counts_cache) = uses @@ -7508,7 +7617,13 @@ mod tests { assert_eq!(off["limits_legacy"], true); assert_eq!( off["limits"], - json!([{ "kind": "new_tokens", "max": 200_000_000u64, "used": 1_120_000u64 }]) + json!([{ + "kind": "new_tokens", + "max": 200_000_000u64, + "used": 1_120_000u64, + "warn_level": 0, + "projected_at": null, + }]) ); assert_eq!(off["features"][0]["feature"], "run"); assert_eq!(off["features"][0]["total_tokens"], 71_320_000u64); @@ -7543,13 +7658,58 @@ mod tests { assert_eq!( body["limits"], json!([ - { "kind": "new_tokens", "max": 5_000_000u64, "used": 1_120_000u64 }, - { "kind": "cache_write", "max": 9_000_000u64, "used": 8_800_000u64 }, + { + "kind": "new_tokens", "max": 5_000_000u64, "used": 1_120_000u64, + "warn_level": 0, "projected_at": null, + }, + { + "kind": "cache_write", "max": 9_000_000u64, "used": 8_800_000u64, + "warn_level": 95, "projected_at": null, + }, ]) ); assert_eq!(body["new_tokens"], 1_120_000u64); } + /// The runs list carries a paused run's pause, so it reads as paused, + /// never as waiting for an answer; and only while it still waits. + #[test] + fn a_paused_run_carries_its_pause_in_the_list() { + use aws_sdk_dynamodb::types::AttributeValue as A; + assert!(super::run_search::LIST_ATTRS.contains(&"waiting_on")); + let now = chrono::DateTime::parse_from_rfc3339("2026-11-30T21:10:00Z") + .unwrap() + .with_timezone(&chrono::Utc); + let p = common::token_room::Pause::limit_reached( + &common::token_room::Refusal { + limit: "new tokens".into(), + used: 40_300_000, + max: 40_000_000, + }, + now, + ); + let wait = common::run_wait::WaitingOn { + action: p.line.clone(), + handback: "usage_limit".into(), + pause: Some(p), + ..Default::default() + }; + let mut item: std::collections::HashMap = + [("run_id", "01BOOK"), ("status", "needs_input")] + .iter() + .map(|(k, v)| (k.to_string(), A::S(v.to_string()))) + .collect(); + item.insert(common::run_wait::FIELD_WAITING_ON.into(), wait.to_attr()); + let got = super::pause_of(&item).expect("paused"); + assert_eq!(got.kind, "token_limit"); + assert_eq!(got.resumes_at, "2026-12-01T00:00:00+00:00"); + item.insert("status".into(), A::S("running".into())); + assert!( + super::pause_of(&item).is_none(), + "resumed: no longer paused" + ); + } + #[test] fn budget_shows_the_three_limits_and_the_old_one_as_fallback() { use aws_sdk_dynamodb::types::AttributeValue as A; diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index efb171bd..d185c53c 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -592,13 +592,11 @@ async fn handle_issue_event( ..Default::default() }); - // Check usage limits before dispatching - if let Some(reason) = check_run_budget(state, team_id).await { - let owner = repo["owner"]["login"].as_str().unwrap_or(""); - let name = repo["name"].as_str().unwrap_or(""); - let number = issue["number"].as_u64().unwrap_or(0); - post_limit_comment(state, installation_id, owner, name, number, &reason).await; - return Ok(StatusCode::OK); + // At the token limit the issue still starts: the worker pauses its run + // at the start, typed, and it goes on by itself when the month turns or + // the limit is raised (`token_room`). An issue is never dropped. + if check_run_budget(state, team_id).await.is_some() { + info!(team_id, "Token limit reached: the run starts paused"); } // Trigger gate: block while a run is in flight; on a completed latest @@ -1686,13 +1684,11 @@ async fn handle_issue_comment( ..Default::default() }); - // Check usage limits before dispatching - if let Some(reason) = check_run_budget(state, team_id).await { - let owner = repo["owner"]["login"].as_str().unwrap_or(""); - let name = repo["name"].as_str().unwrap_or(""); - let number = issue["number"].as_u64().unwrap_or(0); - post_limit_comment(state, installation_id, owner, name, number, &reason).await; - return Ok(StatusCode::OK); + // At the token limit the issue still starts: the worker pauses its run + // at the start, typed, and it goes on by itself when the month turns or + // the limit is raised (`token_room`). An issue is never dropped. + if check_run_budget(state, team_id).await.is_some() { + info!(team_id, "Token limit reached: the run starts paused"); } // Explicit human command: skip the content-hash check but still block diff --git a/services/gateway/src/routes/jira_webhook.rs b/services/gateway/src/routes/jira_webhook.rs index 58b5cdd3..ef9c45e9 100644 --- a/services/gateway/src/routes/jira_webhook.rs +++ b/services/gateway/src/routes/jira_webhook.rs @@ -859,21 +859,17 @@ async fn process_jira_payload( super::trigger_gate::TicketGate::Enqueue => {} } - // Check token budget before processing - if let Some(_reason) = super::github_webhook::check_run_budget(state, team_id).await { - info!(team_id, "Jira webhook skipped — token limit reached"); - log_jira_event( - state, - started, + // At the token limit the ticket still starts: the worker pauses its run + // at the start, typed, and it goes on by itself when the month turns or + // the limit is raised (`token_room`). A ticket is never dropped. + if super::github_webhook::check_run_budget(state, team_id) + .await + .is_some() + { + info!( team_id, - event_type, - ticket_key, - &title, - "token_limit", - None, - ) - .await; - return Ok(StatusCode::OK); + ticket_key, "Token limit reached: the run starts paused" + ); } // Atomic dedup: write a short-lived lock to prevent duplicate SQS sends diff --git a/services/gateway/src/routes/run_search.rs b/services/gateway/src/routes/run_search.rs index 2964a244..afc55a33 100644 --- a/services/gateway/src/routes/run_search.rs +++ b/services/gateway/src/routes/run_search.rs @@ -34,6 +34,9 @@ pub const LIST_ATTRS: &[&str] = &[ "duration_s", "current_pass", "created_at", + // A run paused on the token limit shows as paused, never as a person's + // step (`RunSummary::pause`). + "waiting_on", // How the run started (see `run_trigger`). "issue_number", "sender", diff --git a/services/gateway/src/routes/run_wake.rs b/services/gateway/src/routes/run_wake.rs index 291bb6d1..1bc5c96a 100644 --- a/services/gateway/src/routes/run_wake.rs +++ b/services/gateway/src/routes/run_wake.rs @@ -92,7 +92,11 @@ pub fn woken<'a>(runs: &'a [Item], wake: Wake, added: &[String]) -> Vec<&'a Item runs.iter() .filter(|i| { let wait = WaitingOn::of_item(i).unwrap_or_default(); + // A run waiting on the token limit goes on in place, from its + // checkpoint, by the worker's limit wake (`token_room`): never + // superseded by a new run here. run_wake::wakes_run(text(i, "status"), &wait.handback, wake) + && !(wake == Wake::Limit && common::token_room::waits_on_limit(i)) && (wake != Wake::Access || run_wake::access_reaches( text(i, "repo"), @@ -548,7 +552,9 @@ mod tests { }; assert_eq!(ids(woken(&runs, Wake::Access, &added)), vec!["01A"]); assert_eq!(ids(woken(&runs, Wake::Access, &[])), vec!["01A", "01B"]); - assert_eq!(ids(woken(&runs, Wake::Limit, &[])), vec!["01D"]); + // A wait on the token limit goes on in place, from its checkpoint, + // by the worker's limit wake: it is never superseded here. + assert!(ids(woken(&runs, Wake::Limit, &[])).is_empty()); } #[test] diff --git a/services/gateway/src/routes/search.rs b/services/gateway/src/routes/search.rs index bfbf6472..bad23288 100644 --- a/services/gateway/src/routes/search.rs +++ b/services/gateway/src/routes/search.rs @@ -276,6 +276,9 @@ const RUN_ATTRS: &[&str] = &[ "pr_number", "pr_numbers", "created_at", + // A paused run reads as paused in the palette, never as waiting for an + // answer. + "waiting_on", ]; fn match_runs(rows: &[Item], q: &str, limit: usize) -> Vec { @@ -292,6 +295,7 @@ fn match_runs(rows: &[Item], q: &str, limit: usize) -> Vec { "repo": s(it, "repo"), "status": s(it, "status"), "created_at": s(it, "created_at"), + "pause": super::api::pause_of(it), }) }) .collect() diff --git a/services/worker/src/clients/email.rs b/services/worker/src/clients/email.rs index d80fe5a7..e951d2c7 100644 --- a/services/worker/src/clients/email.rs +++ b/services/worker/src/clients/email.rs @@ -13,6 +13,9 @@ pub enum EmailEvent { used_tokens: String, limit_tokens: String, usage_pct: u8, + /// When the limit runs out at this month's pace, and that paused + /// runs go on by themselves (`token_room::pace_line`). + pace: String, }, TokenLimitReached { month: String, @@ -55,6 +58,7 @@ pub async fn send_notification( used_tokens, limit_tokens, usage_pct, + pace, } => ( "token-warning", "email_token_warning", @@ -64,6 +68,7 @@ pub async fn send_notification( "used_tokens": used_tokens, "limit_tokens": limit_tokens, "usage_pct": usage_pct, + "pace": pace, }) .to_string(), ), @@ -117,11 +122,12 @@ pub async fn send_notification( used_tokens, limit_tokens, usage_pct, + pace, } => ( "token_warning", relay_params(json!({ "month": month, "limit_name": limit_name, "used": used_tokens, - "limit": limit_tokens, "pct": usage_pct, "link": usage_link, + "limit": limit_tokens, "pct": usage_pct, "pace": pace, "link": usage_link, })), ), EmailEvent::TokenLimitReached { diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index fc0b3efc..3b289f96 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -766,6 +766,45 @@ impl BranchStart { } } +/// The highest `-N` a run tries for a branch of its own next to a +/// teammate's. +pub const MAX_ALTERNATE_BRANCH: u32 = 20; + +/// The `n`th branch next to `branch` (`coderhelm/acme-12-2`). +pub fn alternate_branch(branch: &str, n: u32) -> String { + format!("{branch}-{n}") +} + +/// A teammate's branch the run left as it is, and the one it used. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LeftBranch { + /// The ticket's branch, with the teammate's commits on it. + pub left: String, + /// Who made those commits. + pub who: Vec, + /// The branch the run works on instead. + pub used: String, + /// The run is the first to take `used` (it didn't exist yet): the line + /// is said once, never again at each step. + pub first: bool, +} + +impl LeftBranch { + /// The one line the run page and the ticket say. + pub fn line(&self) -> String { + let whose = if self.who.is_empty() { + "a teammate's".to_string() + } else { + format!("{}'s", self.who.join(" and ")) + }; + format!( + "`{}` holds {whose} commits with no pull request, so it was left as it is; this run \ + works on `{}`.", + self.left, self.used + ) + } +} + /// What a run may do with its existing branch before it starts work. #[derive(Debug, Clone, PartialEq, Eq)] pub enum ResetDecision { @@ -2983,6 +3022,74 @@ impl GitHubClient { Ok((new_sha.to_string(), BranchStart::Created)) } + /// Who holds `branch` when it carries commits CoderHelm didn't make and + /// no open pull request (their names); `None` when it is free: missing, + /// with an open pull request, or only CoderHelm's own commits. + async fn held_by_others( + &self, + owner: &str, + repo: &str, + branch: &str, + base: &str, + ) -> Result>, Box> { + if !self.ref_exists(owner, repo, branch).await? { + return Ok(None); + } + if self + .find_open_pr_for_branch(owner, repo, branch) + .await? + .is_some() + { + return Ok(None); + } + let ahead = self.compare_commits(owner, repo, base, branch, 250).await?; + let complete = ahead.len() < 250; + Ok(match reset_decision(false, &ahead, complete) { + ResetDecision::NotOurs(who) => Some(who), + _ => None, + }) + } + + /// The branch a run starts on in place of `branch` when a teammate's + /// work is on it (commits CoderHelm didn't make, no open pull request): + /// the first of `-2`, `-3`, ... that is free or + /// CoderHelm's own, so every step of the run lands on the same one. + /// The teammate's branch is never touched. `Ok(None)`: `branch` itself + /// is free. + pub async fn branch_clear_of_others( + &self, + owner: &str, + repo: &str, + branch: &str, + base: &str, + ) -> Result, Box> { + let base = if base.trim().is_empty() { + self.get_default_branch(owner, repo).await? + } else { + base.to_string() + }; + let Some(who) = self.held_by_others(owner, repo, branch, &base).await? else { + return Ok(None); + }; + for n in 2..=MAX_ALTERNATE_BRANCH { + let alt = alternate_branch(branch, n); + if self + .held_by_others(owner, repo, &alt, &base) + .await? + .is_none() + { + let first = !self.ref_exists(owner, repo, &alt).await?; + return Ok(Some(LeftBranch { + left: branch.to_string(), + who, + used: alt, + first, + })); + } + } + Ok(None) + } + // ─── Merge ─────────────────────────────────────────────────── /// Merge one branch into another via the GitHub Merges API. diff --git a/services/worker/src/passes/change_wait.rs b/services/worker/src/passes/change_wait.rs index ce7f13ff..2ae5637f 100644 --- a/services/worker/src/passes/change_wait.rs +++ b/services/worker/src/passes/change_wait.rs @@ -455,6 +455,7 @@ async fn check_one(state: &WorkerState, item: &HashMap) ) .await; let needs = common::run_recovery::NeedsYou { + pause: None, kind: common::run_recovery::Kind::NeedsPerson, why: common::handback::HumanOnly::ProductDecision, action: cw::closed_action(&dep), diff --git a/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs b/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs index b010ca22..5373d350 100644 --- a/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs +++ b/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs @@ -10,8 +10,8 @@ //! checkpoint (no second plan, no repeated ticket or pull request), the //! same error again with no progress takes the next strategy, and only a //! person's step stops a run, as "needs you" in plain words. An error -//! nobody classified is tried once more, then stops as "needs you", never -//! as failed. Failed runs CoderHelm now gets past are resumed by the +//! nobody classified is CoderHelm's own problem: tried again with longer +//! waits, then parked for the self-heal sweep (`xg`). Failed runs CoderHelm now gets past are resumed by the //! self-heal sweep, on deploy and every 15 minutes, once per run per //! deploy. @@ -61,32 +61,33 @@ async fn a_deleted_base_branch_moves_to_the_default_and_finishes() { assert!(w.prs.values().all(|base| base == "trunk")); } +/// An error nobody classified is CoderHelm's own problem (`xg`): tried +/// again with longer waits, then parked for the self-heal sweep with an +/// internal alert. It never stops the run for a person. #[tokio::test] -async fn an_unclassified_error_is_tried_once_then_needs_you_never_failed() { +async fn an_unclassified_error_is_retried_then_parked_never_a_persons() { let odd = "The frobnicator returned an answer nobody expected"; let mut w = World::new("acme", "site", &["site"], "tk-5"); - w.faults.push_back(Fault::Unclassified(odd.into())); - w.faults.push_back(Fault::Unclassified(odd.into())); - assert!(!w.run_to_end(6).await); - let n = w.stopped.clone().expect("stopped for a person"); - assert_eq!(n.why, common::handback::HumanOnly::Unrepaired); - assert!( - n.action.contains("the run continues by itself"), - "{}", - n.action - ); - assert!(n.detail.contains("tried again once")); + for _ in 0..4 { + w.faults.push_back(Fault::Unclassified(odd.into())); + } + assert!(!w.run_to_end(8).await); + assert!(w.stopped.is_none(), "never a person's: {:?}", w.stopped); + assert!(w.parked); assert_eq!(rr::classify(odd).kind, Kind::Unknown); - // The one failed-status write never writes it as failed. - assert_ne!( - common::run_fail::status_of(&common::run_fail::RunFailure { + // The one ending write parks it for the self-heal sweep. + let u = common::run_fail::update( + "R1", + &common::run_fail::RunFailure { cause: common::run_fail::Cause::Error(odd), ..Default::default() - }), - common::run_status::FAILED + }, + "now", ); - // Tried once more first: one retry, then the stop. - assert_eq!(w.steps, 2); + assert_eq!(u.status, common::run_status::FAILED); + assert!(u.resumable); + // Three tries with longer waits, then parked. + assert_eq!(w.steps, 4); // Once it gets past it, the next error starts its own count. let mut w = World::new("acme", "site", &["site"], "tk-6"); w.faults.push_back(Fault::Unclassified(odd.into())); @@ -107,7 +108,7 @@ fn the_orchestrator_recovers_before_anything_is_marked_failed() { let person = arm.find("recover::stop_for_person(").expect("needs you"); assert!(recover < fail && recover < person); // Every failed write for an error reads the error first: an - // unclassified one waits on a person. A stop the pass knew the reason + // unclassified one is parked as CoderHelm's own problem. A stop the pass knew the reason // for is typed and never read by the classifier (`vv`). let fail_fn = fn_src(src, "pub(crate) async fn fail_run("); assert!(fail_fn.contains("common::run_fail::Cause::Error(error_msg)")); 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 23404640..0a2c1777 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 @@ -26,7 +26,7 @@ use common::handback::HumanOnly; use common::rendered::person_text; -use common::run_recovery::{person_action, unknown_stop, Classified, Kind}; +use common::run_recovery::{own_problem_line, person_action, Classified, Kind}; const RUN_RECOVERY: &str = include_str!("../../../../common/src/run_recovery.rs"); const RUN_FAIL: &str = include_str!("../../../../common/src/run_fail.rs"); @@ -65,13 +65,10 @@ fn a_wait_says_the_run_goes_on_by_itself() { plain: "The frobnicator answered something nobody expected.".into(), signature: "s".into(), }; - let n = unknown_stop(&odd, 1); - assert!(!n.action.contains("put it right"), "{}", n.action); - assert!( - n.action.contains("the run continues by itself"), - "{}", - n.action - ); + // An error nobody classified is CoderHelm's own: never a person's step. + let line = own_problem_line(&odd); + assert!(!line.contains("put it right"), "{line}"); + assert!(line.contains("goes on by itself"), "{line}"); for src in [RUN_RECOVERY, RUN_FAIL] { assert!(!src.contains("then press Retry\"")); assert!(!src.contains("put it right, then")); diff --git a/services/worker/src/passes/incidents/xg_token_limit_pauses_and_resumes.rs b/services/worker/src/passes/incidents/xg_token_limit_pauses_and_resumes.rs new file mode 100644 index 00000000..6f53bde2 --- /dev/null +++ b/services/worker/src/passes/incidents/xg_token_limit_pauses_and_resumes.rs @@ -0,0 +1,664 @@ +//! xg. Several runs on one install planned, then stopped at the start of +//! building with "CoderHelm met an error it doesn't know how to repair, and +//! stopped without trying again: Monthly new tokens limit reached ... ", +//! headed "Look at what stopped the run, put it right, then press Retry" +//! and "Needs a person". The month turned at 00:00 UTC and nothing resumed +//! them: a person pressed Retry hours later. The classifier knew only the +//! older wording of the limit ("limit exceeded"), so the refusal every model +//! call now gives ("limit reached") read as an error nobody knew. No warning +//! came before the limit, and new runs kept starting into it. The same +//! night a run stopped with the same frame because the ticket's branch held +//! a teammate's commits with no pull request. +//! +//! Guarantees (replayed on the acme bookstore): +//! - a refused model call is a typed pause (`token_room::Pause`), never an +//! unknown error and never a person's step; it keeps the run's +//! continuation and resumes in place, from that step, when the month +//! turns or the limit is raised; +//! - a new run waits for token room when what is left is less than a run +//! of its kind takes; runs in progress come first on what is left; +//! - admins are warned at 80% and 95%, once each a month, with the day the +//! limit runs out at this month's pace; +//! - the month's turn wakes the paused runs at 00:00 UTC on the 1st; +//! - a teammate's branch is left as it is and the run works on the next +//! free `-N`; +//! - "an error it doesn't know how to repair ... put it right, then press +//! Retry" is unreachable: an error nobody classified is CoderHelm's own +//! problem (an internal alert, one plain line, retries with backoff); +//! - runs an older release stopped this way are found by their stored words +//! and go on by themselves after the deploy. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use chrono::{DateTime, Utc}; +use common::run_fail::{update, Cause, RunFailure}; +use common::run_recovery::{self as rr, Kind}; +use common::run_wait::WaitingOn; +use common::token_limits::{Limit, LimitKind, LimitUse, TokenLimits}; +use common::token_room::{self as tr, Pause, PauseKind, RunUse, Waiting}; +use common::usage::UsageTotals; + +use crate::clients::github::{alternate_branch, LeftBranch}; +use crate::passes::recover::{resend_for, Resend}; + +const MOD: &str = include_str!("../mod.rs"); +const RECOVER: &str = include_str!("../recover.rs"); +const RUN_WAKE: &str = include_str!("../run_wake.rs"); +const TOKEN_ROOM: &str = include_str!("../token_room.rs"); +const GITHUB: &str = include_str!("../../clients/github.rs"); +const API_STACK: &str = include_str!("../../../../../infra/lib/api-stack.ts"); +const GATEWAY_WAKE: &str = include_str!("../../../../gateway/src/routes/run_wake.rs"); +const GATEWAY_API: &str = include_str!("../../../../gateway/src/routes/api.rs"); + +/// The refusal a model call gave on the bookstore's install. +const REFUSED: &str = "Implement failed: Monthly new tokens limit reached (40.3M of 40M). New \ + model calls are stopped until the month turns or an admin raises the limit in Settings, \ + Token Limit."; + +/// The words an older release stored on a run it stopped this way. +const OLD_STOP: &str = "CoderHelm met an error it doesn't know how to repair, and stopped \ + without trying again: Monthly new tokens limit reached (40.3M of 40M). New model calls are \ + stopped until the month turns or an admin raises the limit in Settings, Token Limit."; + +fn at(s: &str) -> DateTime { + DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc) +} + +fn sv(u: &common::run_fail::Update, k: &str) -> String { + u.values[k].as_s().unwrap().clone() +} + +fn limit(max: u64) -> TokenLimits { + TokenLimits { + limits: vec![Limit { + kind: LimitKind::NewTokens, + max, + }], + legacy: false, + } +} + +fn new_tokens(n: u64) -> UsageTotals { + UsageTotals { + tokens_in_uncached: n / 4, + tokens_out: n - n / 4, + ..Default::default() + } +} + +/// The bookstore's finished runs: a Jira run takes about 3M new tokens. +fn history() -> Vec { + (1..=5) + .map(|i| RunUse { + run_id: format!("01DONE{i}"), + kind: "jira".into(), + status: "completed".into(), + updated_at: format!("2026-11-0{i}T10:00:00Z"), + used: new_tokens(3_000_000), + paused_mid_run: false, + }) + .collect() +} + +fn item(pairs: &[(&str, &str)]) -> HashMap { + pairs + .iter() + .map(|(k, v)| (k.to_string(), AttributeValue::S(v.to_string()))) + .collect() +} + +#[test] +fn a_refused_call_mid_run_is_a_typed_pause_that_resumes_from_its_step_after_the_month_turns() { + // Classified as the limit, never as an unknown error. + let c = rr::classify(REFUSED); + assert_eq!(c.kind, Kind::TokenLimit); + let needs = match rr::next(&c, &rr::Ledger::default(), "implement|abc") { + rr::Next::NeedsYou(n) => n, + other => panic!("{other:?}"), + }; + assert!(needs.pause.is_some(), "typed"); + + // The ending at 21:10 UTC on Nov 30: waiting on the limit, the pause on + // the record, the one line said, no person's step. + let needs = rr::usage_limit_at(REFUSED, at("2026-11-30T21:10:00Z")); + let u = update( + "01BOOK", + &RunFailure { + cause: Cause::NeedsYou { + reason: &needs.detail, + needs: &needs, + }, + ..Default::default() + }, + "now", + ); + assert_eq!(sv(&u, ":failed"), common::run_status::NEEDS_INPUT); + let wait: WaitingOn = serde_json::from_str(&sv(&u, ":wo")).unwrap(); + let p = wait.pause.clone().expect("a typed pause"); + assert_eq!( + p, + Pause { + kind: PauseKind::TokenLimit, + limit: "new tokens".into(), + used: 40_300_000, + max: 40_000_000, + room: 0, + need: 0, + in_progress: false, + resumes_at: "2026-12-01T00:00:00+00:00".into(), + line: "Paused: this month's token limit is used up (40.3M of 40M). Resumes by itself \ + on Dec 1, 00:00 UTC when the month turns, or as soon as an admin raises the \ + limit." + .into(), + settings_path: "/settings/budget".into(), + } + ); + assert_eq!(wait.action, p.line); + assert_eq!(u.said, p.line); + for text in [&wait.action, &u.said, &sv(&u, ":err")] { + assert!(!text.contains("Retry"), "{text}"); + assert!(!text.contains("doesn't know how to repair"), "{text}"); + assert_eq!(common::rendered::person_text(text), None, "{text}"); + } + + // The run keeps its continuation: the same run, one step on, from its + // checkpoint. Not a held draft. + let stop = fn_body(RECOVER, "\npub async fn stop_for_person("); + assert!( + stop.find("needs.pause.is_some()").unwrap() < stop.find("keep_resume_message(").unwrap() + ); + assert!(MOD.contains( + "let goes_on = parked || needs_you.as_ref().is_some_and(|n| n.pause.is_some());" + )); + assert!(MOD.contains("let salvaged = if continued || guard_ended || goes_on {")); + let mut rec = item(&[ + ("team_id", "TEAM#acme"), + ("run_id", "01BOOK"), + ("status", "needs_input"), + ("repo", "acme/bookstore-web"), + ("ticket_source", "jira"), + ("ticket_id", "BOOK-12"), + ("updated_at", "2026-11-30T21:10:00Z"), + ]); + rec.insert(common::run_wait::FIELD_WAITING_ON.into(), wait.to_attr()); + rec.insert("run_step".into(), AttributeValue::N("3".into())); + match resend_for(&rec) { + Some(Resend::Ticket(t)) => { + assert_eq!(t.continuation_run_id.as_deref(), Some("01BOOK")); + assert_eq!(t.continuation, 4, "one step on, from where it stopped"); + } + other => panic!("{other:?}"), + } + + // Before the month turns: still at the limit, nothing wakes. After: + // the new month's counters are empty, and it goes on. + let waiting = [Waiting { + run_id: "01BOOK".into(), + kind: "jira".into(), + mid_run: true, + room_wait: false, + since: "2026-11-30T21:10:00Z".into(), + used: new_tokens(1_200_000), + }]; + assert!(tr::plan_wakes( + &limit(40_000_000), + &new_tokens(40_300_000), + &history(), + &waiting, + 50 + ) + .is_empty()); + assert!(!p.month_turned(at("2026-11-30T23:59:59Z"))); + assert!(p.month_turned(at("2026-12-01T00:00:30Z"))); + assert_eq!( + tr::plan_wakes( + &limit(40_000_000), + &UsageTotals::default(), + &history(), + &waiting, + 50 + ), + vec!["01BOOK".to_string()] + ); + // It resumes in place, from its checkpoint: never superseded by a new + // run, and never by the gateway's retry-style wake. + let wake = fn_body(TOKEN_ROOM, "\npub async fn resume_in_place("); + assert!(wake.contains("super::recover::resend_for(item)")); + assert!(!wake.contains("superseded")); + assert!( + GATEWAY_WAKE.contains("!(wake == Wake::Limit && common::token_room::waits_on_limit(i))") + ); +} + +#[test] +fn a_new_run_waits_for_token_room_instead_of_starting_into_the_wall() { + let h = history(); + let need = tr::estimate(&h, "jira").unwrap(); + assert_eq!(need.uncached_total(), 3_000_000); + // 1.2M left for a run that takes about 3M. + let p = tr::start_room( + &limit(40_000_000), + &new_tokens(38_800_000), + &UsageTotals::default(), + &need, + at("2026-11-28T09:00:00Z"), + ) + .expect("waits"); + assert_eq!(p.kind, PauseKind::TokenRoom); + assert_eq!((p.room, p.need), (1_200_000, 3_000_000)); + assert!(p.line.starts_with( + "Waiting for token room: this month's token limit has 1.2M left and a run like this \ + takes about 3M. Starts by itself on Dec 1, 00:00 UTC" + )); + assert_eq!(common::rendered::person_text(&p.line), None); + let needs = rr::paused(p.clone()); + assert_eq!( + (needs.kind, needs.pause.as_ref()), + (Kind::TokenLimit, Some(&p)) + ); + // Plenty of room: it starts. + assert!(tr::start_room( + &limit(40_000_000), + &new_tokens(20_000_000), + &UsageTotals::default(), + &need, + at("2026-11-28T09:00:00Z"), + ) + .is_none()); + + // The pipeline asks before a new run's first pass, after the limit's + // own check, and ends the run once (never returned as an error to end + // again). + let rp = fn_body(MOD, "\nasync fn run_passes("); + let budget = rp + .find("check_budget_exceeded(state, &msg.team_id)") + .unwrap(); + let room = rp + .find("token_room::start_room(state, msg, run_id)") + .unwrap(); + let first_pass = rp.find("update_pass(").unwrap(); + assert!(budget < room && room < first_pass); + assert!(rp[room - 200..room].contains("if !msg.same_run()")); + let after = &rp[room..first_pass]; + assert!(after.contains("token_room::pause(state, msg, run_id, &needs, usage, duration)")); + assert!(after.contains("return Ok(());")); + + // A run under way waits before its costly step (building) when the + // rest of it wouldn't fit, and goes first when woken. + let p = tr::step_room( + &limit(40_000_000), + &new_tokens(38_500_000), + &need, + &new_tokens(1_000_000), + at("2026-11-28T09:00:00Z"), + ) + .expect("waits before building"); + assert!(p.mid_run()); + let step = MOD + .find("token_room::step_room(state, msg, run_id)") + .unwrap(); + let build = MOD[step..] + .find("update_pass(state, &msg.team_id, run_id, \"implement\")") + .unwrap(); + assert!(build < 600, "checked right before the implement pass"); +} + +#[test] +fn runs_in_progress_come_first_on_the_room_left() { + let mut h = history(); + // Half way through, 1M used of the 3M a run takes. + h.push(RunUse { + run_id: "01LIVE".into(), + kind: "jira".into(), + status: "running".into(), + updated_at: "2026-11-28T08:00:00Z".into(), + used: new_tokens(1_000_000), + paused_mid_run: false, + }); + let need = tr::estimate(&h, "jira").unwrap(); + let reserve = tr::reserved(&h, &["01NEW"]); + assert_eq!(reserve.uncached_total(), 2_000_000); + // 4M left: enough for the new run alone, not before the live run's 2M. + let month = new_tokens(36_000_000); + let now = at("2026-11-28T09:00:00Z"); + assert!(tr::start_room( + &limit(40_000_000), + &month, + &UsageTotals::default(), + &need, + now + ) + .is_none()); + assert!(tr::start_room(&limit(40_000_000), &month, &reserve, &need, now).is_some()); + + // The wake: a run paused half way goes before new runs that queued + // earlier, and new runs only take what is left after it. + let w = |id: &str, mid: bool, since: &str| Waiting { + run_id: id.into(), + kind: "jira".into(), + mid_run: mid, + room_wait: !mid, + since: since.into(), + used: if mid { + new_tokens(1_000_000) + } else { + UsageTotals::default() + }, + }; + let waiting = vec![ + w("01NEW-A", false, "2026-11-20T10:00:00Z"), + w("01HALF", true, "2026-11-25T10:00:00Z"), + w("01NEW-B", false, "2026-11-21T10:00:00Z"), + ]; + assert_eq!( + tr::plan_wakes( + &limit(40_000_000), + &new_tokens(35_000_000), + &history(), + &waiting, + 50 + ), + vec!["01HALF".to_string(), "01NEW-A".to_string()] + ); +} + +#[test] +fn admins_are_warned_at_80_and_95_once_each_with_the_day_it_runs_out() { + let u = |used| LimitUse { + kind: LimitKind::NewTokens, + max: 40_000_000, + used, + }; + let levels: Vec> = [31_000_000, 32_000_000, 37_900_000, 38_000_000, 40_000_000] + .iter() + .map(|n| common::token_limits::warning_level(&u(*n))) + .collect(); + assert_eq!(levels, vec![None, Some(80), Some(80), Some(95), Some(100)]); + // Each level its own once-a-month key. + let keys: std::collections::HashSet = [80, 95, 100] + .iter() + .map(|l| common::token_limits::warning_sk("2026-11", LimitKind::NewTokens, *l)) + .collect(); + assert_eq!(keys.len(), 3); + assert_ne!( + common::token_limits::warning_sk("2026-11", LimitKind::NewTokens, 95), + common::token_limits::warning_sk("2026-12", LimitKind::NewTokens, 95) + ); + // The send reads the key first and writes it with the send: once. + let send = fn_body(MOD, "\nasync fn check_token_usage_warning("); + let read = send.find("let already_sent").unwrap(); + let skip = send.find("if already_sent {").unwrap(); + let mail = send.find("email::send_notification(").unwrap(); + assert!(read < skip && skip < mail); + // With the day the limit runs out at this pace. + let pace = tr::pace_line(32_000_000, 40_000_000, at("2026-11-21T00:00:00Z")); + assert!(pace.contains("runs out on Nov 26, 00:00 UTC"), "{pace}"); + // The dashboard's banner reads the same level and day. + assert!( + GATEWAY_API.contains("warn_level: common::token_limits::warning_level(u).unwrap_or(0),") + ); + assert!(GATEWAY_API.contains(".then(|| common::token_room::projected_out(u.used, u.max, now))")); +} + +#[test] +fn the_months_turn_wakes_the_paused_runs() { + assert_eq!( + tr::month_turn(at("2026-11-30T21:10:00Z")), + at("2026-12-01T00:00:00Z") + ); + assert_eq!( + tr::month_turn(at("2026-12-31T23:00:00Z")), + at("2027-01-01T00:00:00Z") + ); + // A schedule at 00:00 and 00:01 UTC on the 1st sends the sweep. + let rule = &API_STACK[API_STACK.find("\"TokenMonthTurnSchedule\"").unwrap()..]; + let rule = &rule[..rule.find("});").unwrap()]; + assert!(rule.contains("events.Schedule.cron({ minute: \"0,1\", hour: \"0\", day: \"1\" })")); + assert!(rule.contains("type: \"self_heal_sweep\"")); + // The sweep wakes the limit's waits, and those go to the token wake. + let sweep = fn_body(RECOVER, "\npub async fn self_heal_sweep("); + assert!(sweep.contains("super::run_wake::wake_limit_waits(state).await")); + let limit_wake = fn_body(RUN_WAKE, "\npub async fn wake_limit_waits("); + assert!(limit_wake.contains("super::token_room::wake_team(state, &team, &token).await")); + // A saved limit sends the sweep at once too. + let saved = fn_body(GATEWAY_API, "\nasync fn wake_after_limit("); + assert!(saved.contains("\"type\": \"self_heal_sweep\"")); + // The run page says which woke it. + let p = Pause::limit_reached( + &tr::Refusal { + limit: "new tokens".into(), + used: 40_300_000, + max: 40_000_000, + }, + at("2026-11-30T21:10:00Z"), + ); + let mut rec = item(&[("status", "needs_input")]); + rec.insert( + common::run_wait::FIELD_WAITING_ON.into(), + WaitingOn { + action: p.line.clone(), + pause: Some(p), + ..Default::default() + } + .to_attr(), + ); + assert_eq!( + crate::passes::token_room::wake_reason(&[&rec], at("2026-12-01T00:00:30Z")), + "the month turned and the token limit started again" + ); +} + +#[test] +fn a_teammates_branch_is_left_as_it_is_and_the_run_starts_on_a_new_one() { + assert_eq!( + alternate_branch("coderhelm/book-12-cover-image", 2), + "coderhelm/book-12-cover-image-2" + ); + let left = LeftBranch { + left: "coderhelm/book-12-cover-image".into(), + who: vec!["Riley Reader".into()], + used: "coderhelm/book-12-cover-image-2".into(), + first: true, + }; + let line = left.line(); + assert_eq!( + line, + "`coderhelm/book-12-cover-image` holds Riley Reader's commits with no pull request, so it \ + was left as it is; this run works on `coderhelm/book-12-cover-image-2`." + ); + assert_eq!(common::rendered::person_text(&line), None); + // Not a hand-off: no wait, no retry, no stop. + assert!(!line.contains("Retry") && !line.contains("Open a pull request")); + + // The ticket's branch is resolved clear of a teammate's work before any + // branch is started, in both the one-repository and per-repository runs. + let resolve = fn_body(MOD, "\nasync fn resolve_run_branch("); + assert!(resolve.contains(".branch_clear_of_others(owner, name, &branch, base)")); + assert_eq!(MOD.matches("left.filter(|l| l.first)").count(), 2); + let say = fn_body(MOD, "\nasync fn say_left_branch("); + assert!(say.contains("add_progress_note(") && say.contains("post_ticket_notice(")); + // Only a branch that is free or CoderHelm's own is taken. + let clear = fn_body(GITHUB, "\n pub async fn branch_clear_of_others("); + assert!(clear.contains(".held_by_others(owner, repo, &alt, &base)")); + let held = fn_body(GITHUB, "\n async fn held_by_others("); + assert!(held.contains("ResetDecision::NotOurs(who) => Some(who)")); +} + +#[test] +fn the_generic_frame_is_unreachable() { + // Every kind of error, ended through the one ending write: none says + // the frame, and none waits on a person to "put it right". + for reason in [ + REFUSED, + OLD_STOP, + "Monthly token limit exceeded (5 / 4 tokens). Increase your limit in Settings under Token Limit.", + "The frobnicator answered something nobody expected", + "Multi-repo pipeline produced no PRs", + "HTTP status client error (422 Unprocessable Entity) for url (https://api.github.com/repos/acme/bookstore-web/pulls): {\"message\":\"Validation Failed\"}", + "HTTP status server error (502 Bad Gateway) for url (https://api.github.com/repos/acme/bookstore-web/pulls)", + "", + ] { + let u = update("01X", &RunFailure { cause: Cause::Error(reason), ..Default::default() }, "now"); + let mut texts = vec![sv(&u, ":err"), u.said.clone()]; + if let Some(AttributeValue::S(wo)) = u.values.get(":wo") { + let w: WaitingOn = serde_json::from_str(wo).unwrap(); + texts.push(w.action); + } + for t in texts { + assert!(!t.contains("doesn't know how to repair"), "{reason}: {t}"); + assert!(!t.to_lowercase().contains("put it right"), "{reason}: {t}"); + } + } + // An error nobody classified: CoderHelm's own, retried with backoff, + // then parked for the self-heal sweep with an internal alert. + let c = rr::classify("The frobnicator answered something nobody expected"); + assert_eq!(c.kind, Kind::Unknown); + assert!(c.kind.parks() && !c.kind.resumable()); + // The sweep brings back only what this release parked as its own. + let parked = item(&[ + ("status", "failed"), + ( + "error_detail", + "The frobnicator answered something nobody expected", + ), + ("error_kind", "unknown"), + ]); + assert!(crate::passes::recover::sweep_wants(&parked, "v9")); + let older = item(&[ + ("status", "failed"), + ( + "error_message", + "The frobnicator answered something nobody expected", + ), + ]); + assert!(!crate::passes::recover::sweep_wants(&older, "v9")); + let mut l = rr::Ledger::default(); + for want in [30, 60, 120] { + assert_eq!(rr::next(&c, &l, "m"), rr::Next::Retry { delay_secs: want }); + l.record(&c, "retry", "m", "t"); + } + assert_eq!(rr::next(&c, &l, "m"), rr::Next::Park); + let end = fn_body(MOD, "\nasync fn end_with("); + assert!(end.contains( + "own_problems::alert(state, &msg.team_id, run_id, \"unclassified_error\", &c.plain)" + )); + + // The guard fails the phrase anywhere a person reads it. + assert!(common::rendered::person_text(OLD_STOP).is_some()); + assert!(common::rendered::person_text( + "Look at what stopped the run, put it right, then press Retry" + ) + .is_some()); + + // No producer is left in the services' code (comments and tests aside). + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let mut found = Vec::new(); + let mut stack = vec![ + root.join("common/src"), + root.join("worker/src"), + root.join("gateway/src"), + ]; + while let Some(dir) = stack.pop() { + for e in std::fs::read_dir(&dir).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + if !p.ends_with("incidents") { + stack.push(p); + } + continue; + } + if p.extension().is_none_or(|x| x != "rs") || p.ends_with("rendered.rs") { + continue; + } + let text = std::fs::read_to_string(&p).unwrap_or_default(); + let code = text + .find("#[cfg(test)]") + .map_or(text.as_str(), |i| &text[..i]); + for (i, line) in code.lines().enumerate() { + let t = line.trim_start(); + if t.starts_with("//") { + continue; + } + if line.contains("know how to repair") + || line.contains("put it right, then press Retry") + { + found.push(format!("{}:{}", p.display(), i + 1)); + } + } + } + } + assert!( + found.is_empty(), + "the generic frame is still produced at {found:?}" + ); +} + +#[test] +fn runs_stopped_this_way_before_the_deploy_go_on_by_themselves() { + // The stuck run as an older release left it: waiting on a person, the + // refusal only in its stored words, no pause, no kept continuation. + let old_wait = WaitingOn { + action: "Look at what stopped the run, put it right, then press Retry".into(), + detail: OLD_STOP.into(), + handback: "unrepaired".into(), + ..Default::default() + }; + let mut rec = item(&[ + ("team_id", "TEAM#acme"), + ("run_id", "01STUCK"), + ("status", "needs_input"), + ("repo", "acme/bookstore-web"), + ("ticket_source", "jira"), + ("ticket_id", "BOOK-14"), + ("error_message", OLD_STOP), + ("updated_at", "2026-11-30T21:20:00Z"), + ]); + rec.insert( + common::run_wait::FIELD_WAITING_ON.into(), + old_wait.to_attr(), + ); + assert!(tr::waits_on_limit(&rec)); + // The limit's wake reads it as a wait on the limit, paused half way. + let items = vec![rec.clone()]; + let by_team = crate::passes::run_wake::limit_waits(&items); + assert_eq!(by_team["TEAM#acme"].len(), 1); + assert!(crate::passes::token_room::waiting_of(&rec).mid_run); + // It goes on as the same run, one step on, from its checkpoint. + match resend_for(&rec) { + Some(Resend::Ticket(t)) => { + assert_eq!(t.continuation_run_id.as_deref(), Some("01STUCK")); + assert_eq!(t.continuation, 2, "the step after its first"); + } + other => panic!("{other:?}"), + } + // A wait on something else is left alone. + let mut other = rec.clone(); + other.insert( + "error_message".into(), + AttributeValue::S("Review pull request #8".into()), + ); + other.insert( + common::run_wait::FIELD_WAITING_ON.into(), + WaitingOn { + action: "Review pull request #8".into(), + handback: "person_action".into(), + ..Default::default() + } + .to_attr(), + ); + assert!(!tr::waits_on_limit(&other)); + // The deploy's first sweep runs the limit's wake. + assert!(RECOVER.contains("report.woken = super::run_wake::wake_limit_waits(state).await;")); +} + +/// The body of the function that starts at `head` in `src`. +fn fn_body<'a>(src: &'a str, head: &str) -> &'a str { + let start = src.find(head).unwrap_or_else(|| panic!("{head} not found")); + let rest = &src[start..]; + let end = rest + .find("\n}\n") + .or_else(|| rest.find("\n }\n")) + .unwrap_or(rest.len()); + &rest[..end] +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 7d979ad4..8f3c6af8 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1513,6 +1513,7 @@ pub(crate) mod test_setup; pub mod ticket_base; pub mod ticket_comments; pub mod ticket_history; +pub mod token_room; pub mod tool_proposals; mod triage; pub mod upgrade_notes; @@ -1764,9 +1765,12 @@ pub async fn orchestrate_ticket( // repaired and the same pass resumes from its checkpoint, // the same error again with no progress takes another // strategy, and only what a person must do stops the run, as - // "needs you" in plain words. An unclassified error is tried - // again once. + // "needs you" in plain words. An unclassified error is + // CoderHelm's own: tried again with longer waits, then parked + // for the self-heal sweep. A refusal by the token limit + // pauses the run with its continuation kept. let mut needs_you: Option = None; + let mut parked = false; let continued = continued || !guard_ended && e.downcast_ref::().is_none() @@ -1778,14 +1782,22 @@ pub async fn orchestrate_ticket( needs_you = Some(n); false } + recover::AfterError::Parked => { + parked = true; + false + } recover::AfterError::NotHandled => false, }; + // A pause on the token limit, or CoderHelm's own problem + // parked for the self-heal sweep, goes on from its + // checkpoint: never a stopped draft. + let goes_on = parked || needs_you.as_ref().is_some_and(|n| n.pause.is_some()); // A run stopped after its work started (mid-implement or by a // check after it) with work on its branch gets the standard // held draft (`stop_pr`): its ticket line, what is done and // left, and the recorded reason. One path, never a separate // "partial" pull request. - let salvaged = if continued || guard_ended { + let salvaged = if continued || guard_ended || goes_on { false } else if let Some((ref last_pass, ref branch, _)) = checkpoint { if !branch.is_empty() @@ -2268,12 +2280,27 @@ async fn run_passes( let implement_deadline = Some(*start + std::time::Duration::from_secs(LAMBDA_TIMEOUT_SECS.saturating_sub(150))); - // Pre-run budget gate: reject if monthly token limit exceeded + // Pre-run budget gate: a reached monthly token limit pauses the run + // (its continuation kept), and it goes on by itself when the month + // turns or the limit is raised (`token_room`). The ending is written + // here, once: nothing is returned for the error path to end again. if let Some(reason) = check_budget_exceeded(state, &msg.team_id).await { - warn!(run_id, team_id = %msg.team_id, %reason, "Run rejected: budget exceeded"); + info!(run_id, team_id = %msg.team_id, %reason, "Run paused: the token limit is reached"); let duration = start.elapsed().as_secs(); let _ = end_at_usage_limit(state, msg, run_id, &reason, usage, duration).await; - return Err(reason.into()); + return Ok(()); + } + // A new run waits for room instead of starting and dying half way: + // what is left of the month's limit, after what the runs in progress + // still need, against what a run of its kind takes. + if !msg.same_run() { + if let Some(p) = token_room::start_room(state, msg, run_id).await { + info!(run_id, team_id = %msg.team_id, line = %p.line, "Run waits for token room"); + let duration = start.elapsed().as_secs(); + let needs = common::run_recovery::paused(p); + token_room::pause(state, msg, run_id, &needs, usage, duration).await; + return Ok(()); + } } // Initialize GitHub client for this team @@ -4389,7 +4416,7 @@ async fn run_passes( None => match common::security_fixes::branch_in_body(&msg.ticket_id, &msg.body) { Some(b) => b, None => { - resolve_run_branch( + let (b, left) = resolve_run_branch( &github, &msg.repo_owner, &msg.repo_name, @@ -4397,8 +4424,13 @@ async fn run_passes( &conventions, &tokens, "", + &msg.base_branch, ) - .await + .await; + if let Some(l) = left.filter(|l| l.first) { + say_left_branch(state, msg, run_id, &github, &l).await; + } + b } }, }; @@ -4635,6 +4667,16 @@ false, } } else { check_cancelled(state, &msg.team_id, run_id).await?; + // The costly step: a run whose rest wouldn't fit in what is left of + // the month's limit waits here, between steps, with its plan kept, + // instead of meeting the limit half way through building. + if let Some(p) = token_room::step_room(state, msg, run_id).await { + info!(run_id, line = %p.line, "Run waits for token room before building"); + let duration = start.elapsed().as_secs(); + let needs = common::run_recovery::paused(p); + token_room::pause(state, msg, run_id, &needs, usage, duration).await; + return Ok(()); + } update_pass(state, &msg.team_id, run_id, "implement").await?; // The plan is final from here: a comment read now is applied as a // round on the pull request when this step ends. @@ -5558,18 +5600,21 @@ false, // branch of the PR already open there for this ticket. let mut repo_branches: Vec = Vec::new(); for repo_task in &plan_result.repo_tasks { - repo_branches.push( - resolve_run_branch( - &github, - &repo_task.owner, - &repo_task.name, - &msg.ticket_id, - &conventions, - &tokens, - &repo_task.name.to_lowercase(), - ) - .await, - ); + let (b, left) = resolve_run_branch( + &github, + &repo_task.owner, + &repo_task.name, + &msg.ticket_id, + &conventions, + &tokens, + &repo_task.name.to_lowercase(), + "", + ) + .await; + if let Some(l) = left.filter(|l| l.first) { + say_left_branch(state, msg, run_id, &github, &l).await; + } + repo_branches.push(b); } // A pull request for this ticket already open in any of the repos @@ -11178,7 +11223,24 @@ async fn end_with( // a person does. The ticket hears the plain words, never the raw error. let decided = common::run_fail::update(run_id, &failure, ""); let ended_as = decided.status; - if decided.resumable { + // A pause on the token limit is woken with its continuation too. + let paused = match &failure.cause { + common::run_fail::Cause::NeedsYou { needs, .. } => needs.pause.is_some(), + common::run_fail::Cause::Error(e) => { + common::run_recovery::classify(e).kind == common::run_recovery::Kind::TokenLimit + } + common::run_fail::Cause::Stopped { .. } => false, + }; + // An error nobody classified is CoderHelm's own problem: an internal + // alert for its maintainers (`own_problems`), and the run goes on by + // itself; never a person's step. + if let common::run_fail::Cause::Error(e) = &failure.cause { + let c = common::run_recovery::classify(e); + if c.kind == common::run_recovery::Kind::Unknown { + own_problems::alert(state, &msg.team_id, run_id, "unclassified_error", &c.plain).await; + } + } + if decided.resumable || paused { // The continuation the self-heal sweep sends: the same run, from // its checkpoint and its own plan. recover::keep_resume_message(state, msg, run_id).await; @@ -11559,7 +11621,12 @@ pub fn ticket_tokens(msg: &TicketMessage) -> common::git_conventions::Tokens { /// team's pattern and the default, then any open pull request CoderHelm /// opened for the ticket (an earlier pattern, an earlier title's slug). Only /// when there is none is a new branch named from the team's pattern. -/// `suffix` is a multi-repo run's repository name. +/// `suffix` is a multi-repo run's repository name. A new branch whose name +/// a teammate's work already holds (their commits, no open pull request) +/// is never touched and never stops the run: the run takes the next free +/// `-N` instead, and says so once (`LeftBranch`). `base` is the +/// branch the run starts from (the repository's default when empty). +#[allow(clippy::too_many_arguments)] async fn resolve_run_branch( github: &GitHubClient, owner: &str, @@ -11568,19 +11635,60 @@ async fn resolve_run_branch( conventions: &common::git_conventions::GitConventions, tokens: &common::git_conventions::Tokens, suffix: &str, -) -> String { + base: &str, +) -> (String, Option) { let candidates = conventions.branch_candidates(tokens, suffix); for c in &candidates { if let Ok(Some(_)) = github.find_open_pr_for_branch(owner, name, c).await { - return c.clone(); + return (c.clone(), None); } } if let Ok(prs) = github.list_open_pulls(owner, name).await { if let Some(b) = own_pr_branch_for_ticket(&prs, ticket_id) { - return b; + return (b, None); + } + } + let branch = candidates[0].clone(); + match github + .branch_clear_of_others(owner, name, &branch, base) + .await + { + Ok(Some(left)) => (left.used.clone(), Some(left)), + Ok(None) => (branch, None), + Err(e) => { + // The branch start reads it again and never resets a person's + // commits. + warn!(branch = %branch, error = %e, "Couldn't read whose work the branch holds"); + (branch, None) } } - candidates[0].clone() +} + +/// Says once, on the run page and the ticket, that a teammate's branch was +/// left as it is and which branch the run works on. Not a hand-off and not +/// a failure: the run goes on. +async fn say_left_branch( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + github: &GitHubClient, + left: &crate::clients::github::LeftBranch, +) { + let line = left.line(); + info!(run_id, left = %left.left, used = %left.used, "A teammate's branch was left as it is"); + add_progress_note(state, &msg.team_id, run_id, &line).await; + post_ticket_notice( + state, + msg, + run_id, + github, + &format!("branch_left:{}", left.left), + &line, + &line, + "Branch left as it is", + &[], + ) + .await; } /// The branch of an open pull request CoderHelm opened (its author is the @@ -13994,7 +14102,7 @@ async fn check_token_usage_warning(state: &WorkerState, team_id: &str, _usage: & continue; } - let Some(event) = token_warning_event(&month, &u) else { + let Some(event) = token_warning_event(&month, &u, chrono::Utc::now()) else { continue; }; @@ -14031,10 +14139,12 @@ fn format_tokens(n: u64) -> String { } } -/// The email for one limit at its warning level (100% reached, or 80%). +/// The email for one limit at its warning level (100% reached, or 95% or +/// 80% with the day it runs out at this month's pace), each once a month. fn token_warning_event( month: &str, u: &common::token_limits::LimitUse, + now: chrono::DateTime, ) -> Option { use crate::clients::email::EmailEvent; let limit_name = match u.kind { @@ -14054,6 +14164,7 @@ fn token_warning_event( used_tokens: format_tokens(u.used), limit_tokens: format_tokens(u.max), usage_pct: u.pct().min(99) as u8, + pace: common::token_room::pace_line(u.used, u.max, now), }), } } @@ -14068,6 +14179,49 @@ mod token_limit_tests { LimitUse { kind, max, used } } + fn now() -> chrono::DateTime { + chrono::DateTime::parse_from_rfc3339("2026-10-21T00:00:00Z") + .unwrap() + .with_timezone(&chrono::Utc) + } + + /// 80% and 95% each warn once, with the day the limit runs out at this + /// month's pace. + #[test] + fn warnings_at_80_and_95_say_when_the_limit_runs_out() { + // 80% in 20 days: out on the 26th. + match token_warning_event( + "2026-10", + &at(LimitKind::NewTokens, 32_000_000, 40_000_000), + now(), + ) { + Some(EmailEvent::TokenWarning80 { + usage_pct, pace, .. + }) => { + assert_eq!(usage_pct, 80); + assert!(pace.contains("runs out on Oct 26, 00:00 UTC"), "{pace}"); + } + _ => panic!("expected an 80% warning"), + } + match token_warning_event( + "2026-10", + &at(LimitKind::NewTokens, 38_200_000, 40_000_000), + now(), + ) { + Some(EmailEvent::TokenWarning80 { + usage_pct, pace, .. + }) => { + assert_eq!(usage_pct, 95); + assert!(pace.contains("runs out on Oct 21"), "{pace}"); + } + _ => panic!("expected a 95% warning"), + } + assert_ne!( + common::token_limits::warning_sk("2026-10", LimitKind::NewTokens, 80), + common::token_limits::warning_sk("2026-10", LimitKind::NewTokens, 95) + ); + } + #[test] fn the_reason_names_the_limit_reached() { let r = budget_reason(&at(LimitKind::CacheRead, 60, 50)); @@ -14093,8 +14247,10 @@ mod token_limit_tests { #[test] fn warnings_go_out_per_limit_at_80_and_100() { - assert!(token_warning_event("2026-10", &at(LimitKind::CacheWrite, 79, 100)).is_none()); - match token_warning_event("2026-10", &at(LimitKind::CacheWrite, 85, 100)) { + assert!( + token_warning_event("2026-10", &at(LimitKind::CacheWrite, 79, 100), now()).is_none() + ); + match token_warning_event("2026-10", &at(LimitKind::CacheWrite, 85, 100), now()) { Some(EmailEvent::TokenWarning80 { limit_name, usage_pct, @@ -14105,7 +14261,11 @@ mod token_limit_tests { } _ => panic!("expected an 80% warning"), } - match token_warning_event("2026-10", &at(LimitKind::NewTokens, 3_000_000, 2_000_000)) { + match token_warning_event( + "2026-10", + &at(LimitKind::NewTokens, 3_000_000, 2_000_000), + now(), + ) { Some(EmailEvent::TokenLimitReached { limit_name, used_tokens, @@ -14121,6 +14281,7 @@ mod token_limit_tests { match token_warning_event( "2026-10", &at(LimitKind::Legacy { counts_cache: true }, 100, 100), + now(), ) { Some(EmailEvent::TokenLimitReached { limit_name, .. }) => { assert_eq!(limit_name, "token") diff --git a/services/worker/src/passes/recover.rs b/services/worker/src/passes/recover.rs index d4587ea3..f69b8890 100644 --- a/services/worker/src/passes/recover.rs +++ b/services/worker/src/passes/recover.rs @@ -99,6 +99,9 @@ pub enum Recovered { note: String, }, NeedsYou(NeedsYou), + /// CoderHelm's own problem, tried again with no luck: parked for the + /// self-heal sweep, with an internal alert (`run_recovery::Next::Park`). + Park, } /// A repair that worked: what it did, and a new base when it moved one. @@ -118,11 +121,18 @@ pub async fn recover( let mut ledger = store.ledger().await; match rr::next(c, &ledger, at.mark) { Next::NeedsYou(n) => { - store - .note(&format!("Stopped for a person: {} {}.", n.detail, n.action)) - .await; + // A pause on the token limit is no one's step: its one line. + let note = match &n.pause { + Some(p) => p.line.clone(), + None => format!("Stopped for a person: {} {}.", n.detail, n.action), + }; + store.note(¬e).await; Recovered::NeedsYou(n) } + Next::Park => { + store.note(&rr::own_problem_line(c)).await; + Recovered::Park + } Next::Retry { delay_secs } => { ledger.record(c, "retry", at.mark, at.now); store.save_ledger(&ledger).await; @@ -475,6 +485,10 @@ pub enum AfterError { /// Only a person can get past it: the caller stops the run for them /// ([`stop_for_person`]) unless a held draft takes the work. NeedsYou(NeedsYou), + /// CoderHelm's own problem, tried again with longer waits: the caller's + /// one ending parks it for the self-heal sweep (`fail_run`), never a + /// held draft and never a person's step. + Parked, /// Nothing done (the run already ended, or no step could be queued): /// the caller's one ending applies (`fail_run`, which reads the error /// the same way). @@ -526,6 +540,7 @@ pub async fn after_error( }; match recover(&github, &store, &c, &at).await { Recovered::NeedsYou(n) => AfterError::NeedsYou(n), + Recovered::Park => AfterError::Parked, Recovered::Resume { delay_secs, base, @@ -580,6 +595,11 @@ pub async fn stop_for_person( usage: &TokenUsage, duration: u64, ) { + // A pause on the token limit keeps the run's continuation: the limit's + // wake sends it, the same run from its checkpoint (`token_room`). + if needs.pause.is_some() { + keep_resume_message(state, msg, run_id).await; + } let delta = usage.unrecorded(); let failure = common::run_fail::RunFailure { cause: common::run_fail::Cause::NeedsYou { @@ -796,7 +816,15 @@ pub fn sweep_wants(item: &HashMap, version: &str) -> boo return false; } let ledger = Ledger::from_json(item_s(item, FIELD_LEDGER)); - !ledger.healed_at_version(version) && failed_run_error(item).kind.resumable() + if ledger.healed_at_version(version) { + return false; + } + let kind = failed_run_error(item).kind; + // CoderHelm's own problem is resumed only when this release parked it + // so (its kind kept as `unknown`): never an older failure brought back. + kind.resumable() + || (kind == rr::Kind::Unknown + && item_s(item, rr::FIELD_ERROR_KIND) == rr::Kind::Unknown.code()) } /// On deploy and every 15 minutes: every run left failed on an error that @@ -985,6 +1013,8 @@ async fn heal_one( stop_for_person(state, &msg, run_id, &n, &TokenUsage::default(), 0).await; Some(false) } + // Parked already, as it is: the next release's sweep tries again. + Recovered::Park => None, Recovered::Resume { delay_secs, base: new_base, @@ -1249,6 +1279,8 @@ pub(crate) mod replay { pub faults: VecDeque, pub steps: u32, pub stopped: Option, + /// Parked for the self-heal sweep: CoderHelm's own problem. + pub parked: bool, } fn http(code: &str, owner: &str, repo: &str, path: &str) -> String { @@ -1285,6 +1317,7 @@ pub(crate) mod replay { faults: VecDeque::new(), steps: 0, stopped: None, + parked: false, } } @@ -1479,6 +1512,10 @@ pub(crate) mod replay { self.stopped = Some(n); return false; } + Recovered::Park => { + self.parked = true; + return false; + } } } false diff --git a/services/worker/src/passes/run_wake.rs b/services/worker/src/passes/run_wake.rs index 9e0c5756..b8ead15a 100644 --- a/services/worker/src/passes/run_wake.rs +++ b/services/worker/src/passes/run_wake.rs @@ -42,12 +42,17 @@ fn n(item: &Item, k: &str) -> u64 { /// Most waiting runs one sweep starts again. const MAX_WOKEN: usize = 50; -/// The runs in `items` that wait on the usage limit, by team. +/// The runs in `items` that wait on the usage limit, by team: a wait on +/// the limit, a typed pause on the token limit, or a run an older release +/// stopped on a refused call as an unknown error (its stored words name +/// the refusal: `token_room::is_token_wait`). pub fn limit_waits(items: &[Item]) -> HashMap> { let mut out: HashMap> = HashMap::new(); for i in items { let wait = WaitingOn::of_item(i).unwrap_or_default(); - if run_wake::wakes_run(s(i, "status"), &wait.handback, Wake::Limit) { + if run_wake::wakes_run(s(i, "status"), &wait.handback, Wake::Limit) + || super::token_room::is_token_wait(i) + { out.entry(s(i, "team_id").to_string()).or_default().push(i); } } @@ -172,6 +177,17 @@ pub async fn wake_limit_waits(state: &WorkerState) -> usize { let mut started = 0; let mut full: HashSet = HashSet::new(); for (team, runs) in limit_waits(&items) { + // Runs waiting on the token limit resume in place, from their + // checkpoint: runs paused half way first, then new runs while room + // is left (`token_room::wake_team`). + let (token, other): (Vec<&Item>, Vec<&Item>) = runs + .into_iter() + .partition(|i| super::token_room::is_token_wait(i)); + started += super::token_room::wake_team(state, &team, &token).await; + if other.is_empty() { + continue; + } + let runs = other; if super::check_budget_exceeded(state, &team).await.is_some() { full.insert(team); continue; diff --git a/services/worker/src/passes/token_room.rs b/services/worker/src/passes/token_room.rs new file mode 100644 index 00000000..ec4b34df --- /dev/null +++ b/services/worker/src/passes/token_room.rs @@ -0,0 +1,422 @@ +//! The worker's side of `common::token_room`: runs the team's token limit +//! refused are paused with their checkpoint kept, new runs wait for room, +//! and both go on by themselves. +//! +//! - [`start_room`]: before a new run's first pass, what is left of the +//! month's limit after the runs in progress is compared with what a run +//! of its kind takes. When it is short the run waits ("Waiting for token +//! room") instead of starting and dying half way. +//! - [`pause`]: a run the limit refused (at its start, or mid-run) waits +//! on the limit with its continuation kept (`recover::keep_resume_message`): +//! the same run, from its checkpoint, plan and branch. +//! - [`wake_team`]: the limit's wake (`run_wake::wake_limit_waits`, from the +//! 15-minute sweep, the month's turn at 00:00 UTC on the 1st, and a saved +//! limit) starts the waiting runs in place, runs paused half way first, +//! new runs while room is left. Runs an older release stopped on the +//! limit as "an error it doesn't know how to repair" are found by their +//! stored words ([`is_token_wait`]) and go on the same way. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::run_wait::WaitingOn; +use common::token_room::{self as tr, Pause, PauseKind, RunUse, Waiting}; +use common::usage::UsageTotals; +use tracing::{info, warn}; + +use super::{add_progress_note, attr_s}; +use crate::models::{TicketMessage, TicketSource, TokenUsage, WorkerMessage}; +use crate::WorkerState; + +type Item = HashMap; + +/// Days of runs read for what a run takes and what the runs in progress +/// still need. +pub const HISTORY_DAYS: i64 = 30; + +/// Most waiting runs one wake starts. +pub const MAX_WOKEN: usize = 50; + +fn s<'a>(item: &'a Item, k: &str) -> &'a str { + item.get(k) + .and_then(|v| v.as_s().ok()) + .map(|x| x.as_str()) + .unwrap_or("") +} + +fn n(item: &Item, k: &str) -> u64 { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|x| x.parse::().ok()) + .map(|f| f.max(0.0) as u64) + .unwrap_or(0) +} + +/// The kind a run's estimate is read by: its ticket source. +pub fn kind_of(source: &TicketSource) -> &'static str { + match source { + TicketSource::Github => "github", + TicketSource::Jira => "jira", + TicketSource::Alert => "alert", + } +} + +/// What a run used so far, from its record. +pub fn used_of(item: &Item) -> UsageTotals { + UsageTotals { + tokens_in_uncached: n(item, "tokens_in"), + cache_read: n(item, "cache_read_tokens"), + cache_write: n(item, "cache_write_tokens"), + tokens_out: n(item, "tokens_out"), + } +} + +/// The pause a waiting run's record holds, if any. +pub fn pause_of(item: &Item) -> Option { + WaitingOn::of_item(item).and_then(|w| w.pause) +} + +/// Whether the run waits on the token limit (`token_room::waits_on_limit`). +pub fn is_token_wait(item: &Item) -> bool { + tr::waits_on_limit(item) +} + +/// One run's record as the estimate reads it. +pub fn run_use(item: &Item) -> RunUse { + let paused_mid_run = s(item, "status") == common::run_status::NEEDS_INPUT + && is_token_wait(item) + && pause_of(item).is_none_or(|p| p.mid_run()); + RunUse { + run_id: s(item, "run_id").to_string(), + kind: s(item, "ticket_source").to_string(), + status: s(item, "status").to_string(), + updated_at: s(item, "updated_at").to_string(), + used: used_of(item), + paused_mid_run, + } +} + +/// A waiting run as the wake reads it. +pub fn waiting_of(item: &Item) -> Waiting { + let wait = WaitingOn::of_item(item).unwrap_or_default(); + let mid_run = wait.pause.as_ref().is_none_or(Pause::mid_run); + let room_wait = wait + .pause + .as_ref() + .is_some_and(|p| p.kind == PauseKind::TokenRoom); + Waiting { + run_id: s(item, "run_id").to_string(), + kind: s(item, "ticket_source").to_string(), + mid_run, + room_wait, + since: if wait.since.is_empty() { + s(item, "updated_at").to_string() + } else { + wait.since + }, + used: used_of(item), + } +} + +/// The team's runs of the last [`HISTORY_DAYS`]. +pub async fn history(state: &WorkerState, team_id: &str) -> Vec { + let since = (chrono::Utc::now() - chrono::Duration::days(HISTORY_DAYS)).to_rfc3339(); + let filter = super::team_runs::Filter { + expr: "updated_at >= :since", + names: vec![ + ("#s", "status"), + ("#wo", common::run_wait::FIELD_WAITING_ON), + ], + values: vec![(":since", attr_s(&since))], + projection: Some( + "run_id, ticket_source, #s, updated_at, tokens_in, tokens_out, cache_read_tokens, \ + cache_write_tokens, #wo, error_message, error_detail", + ), + }; + match super::team_runs::of_team(state, team_id, &filter).await { + Ok(items) => items.iter().map(run_use).collect(), + Err(e) => { + warn!(team_id, error = %e, "Runs not read for the token room; nothing is held back"); + Vec::new() + } + } +} + +/// The month's counts and the team's limits. `None` when either can't be +/// read: nothing is held back on a failed read. +async fn limits_and_month( + state: &WorkerState, + team_id: &str, +) -> Option<(common::token_limits::TokenLimits, UsageTotals)> { + let limits = + common::token_limits::load(&state.dynamo, &state.config.settings_table_name, team_id) + .await + .ok()?; + let month = chrono::Utc::now().format("%Y-%m").to_string(); + let totals = common::token_limits::load_month_usage( + &state.dynamo, + &state.config.analytics_table_name, + team_id, + &month, + ) + .await + .ok()?; + Some((limits, totals)) +} + +/// Before a new run's first pass: the wait when what is left of the +/// month's limit, after what the runs in progress still need, is less than +/// a run of its kind takes. `None`: it starts. +pub async fn start_room(state: &WorkerState, msg: &TicketMessage, run_id: &str) -> Option { + let (limits, month) = limits_and_month(state, &msg.team_id).await?; + if limits.is_empty() { + return None; + } + let history = history(state, &msg.team_id).await; + let need = tr::estimate(&history, kind_of(&msg.source))?; + let reserve = tr::reserved(&history, &[run_id]); + tr::start_room(&limits, &month, &reserve, &need, chrono::Utc::now()) +} + +/// Before a costly step (the implement pass) of a run under way: the wait +/// when what is left of the month's limit is less than the rest of a run of +/// its kind. Pausing here, between steps, keeps the step whole instead of +/// meeting the limit half way through it. `None`: it goes on. +pub async fn step_room(state: &WorkerState, msg: &TicketMessage, run_id: &str) -> Option { + let (limits, month) = limits_and_month(state, &msg.team_id).await?; + if limits.is_empty() { + return None; + } + let history = history(state, &msg.team_id).await; + let need = tr::estimate(&history, kind_of(&msg.source))?; + let spent = history + .iter() + .find(|r| r.run_id == run_id) + .map(|r| r.used) + .unwrap_or_default(); + tr::step_room(&limits, &month, &need, &spent, chrono::Utc::now()) +} + +/// Pauses the run on the token limit: its continuation (the same run, from +/// its checkpoint, plan and branch) is kept for the wake, and the run waits +/// with its one line. Nothing is opened as a stopped draft and nobody is +/// asked to do anything. +pub async fn pause( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + needs: &common::run_recovery::NeedsYou, + usage: &TokenUsage, + duration: u64, +) { + // `stop_for_person` keeps the continuation for a pause. + super::recover::stop_for_person(state, msg, run_id, needs, usage, duration).await; + info!( + run_id, + line = needs.pause.as_ref().map_or("", |p| p.line.as_str()), + "Run paused on the token limit" + ); +} + +/// Starts the waiting run `item` in place: the same run, from its +/// checkpoint (its kept continuation, or one built from its record), after +/// one conditional write claims it so two wakes never send it twice. +pub async fn resume_in_place(state: &WorkerState, item: &Item, what: &str) -> bool { + let team_id = s(item, "team_id"); + let run_id = s(item, "run_id"); + let Some(resend) = super::recover::resend_for(item) else { + return false; + }; + let now = chrono::Utc::now(); + let stale = (now - chrono::Duration::minutes(tr::CLAIM_STALE_MINS)).to_rfc3339(); + let claimed = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #w = :now") + .condition_expression("#s = :waiting AND (attribute_not_exists(#w) OR #w < :stale)") + .expression_attribute_names("#s", "status") + .expression_attribute_names("#w", tr::FIELD_WOKEN_AT) + .expression_attribute_values(":now", attr_s(&now.to_rfc3339())) + .expression_attribute_values(":stale", attr_s(&stale)) + .expression_attribute_values(":waiting", attr_s(common::run_wake::WAITING)) + .send() + .await + .is_ok(); + if !claimed { + return false; + } + let body = match resend { + super::recover::Resend::Ticket(t) => serde_json::to_string(&WorkerMessage::Ticket(*t)).ok(), + super::recover::Resend::Resume { .. } => { + // A run with its pull request open goes back to waiting on its + // checks, where its resume picks it up. + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #s = :a, status_run_id = :sri") + .condition_expression("#s = :waiting") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":a", attr_s(common::run_status::AWAITING_CI)) + .expression_attribute_values( + ":sri", + common::run_ending::working(common::run_ending::Working::AwaitingCi, run_id) + .sri_attr(), + ) + .expression_attribute_values(":waiting", attr_s(common::run_wake::WAITING)) + .send() + .await; + Some( + serde_json::json!({ + "type": "resume", + "team_id": team_id, + "run_id": run_id, + "installation_id": n(item, "installation_id"), + }) + .to_string(), + ) + } + }; + let Some(body) = body else { + return false; + }; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .send() + .await + { + Ok(_) => { + add_progress_note( + state, + team_id, + run_id, + &format!("Resumed by itself when {what}: the run goes on from its checkpoint"), + ) + .await; + info!( + run_id, + what, "Run waiting on the token limit resumed in place" + ); + true + } + Err(e) => { + warn!(run_id, error = %e, "Could not send the paused run on; the next wake tries again"); + false + } + } +} + +/// What woke the team's runs, said on each run's page. +pub fn wake_reason(waiting: &[&Item], now: chrono::DateTime) -> &'static str { + let turned = waiting + .iter() + .filter_map(|i| pause_of(i)) + .any(|p| p.month_turned(now)); + if turned { + "the month turned and the token limit started again" + } else { + "the token limit allowed runs again" + } +} + +/// The team's runs waiting on the token limit that start now +/// ([`tr::plan_wakes`]), each resumed in place. Returns how many started. +pub async fn wake_team(state: &WorkerState, team_id: &str, waiting: &[&Item]) -> usize { + if waiting.is_empty() { + return 0; + } + let Some((limits, month)) = limits_and_month(state, team_id).await else { + return 0; + }; + let history = history(state, team_id).await; + let reads: Vec = waiting.iter().map(|i| waiting_of(i)).collect(); + let order = tr::plan_wakes(&limits, &month, &history, &reads, MAX_WOKEN); + let what = wake_reason(waiting, chrono::Utc::now()); + let mut started = 0; + for id in order { + if let Some(item) = waiting.iter().find(|i| s(i, "run_id") == id) { + if resume_in_place(state, item, what).await { + started += 1; + } + } + } + if started > 0 { + info!( + team_id, + started, what, "Runs waiting on the token limit resumed" + ); + } + started +} + +#[cfg(test)] +mod tests { + use super::*; + + fn item(pairs: &[(&str, &str)]) -> Item { + pairs + .iter() + .map(|(k, v)| (k.to_string(), attr_s(v))) + .collect() + } + + #[test] + fn a_run_an_older_release_stopped_on_the_limit_is_a_token_wait() { + let stuck = item(&[ + ("status", "needs_input"), + ( + "error_message", + "CoderHelm met an error it doesn't know how to repair, and stopped without trying \ + again: Monthly new tokens limit reached (40.3M of 40M). New model calls are \ + stopped until the month turns or an admin raises the limit in Settings, Token \ + Limit.", + ), + ]); + assert!(is_token_wait(&stuck)); + let w = waiting_of(&stuck); + assert!(w.mid_run, "it was stopped half way"); + // Another wait is not. + let other = item(&[ + ("status", "needs_input"), + ("error_message", "Review pull request #4"), + ]); + assert!(!is_token_wait(&other)); + // Not waiting any more. + let done = item(&[ + ("status", "completed"), + ( + "error_message", + "Monthly new tokens limit reached (1M of 1M).", + ), + ]); + assert!(!is_token_wait(&done)); + } + + #[test] + fn a_pause_on_the_record_says_its_kind() { + let now = chrono::Utc::now(); + let p = Pause::no_room("new tokens", 38, 40, 1, 3, now); + let wait = WaitingOn { + action: p.line.clone(), + handback: "usage_limit".into(), + pause: Some(p), + since: "2026-11-20T10:00:00Z".into(), + ..Default::default() + }; + let mut i = item(&[("status", "needs_input"), ("run_id", "01Q")]); + i.insert(common::run_wait::FIELD_WAITING_ON.into(), wait.to_attr()); + assert!(is_token_wait(&i)); + let w = waiting_of(&i); + assert!(!w.mid_run, "a new run waiting for room"); + assert_eq!(w.since, "2026-11-20T10:00:00Z"); + assert!(!run_use(&i).paused_mid_run); + } +} diff --git a/services/worker/src/passes/webhooks.rs b/services/worker/src/passes/webhooks.rs index 1e8e0306..7a2fa59f 100644 --- a/services/worker/src/passes/webhooks.rs +++ b/services/worker/src/passes/webhooks.rs @@ -67,8 +67,9 @@ pub fn run_data(item: &HashMap, status: &str, app: &str) // Waiting on a person: what for, by name (its question or action). "error": match status { "failed" => error, + // A pause says its one line, with when it resumes. "needs_input" => common::run_wait::WaitingOn::of_item(item) - .map(|w| w.line()) + .map(|w| w.pause.as_ref().map(|p| p.line.clone()).unwrap_or_else(|| w.line())) .or(error), _ => None, }, @@ -89,12 +90,24 @@ pub fn run_event_for(status: &str) -> Option<&'static str> { } } +/// The event for a run's record and the status just written: a run paused +/// on the token limit (its wait carries a pause) is `run.paused`, never +/// `run.needs_input`, which stays for waits a person ends. +pub fn run_event_of(item: &HashMap, status: &str) -> Option<&'static str> { + let paused = status == "needs_input" + && common::run_wait::WaitingOn::of_item(item).is_some_and(|w| w.pause.is_some()); + if paused { + return Some("run.paused"); + } + run_event_for(status) +} + /// Emits a `run.*` event for a run, read back from its record so every run /// event carries the same fields. `status` is what the work just wrote. pub async fn emit_run(state: &WorkerState, team_id: &str, run_id: &str, status: &str) { // The run's plan task follows its status (`common::plan_state`). super::plan_sync::on_run(state, team_id, run_id).await; - let Some(event_type) = run_event_for(status) else { + if run_event_for(status).is_none() { return; }; if state.config.webhook_queue_url.is_empty() { @@ -117,6 +130,9 @@ pub async fn emit_run(state: &WorkerState, team_id: &str, run_id: &str, status: let mut item = item; item.entry("run_id".into()) .or_insert_with(|| AttributeValue::S(run_id.into())); + let Some(event_type) = run_event_of(&item, status) else { + return; + }; let shown = if status == "success" { "completed" } else { @@ -578,6 +594,53 @@ mod tests { }) } + /// A run paused on the token limit sends `run.paused` with its one line; + /// `run.needs_input` stays for waits a person ends. + #[test] + fn a_pause_sends_run_paused_and_a_persons_wait_needs_input() { + let now = chrono::DateTime::parse_from_rfc3339("2026-11-30T21:10:00Z") + .unwrap() + .with_timezone(&chrono::Utc); + let p = common::token_room::Pause::limit_reached( + &common::token_room::Refusal { + limit: "new tokens".into(), + used: 40_300_000, + max: 40_000_000, + }, + now, + ); + let mut paused = item(&[("run_id", "01JBPAUSE"), ("title", "Show the cover image")]); + paused.insert( + common::run_wait::FIELD_WAITING_ON.into(), + common::run_wait::WaitingOn { + action: p.line.clone(), + detail: p.line.clone(), + handback: "usage_limit".into(), + pause: Some(p.clone()), + ..Default::default() + } + .to_attr(), + ); + assert_eq!(run_event_of(&paused, "needs_input"), Some("run.paused")); + let d = run_data(&paused, "needs_input", "https://app.example.com"); + assert!(conforms(&schema("run.paused"), &d), "{d}"); + assert_eq!(d["error"], p.line.as_str()); + // A person's wait keeps the old event. + let mut asked = item(&[("run_id", "01JBASK")]); + asked.insert( + common::run_wait::FIELD_WAITING_ON.into(), + common::run_wait::WaitingOn::review_pr( + 318, + "https://github.com/example-org/api/pull/318", + "a check is open", + ) + .unwrap() + .to_attr(), + ); + assert_eq!(run_event_of(&asked, "needs_input"), Some("run.needs_input")); + assert_eq!(run_event_of(&paused, "completed"), Some("run.completed")); + } + #[test] fn run_events_carry_the_documented_fields() { let rec = item(&[