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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -3559,6 +3559,16 @@
"null"
]
},
"github_wait": {
"description": "While the run waits for GitHub (its hourly limit, or a moment GitHub\nfailed to answer): when it goes on, in plain words. The run continues\nby itself; nothing is needed from anyone.",
"examples": [
"Waiting for GitHub's hourly limit to reset at 21:05 UTC; continues by itself"
],
"type": [
"string",
"null"
]
},
"lesson": {
"description": "A lesson recorded for the repository when the fix was elsewhere.",
"examples": [
Expand Down
1 change: 1 addition & 0 deletions docs/incidents.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ pipeline still calls it there.
| o. `o_mention_resumes_held_work` | A requester asked for five changes on a PR CoderHelm opened, and for no PR comments. The feedback round did all five, then the sandbox test step broke on CoderHelm's own setup, so the round was held and its WIP branch kept, with nothing about it on the run record. The next day the owner commented a bare `@coderhelm` to get the work landed. A bare mention was the re-review command, so CoderHelm posted a fresh verdict and nothing landed. | Work a round left held or unfinished on CoderHelm's own PR comes first. A held round stays on the run record (its WIP branch, where it started, what it was asked) until it lands, and a WIP branch ahead of the PR counts too. A bare mention resumes that round: the checks run again on the WIP with the current setup, and the work lands, or is fixed and then lands. Words are read by the model, told about the held work: "do it", "redo", "continue" and fix requests run a fix round on the held WIP, and only an ask for a review is a review. The person is told what CoderHelm is doing, on the run and the ticket when the requester asked for no PR comments. |
| p. `p_finished_work_loop` | A small ticket finished its 11 tasks, then spent 2.5 hours and $41.96 with no pull request: each 15-minute step re-ran the checks before the pull request from nothing and started fresh fix rounds. | The draft pull request opens before the proof check, the rules and the review, which then can't block it. A check runs once on a head and keeps its rounds across steps. A run with no real progress (tasks, the pull request, CI green, fewer findings) ends one way: a draft with Open items, waiting on a person. |
| q. `q_run_ceiling` | The same bug had been fixed in one loop at a time. | A run has an absolute ceiling on passes, continuations, worked time and spend that only a person's Retry renews, held at the worker's one entry point, at every model call, and by the stuck-run sweep, each without the others. |
| r. `r_github_limit` | A fix round hit GitHub's hourly limit. 29 writes and the diff came back "403 rate limit exceeded", and the run ended "the coder wrote no file ... That is CoderHelm's miss". | GitHub refusing for a while (its rate limit, a 5xx, no answer) never ends a run and is never blamed on the coder. The model is told the run pauses, the pass ends, and the run goes on as itself at GitHub's reset, with its page saying when. The wait adds no step and no pass. Writes GitHub rejected for a real reason are reported with that reason. A review waits for the reset without spending its retries. |

## Adding a case

Expand Down
212 changes: 212 additions & 0 deletions services/common/src/github_wait.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
//! A run that GitHub can't serve for a while waits, then goes on by itself.
//!
//! A ticket run once hit the installation's hourly GitHub limit in a fix
//! round: fifteen `batch_write` and fourteen `edit_file` calls came back
//! "403 ... API rate limit exceeded", the branch's diff couldn't be read
//! either, and the run ended "the coder wrote no file ... That is CoderHelm's
//! miss". The coder had written; GitHub had refused, for an hour.
//!
//! The rules:
//!
//! - GitHub refusing for a while (its rate limit, a 5xx, a dropped
//! connection) is never the coder's fault and never ends a run. The tool
//! call gets [`tool_result`], the pass ends, and the run is sent again with
//! an SQS delay until GitHub's reset ([`hop`] chains delays past the 900
//! seconds one message holds). It goes on from its checkpoint, plan and
//! branch, as the same run.
//! - The run page says [`waiting_text`] while it waits.
//! - The wait isn't work: it adds no step, no worked time and no pass to the
//! run's progress guard or its ceiling.
//! - [`MAX_WAITS`] bounds it: a GitHub that refuses through that many waits
//! ends the run with [`gave_up_reason`], which says it was GitHub.

use serde::{Deserialize, Serialize};

/// The longest delay one SQS message carries.
pub const MAX_HOP_SECS: u64 = 900;

/// Waits one run takes for GitHub before it stops (about eight hours of
/// hourly limits): far above a real limit, which resets within the hour.
pub const MAX_WAITS: u32 = 8;

/// Seconds added after GitHub's reset time, so the run starts after it.
pub const RESET_SLACK_SECS: u64 = 5;

/// Why GitHub can't be used right now.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum Cause {
/// The installation's rate limit (hourly, or a secondary limit).
#[default]
RateLimit,
/// GitHub failed for a moment: a 5xx, or no answer at all.
Outage,
}

/// A run waiting for GitHub, carried on the run's next message.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GitHubWait {
/// When the run may go on (epoch seconds). 0 when it isn't waiting.
#[serde(default)]
pub until: u64,
/// Waits this run took so far.
#[serde(default)]
pub waits: u32,
/// The pass the run was in when it paused: going on with it again is not
/// a new pass for the progress guard.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub pass: String,
#[serde(default)]
pub cause: Cause,
}

impl GitHubWait {
/// Nothing to carry: the run never waited.
pub fn is_idle(&self) -> bool {
self.until == 0 && self.waits == 0
}
}

/// [`GitHubWait::is_idle`] for a boxed field (serde passes the field).
#[allow(clippy::borrowed_box)]
pub fn is_idle_boxed(w: &Box<GitHubWait>) -> bool {
w.is_idle()
}

/// The delay of the next hop of a wait that ends at `until`, at `now`: None
/// once it is (about) over and the run should go on.
pub fn hop(until: u64, now: u64) -> Option<u64> {
let left = until.saturating_sub(now);
(left > RESET_SLACK_SECS).then(|| left.min(MAX_HOP_SECS))
}

/// When a wait of `wait_secs` from `now` ends, with the slack.
pub fn until(now: u64, wait_secs: u64) -> u64 {
now + wait_secs.max(1) + RESET_SLACK_SECS
}

/// `HH:MM UTC` of an epoch time.
pub fn clock(epoch: u64) -> String {
chrono::DateTime::from_timestamp(epoch as i64, 0)
.map(|t| t.format("%H:%M UTC").to_string())
.unwrap_or_else(|| "soon".to_string())
}

/// What the run page says while the run waits.
pub fn waiting_text(cause: Cause, until: u64) -> String {
match cause {
Cause::RateLimit => format!(
"Waiting for GitHub's hourly limit to reset at {}; continues by itself",
clock(until)
),
Cause::Outage => format!(
"Waiting for GitHub to answer again; tries at {} and continues by itself",
clock(until)
),
}
}

/// The tool result the model gets for a call GitHub refused this way, in
/// place of the raw error it would retry.
pub fn tool_result(cause: Cause, until: u64) -> String {
let what = match cause {
Cause::RateLimit => "GitHub's rate limit is reached",
Cause::Outage => "GitHub isn't answering right now",
};
format!(
"{what}; the run will pause and continue at {}. Do not retry this or any other call: \
nothing is wrong with your change, and the work so far is kept.",
clock(until)
)
}

/// What a tool call the loop didn't run (after GitHub refused an earlier one
/// in the same turn) returns.
pub fn not_run(cause: Cause, until: u64) -> String {
format!("Not run: {}", tool_result(cause, until))
}

/// Why a run stops when GitHub kept refusing through every wait. It names
/// GitHub, never the coder.
pub fn gave_up_reason(cause: Cause, waits: u32) -> String {
let what = match cause {
Cause::RateLimit => "GitHub's rate limit for this installation",
Cause::Outage => "GitHub failing to answer",
};
format!(
"Stopped after waiting {waits} times for {what}: GitHub refused the run's requests each \
time. Nothing was wrong with the work, which is kept on the branch. Retry goes on from \
it once GitHub is back."
)
}

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

#[test]
fn a_wait_past_one_delay_is_sent_on_in_hops() {
let now = 1_000_000;
let until = until(now, 3_000);
assert_eq!(until, now + 3_005);
let mut t = now;
let mut hops = Vec::new();
while let Some(h) = hop(until, t) {
assert!(h <= MAX_HOP_SECS);
hops.push(h);
t += h;
}
assert_eq!(hops, vec![900, 900, 900, 305]);
assert!(hop(until, t).is_none());
// A wait that is already over goes on at once.
assert!(hop(now, now + 1).is_none());
assert!(hop(now + 3, now).is_none(), "within the slack: go on");
}

#[test]
fn the_waiting_text_names_the_reset_in_plain_words() {
// 2026-11-06 21:05:00 UTC.
let reset = 1_793_999_100;
assert_eq!(clock(reset), "21:05 UTC");
assert_eq!(
waiting_text(Cause::RateLimit, reset),
"Waiting for GitHub's hourly limit to reset at 21:05 UTC; continues by itself"
);
assert!(waiting_text(Cause::Outage, reset).contains("continues by itself"));
}

#[test]
fn the_tool_result_tells_the_model_not_to_retry() {
let reset = 1_793_999_100;
let r = tool_result(Cause::RateLimit, reset);
assert!(r.starts_with(
"GitHub's rate limit is reached; the run will pause and continue at 21:05 UTC"
));
assert!(r.contains("Do not retry"));
assert!(!r.contains("403"));
assert!(not_run(Cause::RateLimit, reset).starts_with("Not run: GitHub's rate limit"));
}

#[test]
fn giving_up_names_github_never_the_coder() {
let r = gave_up_reason(Cause::RateLimit, MAX_WAITS);
assert!(r.contains("GitHub's rate limit"));
assert!(!r.contains("CoderHelm's miss"));
assert!(!r.to_lowercase().contains("coder wrote no file"));
}

#[test]
fn an_idle_wait_is_not_carried() {
assert!(GitHubWait::default().is_idle());
let w = GitHubWait {
until: 5,
waits: 1,
pass: "implement".into(),
cause: Cause::RateLimit,
};
let back: GitHubWait = serde_json::from_str(&serde_json::to_string(&w).unwrap()).unwrap();
assert_eq!(back, w);
let old: GitHubWait = serde_json::from_str("{}").unwrap();
assert!(old.is_idle());
}
}
1 change: 1 addition & 0 deletions services/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ pub mod notify;
pub mod e2e;
/// A team's branch, commit and PR title templates, and how they render.
pub mod git_conventions;
pub mod github_wait;
pub mod live;
/// Log findings and the fix runs started from them.
pub mod log_findings;
Expand Down
44 changes: 43 additions & 1 deletion services/common/src/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ impl WorkerMessage {
WorkerMessage::Ticket(t) => t
.continuation_run_id
.as_deref()
.filter(|r| !r.is_empty() && (t.continuation > 0 || t.model_retries > 0))
.filter(|r| !r.is_empty() && t.same_run())
.map(|r| (t.team_id.as_str(), r)),
WorkerMessage::Feedback(m) => Some((m.team_id.as_str(), m.run_id.as_str())),
WorkerMessage::Resume(m) => Some((m.team_id.as_str(), m.run_id.as_str())),
Expand Down Expand Up @@ -829,6 +829,11 @@ pub struct ReviewMessage {
/// one SQS delay allows, so it is sent on in hops until this reaches 0.
#[serde(default)]
pub wait_secs: u64,
/// How many times this review waited for GitHub's rate limit to reset.
/// Those waits don't spend `attempt`: the limit is GitHub's, not a
/// failure of the review.
#[serde(default, skip_serializing_if = "is_zero_u32")]
pub limit_waits: u32,
/// Set when CoderHelm's own reply on the PR concluded something the
/// standing formal verdict doesn't match; the review checks it.
#[serde(default)]
Expand Down Expand Up @@ -906,6 +911,14 @@ pub struct ResumeMessage {
/// Times this resume was sent again after a transient model error.
#[serde(default)]
pub model_retries: u32,
/// Set while this message waits for GitHub (its rate limit, or a moment
/// it failed to answer): sent on in hops until `until`, without spending
/// `model_retries` (see `github_wait`).
#[serde(
default,
skip_serializing_if = "crate::github_wait::GitHubWait::is_idle"
)]
pub github_wait: crate::github_wait::GitHubWait,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
Expand Down Expand Up @@ -960,6 +973,13 @@ pub struct TicketMessage {
/// The run keeps its run_id across these, like a continuation.
#[serde(default)]
pub model_retries: u32,
/// Set while the run waits for GitHub (its rate limit, or a moment it
/// failed to answer): sent on in hops until `until`, then the run goes on
/// as itself (see `github_wait`). The run keeps its run_id, like a
/// continuation, and the wait adds no step. Boxed: most tickets never
/// wait, and every queued message carries the field.
#[serde(default, skip_serializing_if = "crate::github_wait::is_idle_boxed")]
pub github_wait: Box<crate::github_wait::GitHubWait>,
/// What the tracker calls the ticket (a Jira issue type such as `Story`
/// or `Bug`, a GitHub issue type or its `bug`/`enhancement` label), when
/// it says. Triage weighs it with the ticket's text (see
Expand Down Expand Up @@ -1003,10 +1023,23 @@ pub struct TicketMessage {
pub new_run_id: Option<String>,
}

fn is_zero_u32(n: &u32) -> bool {
*n == 0
}

fn default_branch() -> String {
"main".to_string()
}

impl TicketMessage {
/// This message goes on with an existing run (`continuation_run_id`): a
/// continuation, a send after a transient model error, or after a wait
/// for GitHub.
pub fn same_run(&self) -> bool {
self.continuation > 0 || self.model_retries > 0 || self.github_wait.waits > 0
}
}

/// The issue type a Jira issue carries (`fields.issuetype.name`), when the
/// event has it.
pub fn ticket_type_of_jira(issue: &serde_json::Value) -> Option<String> {
Expand Down Expand Up @@ -1080,6 +1113,7 @@ impl Default for TicketMessage {
resume_from: None,
retry_of_run: false,
model_retries: 0,
github_wait: Default::default(),
ticket_type: None,
ticket_update_note: None,
ticket_history_note: None,
Expand Down Expand Up @@ -1127,6 +1161,14 @@ pub struct FeedbackMessage {
/// Times this feedback was sent again after a transient model error.
#[serde(default)]
pub model_retries: u32,
/// Set while this message waits for GitHub (its rate limit, or a moment
/// it failed to answer): sent on in hops until `until`, without spending
/// `model_retries` (see `github_wait`).
#[serde(
default,
skip_serializing_if = "crate::github_wait::GitHubWait::is_idle"
)]
pub github_wait: crate::github_wait::GitHubWait,
/// Steps this feedback round already used: each step has its own time
/// budget, and a round that runs out of it with work left continues in
/// the next step (see `run_round`).
Expand Down
8 changes: 8 additions & 0 deletions services/gateway/src/routes/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1091,6 +1091,13 @@ pub struct Run {
/// answered in time.
#[schema(example = json!(null))]
pub policy_note: Option<String>,
/// While the run waits for GitHub (its hourly limit, or a moment GitHub
/// failed to answer): when it goes on, in plain words. The run continues
/// by itself; nothing is needed from anyone.
#[schema(
example = "Waiting for GitHub's hourly limit to reset at 21:05 UTC; continues by itself"
)]
pub github_wait: Option<String>,
/// The approval card that timed out, when one did.
#[schema(example = json!(null))]
pub policy_approval: Option<String>,
Expand Down Expand Up @@ -1638,6 +1645,7 @@ fn run_of(
duration_s: num("duration_s"),
error: st("error_message"),
policy_note: st("policy_note"),
github_wait: st("github_wait"),
policy_approval: st("policy_approval").filter(|s| !s.is_empty()),
sign_in_prompts: item
.get("sign_in_prompts")
Expand Down
Loading
Loading