From d11980a5ca686dba12cee7b9bc9deba296f27cb5 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 6 Nov 2026 17:15:00 -0500 Subject: [PATCH] Runs wait out GitHub's limits instead of failing; refused writes are never "no file" A fix round hit the installation's hourly GitHub 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". The coder had written; GitHub refused. - GitHub client: outside_wait() tells GitHub refusing for a while (rate limit, a 5xx, no answer) from a real answer; a per-installation record says when GitHub refuses requests right now. GitHubPaused carries when the run goes on. - Tool loop: the first refused call gets "GitHub's rate limit is reached; the run will pause and continue at HH:MM UTC. Do not retry", later calls in the turn aren't run, and the pass ends with GitHubPaused. - Implement: write calls GitHub refused or rejected are recorded; the follow-up rounds that swallowed errors pass a pause on. - Empty-step check: refused writes (or an unreadable diff while GitHub refuses) are a wait; writes rejected for a real reason stop with that reason; only no write at all is "no write". An unread diff never says CoderHelm's miss. - Ticket runs: a GitHub pause sends the run again as itself at the reset, in hops of at most 900s, saying "Waiting for GitHub's hourly limit to reset at HH:MM UTC; continues by itself" on the run page. The wait adds no step, no continuation, no model retry, and re-entering the pass it interrupted is not a new pass for the guard. Bounded by 8 waits, then a stop that names GitHub. - Feedback and CI-fix rounds wait for GitHub the same way. - Reviews: a rate limit waits for the reset without spending an attempt and never ends in the gave-up note. - API: runs carry github_wait while waiting. --- docs/api/openapi.json | 10 + docs/incidents.md | 1 + services/common/src/github_wait.rs | 212 +++++++++++ services/common/src/lib.rs | 1 + services/common/src/messages.rs | 44 ++- services/gateway/src/routes/api.rs | 8 + services/worker/src/agent/anthropic.rs | 107 +++++- services/worker/src/clients/github.rs | 264 +++++++++++++- services/worker/src/main.rs | 4 + services/worker/src/models.rs | 2 + services/worker/src/passes/e2e.rs | 3 + services/worker/src/passes/e2e_attribution.rs | 1 + services/worker/src/passes/feedback.rs | 66 ++++ services/worker/src/passes/implement.rs | 33 ++ .../src/passes/incidents/a_whole_branch.rs | 3 + services/worker/src/passes/incidents/mod.rs | 1 + .../src/passes/incidents/q_run_ceiling.rs | 1 + .../src/passes/incidents/r_github_limit.rs | 161 +++++++++ services/worker/src/passes/log_autofix.rs | 1 + services/worker/src/passes/mod.rs | 340 +++++++++++++++++- services/worker/src/passes/resume.rs | 69 +++- services/worker/src/passes/review_eval.rs | 4 + services/worker/src/passes/review_pr.rs | 258 ++++++++++++- services/worker/src/passes/review_session.rs | 12 + services/worker/src/passes/review_sweep.rs | 1 + services/worker/src/passes/run_end.rs | 173 ++++++++- services/worker/src/passes/run_guard.rs | 33 ++ 27 files changed, 1771 insertions(+), 42 deletions(-) create mode 100644 services/common/src/github_wait.rs create mode 100644 services/worker/src/passes/incidents/r_github_limit.rs diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 2f56e906f..02e5f8851 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -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": [ diff --git a/docs/incidents.md b/docs/incidents.md index 397123934..4ad7bb968 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -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 diff --git a/services/common/src/github_wait.rs b/services/common/src/github_wait.rs new file mode 100644 index 000000000..6f07757dc --- /dev/null +++ b/services/common/src/github_wait.rs @@ -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) -> 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 { + 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()); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 9975e72a3..06ec0a378 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -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; diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 46058e2d1..82f476d41 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -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())), @@ -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)] @@ -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)] @@ -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, /// 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 @@ -1003,10 +1023,23 @@ pub struct TicketMessage { pub new_run_id: Option, } +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 { @@ -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, @@ -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`). diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 15716207b..0fdf05322 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -1091,6 +1091,13 @@ pub struct Run { /// answered in time. #[schema(example = json!(null))] pub policy_note: Option, + /// 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, /// The approval card that timed out, when one did. #[schema(example = json!(null))] pub policy_approval: Option, @@ -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") diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index fa7cb82fe..fc581befe 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -888,7 +888,20 @@ pub async fn converse_tool_loop( // Execute tools, each only after the policy gate allows it. let mut tool_results: Vec = Vec::new(); + // Set once GitHub refused a call for a while (its rate limit, a + // 5xx): the calls after it in this turn aren't run, and the loop + // ends after this turn so the run can wait (`common::github_wait`). + let mut paused: Option = None; for (tool_id, tool_name, tool_input) in &tool_uses { + if let Some(p) = &paused { + tool_results.push(json!({ + "type": "tool_result", + "tool_use_id": tool_id, + "content": common::github_wait::not_run(p.cause, p.until), + "is_error": true + })); + continue; + } let tool_start = std::time::Instant::now(); info!(tool = %tool_name, "Executing tool"); @@ -943,10 +956,27 @@ pub async fn converse_tool_loop( cb(tool_name, duration_ms, &input_summary, true); } warn!(tool = %tool_name, error = %e, duration_ms, "Tool execution failed"); + // GitHub refusing for a while is not an answer to retry: + // the model is told the run pauses, and the loop ends. + let content = match crate::clients::github::outside_wait(&*e) { + Some((cause, wait)) => { + let p = crate::clients::github::GitHubPaused::after(cause, wait); + warn!( + tool = %tool_name, + until = p.until, + ?cause, + "github_paused: GitHub refused a tool call; the pass ends and the run waits" + ); + let text = common::github_wait::tool_result(p.cause, p.until); + paused = Some(p); + text + } + None => format!("Error: {e}"), + }; tool_results.push(json!({ "type": "tool_result", "tool_use_id": tool_id, - "content": format!("Error: {e}"), + "content": content, "is_error": true })); } @@ -992,6 +1022,9 @@ pub async fn converse_tool_loop( } messages.push(("user".to_string(), tool_results)); + if let Some(p) = paused { + return Err(Box::new(p)); + } } } @@ -1668,6 +1701,78 @@ mod accounting_tests { } } + /// Every call is refused the way GitHub refused the incident's writes. + struct Limited(std::sync::atomic::AtomicUsize); + + #[async_trait::async_trait] + impl super::super::llm::ToolExecutor for Limited { + async fn execute( + &self, + _name: &str, + _input: &Value, + ) -> Result> { + self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Err("HTTP status client error (403 Forbidden) for url \ + (https://api.github.com/repos/o/r/git/trees): API rate limit exceeded for \ + installation ID 1." + .into()) + } + } + + /// A tool call GitHub refused for its limit ends the loop with a pause + /// (no more model turns, no more calls), and the model's last tool + /// result says the run continues at the reset, not the raw 403. + #[tokio::test] + async fn a_rate_limited_tool_call_ends_the_loop_with_a_pause() { + let (url, bodies) = server(vec![tool_turn(0, 100), answer_turn(0, 0)]).await; + let (meter, _) = UsageMeter::memory("team-1"); + let client = AnthropicClient::new("k".into(), meter).at(&url); + let tools = crate::passes::review_agent::review_tools(); + let gate = common::agent_policy::Gate::new( + Arc::new(common::agent_policy::store::MemStore::new()), + common::agent_policy::GateCtx::new("t", common::agent_policy::Agent::Reviewer), + ) + .offering(tools.iter().map(|t| t.name.clone())); + let mut messages = vec![( + "user".to_string(), + vec![json!({"type":"text","text":"fix it"})], + )]; + let ex = Limited(Default::default()); + let mut usage = TokenUsage::default(); + let out = converse_tool_loop( + &client, + "claude-opus-5-5", + "You write code.", + &mut messages, + &tools, + &ex, + &gate, + &mut usage, + 10, + 1024, + None, + None, + None, + None, + ) + .await; + let err = out.expect_err("the loop pauses"); + let paused = err + .downcast_ref::() + .expect("a typed pause"); + assert_eq!(paused.cause, common::github_wait::Cause::RateLimit); + assert_eq!(ex.0.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!(bodies.lock().unwrap().len(), 1, "no model turn after it"); + let last = &messages.last().unwrap().1[0]; + let said = last["content"].as_str().unwrap(); + assert!( + said.starts_with("GitHub's rate limit is reached; the run will pause and continue at"), + "{said}" + ); + assert!(said.contains("Do not retry")); + assert!(!said.contains("403")); + } + async fn run_loop( client: &AnthropicClient, tools: &[ToolDefinition], diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index bde189ad8..f9e770c24 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -216,6 +216,168 @@ pub fn rate_limited(e: &(dyn std::error::Error + Send + Sync + 'static)) -> Opti .then_some(60) } +/// GitHub can't be used for a while (`common::github_wait`): the pass stops +/// here and the run waits until `until`, then goes on by itself. Never a +/// failure of the work, and never the coder's. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GitHubPaused { + pub cause: common::github_wait::Cause, + /// When the run may go on (epoch seconds). + pub until: u64, +} + +impl GitHubPaused { + /// A wait of `wait_secs` from now. + pub fn after(cause: common::github_wait::Cause, wait_secs: u64) -> Self { + Self { + cause, + until: common::github_wait::until(GitHubClient::now_epoch(), wait_secs), + } + } +} + +impl std::fmt::Display for GitHubPaused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&common::github_wait::waiting_text(self.cause, self.until)) + } +} + +impl std::error::Error for GitHubPaused {} + +/// Seconds a moment of GitHub failing (a 5xx, no answer) waits before the +/// run tries again. +pub const OUTAGE_WAIT_SECS: u64 = 60; + +/// Whether a request to `url` went to GitHub's API. +fn is_github_url(url: &str) -> bool { + url.starts_with(API_BASE) || url.contains("://api.github.com/") +} + +/// Whether this error is GitHub refusing for a while, and how long to wait: +/// its rate limit (primary or secondary), a 5xx from its API, or its API not +/// answering (timeout, refused or reset connection). Anything else (a 404, a +/// 422, a 403 for a permission) is a real answer and None. Walks the error's +/// sources, and reads the status line of errors that lost their type. +pub fn outside_wait( + e: &(dyn std::error::Error + 'static), +) -> Option<(common::github_wait::Cause, u64)> { + use common::github_wait::Cause; + let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(e); + while let Some(err) = cur { + if let Some(p) = err.downcast_ref::() { + let left = p.until.saturating_sub(GitHubClient::now_epoch()); + return Some((p.cause, left.max(1))); + } + if let Some(r) = err.downcast_ref::() { + return Some((Cause::RateLimit, r.wait_secs)); + } + if let Some(r) = err.downcast_ref::() { + let github = r.url().is_some_and(|u| is_github_url(u.as_str())); + let transient = r.is_timeout() || r.is_connect() || r.is_request() || r.is_body(); + if github && transient { + return Some((Cause::Outage, OUTAGE_WAIT_SECS)); + } + if github && r.status().is_some_and(|s| s.is_server_error()) { + return Some((Cause::Outage, OUTAGE_WAIT_SECS)); + } + } + cur = err.source(); + } + let m = e.to_string(); + if m.contains("(429 Too Many Requests)") + || (m.contains("(403 Forbidden)") && m.to_ascii_lowercase().contains("rate limit")) + { + return Some((Cause::RateLimit, 60)); + } + outage_in_text(&m).then_some((Cause::Outage, OUTAGE_WAIT_SECS)) +} + +/// A 5xx from GitHub's API, as `status_error_message` writes it. +fn outage_in_text(m: &str) -> bool { + m.contains("HTTP status server error (5") && m.contains("api.github.com") +} + +/// Until when each installation's GitHub is known to refuse requests (epoch +/// seconds), and why, in this process: its rate limit (every request made +/// while it holds fails), or a 5xx or no answer a moment ago. A decision +/// that reads GitHub's failures as answers ("no file on the branch") checks +/// this first and waits instead. +static LIMITED: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| Mutex::new(HashMap::new())); + +/// Until when a response says the installation is limited: a 429, or a 403 +/// with no requests left (until the reset) or a `retry-after`. +fn limited_until_from( + status: u16, + retry_after: Option<&str>, + remaining: Option<&str>, + reset: Option<&str>, + now: u64, +) -> Option { + let spent = remaining.map(str::trim) == Some("0"); + let after = retry_after.and_then(|s| s.trim().parse::().ok()); + let limited = status == 429 || (status == 403 && (spent || after.is_some())); + if !limited { + return None; + } + let until_reset = reset + .and_then(|s| s.trim().parse::().ok()) + .filter(|_| spent); + Some(after.map(|a| now + a).or(until_reset).unwrap_or(now + 60)) +} + +fn note_limited(installation_id: u64, headers: &reqwest::header::HeaderMap, status: u16) { + let h = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()); + let now = GitHubClient::now_epoch(); + if let Some(until) = limited_until_from( + status, + h("retry-after"), + h("x-ratelimit-remaining"), + h("x-ratelimit-reset"), + now, + ) { + mark_limited(installation_id, until); + } else if (500..=599).contains(&status) { + mark_outside( + installation_id, + common::github_wait::Cause::Outage, + now + OUTAGE_WAIT_SECS, + ); + } +} + +/// Records that the installation is rate limited until `until` (epoch +/// seconds). +pub fn mark_limited(installation_id: u64, until: u64) { + mark_outside( + installation_id, + common::github_wait::Cause::RateLimit, + until, + ); +} + +/// Records that GitHub refuses the installation's requests until `until`. +/// A rate limit is never shortened by a later, shorter outage. +pub fn mark_outside(installation_id: u64, cause: common::github_wait::Cause, until: u64) { + if let Ok(mut m) = LIMITED.lock() { + let now = GitHubClient::now_epoch(); + let e = m + .entry(installation_id) + .or_insert((0, common::github_wait::Cause::Outage)); + if e.0 <= now || until > e.0 { + *e = (until, cause); + } + } +} + +/// Why GitHub refuses the installation's requests right now and for how +/// many more seconds, when it does. +pub fn outside_for(installation_id: u64) -> Option<(common::github_wait::Cause, u64)> { + let (until, cause) = *LIMITED.lock().ok()?.get(&installation_id)?; + let now = GitHubClient::now_epoch(); + (until > now).then(|| (cause, until - now)) +} + fn status_error_message(status: reqwest::StatusCode, url: &str, body: &str) -> String { let kind = if status.is_client_error() { "client" @@ -581,11 +743,31 @@ impl GitHubClient { &self, req: reqwest::RequestBuilder, ) -> Result { - let resp = req.send().await?; + let resp = match req.send().await { + Ok(r) => r, + Err(e) => { + // GitHub not answering at all is a moment it can't be used. + if e.is_timeout() || e.is_connect() { + mark_outside( + self.installation_id, + common::github_wait::Cause::Outage, + Self::now_epoch() + OUTAGE_WAIT_SECS, + ); + } + return Err(e); + } + }; observe_budget(self.installation_id, resp.headers()); + note_limited(self.installation_id, resp.headers(), resp.status().as_u16()); Ok(resp) } + /// GitHub refusing this installation's requests right now: why, and until + /// when the run waits (see [`outside_for`]). + pub fn outside(&self) -> Option { + outside_for(self.installation_id).map(|(cause, secs)| GitHubPaused::after(cause, secs)) + } + /// How long background reads should wait for the installation's budget /// to refill (see [`background_wait`]); None while there is headroom. pub fn background_wait(&self) -> Option { @@ -4689,6 +4871,86 @@ mod status_error_tests { assert!(m.contains("Line could not be resolved")); } + /// The incident: every write came back "403 ... API rate limit + /// exceeded". That is GitHub's limit, a wait until its reset; a 5xx is a + /// short wait; a real refusal (permission, unprocessable) is not a wait. + #[test] + fn github_refusing_for_a_while_is_told_apart_from_a_real_answer() { + use common::github_wait::Cause; + let limited: Box = Box::new(RateLimited { + wait_secs: 1_700, + message: "HTTP status client error (403 Forbidden) for url \ + (https://api.github.com/repos/o/r/git/trees): API rate limit exceeded" + .into(), + }); + assert_eq!(outside_wait(&*limited), Some((Cause::RateLimit, 1_700))); + // The same, after something turned it into text. + let text: Box = limited.to_string().into(); + assert_eq!(outside_wait(&*text).map(|w| w.0), Some(Cause::RateLimit)); + let bad_gateway: Box = status_error_message( + reqwest::StatusCode::BAD_GATEWAY, + "https://api.github.com/repos/o/r/compare/main...x", + "", + ) + .into(); + assert_eq!( + outside_wait(&*bad_gateway), + Some((Cause::Outage, OUTAGE_WAIT_SECS)) + ); + for real in [ + status_error_message( + reqwest::StatusCode::FORBIDDEN, + "https://api.github.com/repos/o/r/contents/a", + "Resource not accessible by integration", + ), + status_error_message( + reqwest::StatusCode::UNPROCESSABLE_ENTITY, + "https://api.github.com/repos/o/r/git/refs", + "Reference update failed", + ), + "Missing path".to_string(), + ] { + let e: Box = real.clone().into(); + assert_eq!(outside_wait(&*e), None, "{real}"); + } + // A paused pass's error says when it goes on, plainly. + let paused: Box = + Box::new(GitHubPaused::after(Cause::RateLimit, 600)); + let (cause, left) = outside_wait(&*paused).unwrap(); + assert_eq!(cause, Cause::RateLimit); + assert!((600..=606).contains(&left), "{left}"); + assert!(paused + .to_string() + .starts_with("Waiting for GitHub's hourly limit to reset at ")); + } + + #[test] + fn a_limited_installation_is_known_until_its_reset() { + let now = 10_000; + assert_eq!( + limited_until_from(403, None, Some("0"), Some("12000"), now), + Some(12_000) + ); + assert_eq!( + limited_until_from(403, Some("90"), Some("40"), None, now), + Some(10_090), + "a secondary limit" + ); + assert_eq!(limited_until_from(429, None, None, None, now), Some(10_060)); + assert_eq!(limited_until_from(403, None, Some("12"), None, now), None); + assert_eq!( + limited_until_from(200, None, Some("0"), Some("12000"), now), + None + ); + let inst = 555_000_111; + assert_eq!(outside_for(inst), None); + mark_limited(inst, GitHubClient::now_epoch() + 300); + assert!(outside_for(inst) + .is_some_and(|(c, s)| c == common::github_wait::Cause::RateLimit && s <= 300)); + mark_limited(inst + 1, GitHubClient::now_epoch().saturating_sub(5)); + assert_eq!(outside_for(inst + 1), None, "a reset in the past is over"); + } + #[test] fn empty_body_keeps_the_status_line() { let m = status_error_message(reqwest::StatusCode::BAD_GATEWAY, "u", " "); diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 08800aa87..9dd3f8449 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -331,6 +331,10 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) // A transient model failure is sent again later by the one // requeue policy; only a real failure marks the run failed. let err: &(dyn std::error::Error + 'static) = &*e; + // GitHub refusing for a while: wait for its reset. + if passes::feedback::wait_for_github(&state, &retry_msg, err).await { + return; + } if common::model_retry::is_transient_model_error(err) && passes::feedback::requeue_after_model_error(&state, &retry_msg).await { diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index 1bf5e43db..7d8e6fb2e 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -295,6 +295,7 @@ mod tests { #[test] fn ticket_message_roundtrip() { let msg = WorkerMessage::Ticket(TicketMessage { + github_wait: Default::default(), team_id: "TEAM#1".into(), installation_id: 1, source: TicketSource::Github, @@ -331,6 +332,7 @@ mod tests { #[test] fn feedback_message_roundtrip() { let msg = WorkerMessage::Feedback(FeedbackMessage { + github_wait: Default::default(), team_id: "TEAM#1".into(), installation_id: 1, run_id: "run1".into(), diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index b6616c7d3..ddf8821b3 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -849,6 +849,7 @@ async fn own_pr_failures( url = run.url, ); let fb = FeedbackMessage { + github_wait: Default::default(), team_id: msg.team_id.clone(), installation_id: msg.installation_id, run_id, @@ -1610,6 +1611,7 @@ async fn start_fix_ticket( runs = BURN_IN_RUNS, ); let ticket = TicketMessage { + github_wait: Default::default(), team_id: msg.team_id.clone(), installation_id: msg.installation_id, source: TicketSource::Alert, @@ -1862,6 +1864,7 @@ pub async fn act(state: &WorkerState, a: TestAction) -> Result<(), Err> { base = if rec.evidence.iter().any(|e| e.kind == "bug_ticket") { " and fails on the code from before the bug fix" } else { "" }, ); let ticket = TicketMessage { + github_wait: Default::default(), team_id: a.team_id.clone(), installation_id, source: TicketSource::Alert, diff --git a/services/worker/src/passes/e2e_attribution.rs b/services/worker/src/passes/e2e_attribution.rs index 3fe463a17..78245b47d 100644 --- a/services/worker/src/passes/e2e_attribution.rs +++ b/services/worker/src/passes/e2e_attribution.rs @@ -441,6 +441,7 @@ async fn start_fix( } let original = format!("{}/{}#{pr}", msg.repo_owner, msg.repo_name); let ticket = TicketMessage { + github_wait: Default::default(), team_id: msg.team_id.clone(), installation_id: msg.installation_id, source: TicketSource::Alert, diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index b2b6d28b8..5a5a6fc8e 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -19,6 +19,14 @@ pub async fn run( let start = std::time::Instant::now(); let mut usage = TokenUsage::default(); + // Feedback waiting for GitHub is sent on in hops until its reset. + let now = chrono::Utc::now().timestamp().max(0) as u64; + if let Some(hop) = common::github_wait::hop(msg.github_wait.until, now) { + if send_feedback_message(state, &msg, hop).await { + return Ok(()); + } + } + // Load team's Anthropic API key (required), gated for this run. let provider = ModelProvider::load_for_team( &state.dynamo, @@ -240,6 +248,7 @@ pub async fn run( if !branch.is_empty() && may_update { // The run's ticket, so the merge commit carries its real key. let ticket_msg = crate::models::TicketMessage { + github_wait: Default::default(), team_id: msg.team_id.clone(), installation_id: msg.installation_id, source: if ticket.2 > 0 { @@ -1658,6 +1667,62 @@ Rules: Ok(()) } +/// Feedback GitHub refused for a while (its rate limit, a 5xx, no answer) is +/// sent again once GitHub's reset passes, in hops, without spending a model +/// retry (`common::github_wait`). False when the error isn't GitHub's or +/// every wait is taken. +pub(crate) async fn wait_for_github( + state: &WorkerState, + msg: &FeedbackMessage, + e: &(dyn std::error::Error + 'static), +) -> bool { + let Some((cause, wait)) = crate::clients::github::outside_wait(e) else { + return false; + }; + if msg.github_wait.waits >= common::github_wait::MAX_WAITS { + return false; + } + let now = chrono::Utc::now().timestamp().max(0) as u64; + let until = common::github_wait::until(now, wait); + let mut next = msg.clone(); + next.github_wait = common::github_wait::GitHubWait { + until, + waits: msg.github_wait.waits + 1, + pass: String::new(), + cause, + }; + let first = + common::github_wait::hop(until, now).unwrap_or(common::github_wait::RESET_SLACK_SECS + 1); + if !send_feedback_message(state, &next, first).await { + return false; + } + let text = common::github_wait::waiting_text(cause, until); + warn!(run_id = %msg.run_id, until, "github_wait: the feedback round waits for GitHub"); + super::add_progress_note(state, &msg.team_id, &msg.run_id, &text).await; + true +} + +/// Sends this feedback message, as it is, to the feedback queue after +/// `delay` seconds (at most one SQS delay). +async fn send_feedback_message(state: &WorkerState, msg: &FeedbackMessage, delay: u64) -> bool { + if state.config.feedback_queue_url.is_empty() { + return false; + } + let Ok(body) = serde_json::to_string(&WorkerMessage::Feedback(msg.clone())) else { + return false; + }; + state + .sqs + .send_message() + .queue_url(&state.config.feedback_queue_url) + .message_body(body) + .delay_seconds(delay.min(common::github_wait::MAX_HOP_SECS) as i32) + .send() + .await + .map_err(|e| warn!(run_id = %msg.run_id, error = %e, "Could not send the feedback on")) + .is_ok() +} + /// Sends feedback again after a transient model error, per /// [`common::model_retry::requeue_delay`]. False once the policy is spent. pub(crate) async fn requeue_after_model_error(state: &WorkerState, msg: &FeedbackMessage) -> bool { @@ -2890,6 +2955,7 @@ async fn handle_wrong_repo( // Send new ticket message to re-trigger in the correct repo let ticket_msg = WorkerMessage::Ticket(crate::models::TicketMessage { + github_wait: Default::default(), team_id: msg.team_id.clone(), installation_id: msg.installation_id, source, diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 0bbe35769..476b1ef70 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -130,6 +130,9 @@ pub struct ImplementResult { pub conversation_log: Vec, /// What the pass could read, looked up, and wrote as its evidence. pub evidence: super::proof::RunEvidence, + /// The writes GitHub refused or rejected: a pass that wrote no file + /// because GitHub refused it did write (see `run_end`). + pub writes: super::run_end::Writes, } #[allow(clippy::too_many_arguments)] @@ -699,6 +702,7 @@ pub async fn run( branch: branch.to_string(), base_branch: msg.base_branch.clone(), files_modified: std::sync::Mutex::new(HashSet::new()), + writes: Default::default(), task_tracker: &task_tracker, file_cache, state, @@ -936,6 +940,10 @@ pub async fn run( ) .await { + // GitHub refusing for a while ends the pass: the run waits. + if crate::clients::github::outside_wait(&*e).is_some() { + return Err(e); + } warn!(error = %e, "Test-remediation pass errored — proceeding with current state"); } if let Some(s) = &skills { @@ -1009,6 +1017,9 @@ pub async fn run( ) .await { + if crate::clients::github::outside_wait(&*e).is_some() { + return Err(e); + } warn!(error = %e, "Migration-registration pass errored — proceeding with current state"); } if let Some(s) = &skills { @@ -1060,10 +1071,12 @@ pub async fn run( .unwrap() .clone(); let ci_gates = super::checks::kinds_from(&ci); + let writes = std::mem::take(&mut *executor.write_executor.writes.lock().unwrap()); Ok(ImplementResult { files_modified: files, timed_out, conversation_log: conv_log, + writes, evidence: super::proof::RunEvidence { sources, lookups, @@ -1529,6 +1542,8 @@ struct WriteToolExecutor<'a> { branch: String, base_branch: String, files_modified: std::sync::Mutex>, + /// Write calls GitHub refused for a while or rejected (see `run_end`). + writes: std::sync::Mutex, task_tracker: &'a TaskTracker, file_cache: &'a FileCache, /// Worker state + the code graph (shared with every agent that reads @@ -1608,6 +1623,16 @@ impl<'a> ToolExecutor for WriteToolExecutor<'a> { ) -> Result> { let out = self.execute_tool(name, input).await; if let Err(e) = &out { + if is_write_tool(name) { + let mut w = self.writes.lock().unwrap(); + match crate::clients::github::outside_wait(&**e) { + Some((cause, wait)) => { + let p = crate::clients::github::GitHubPaused::after(cause, wait); + w.refuse(p.cause, p.until); + } + None => w.reject(&tool_write_paths(input).join(", "), &e.to_string()), + } + } // A write refused as stale must leave NO stale copy behind: the // client already dropped its snapshot, and the pass cache goes too, // so the re-read the error asks for sees live content (it used to @@ -1624,6 +1649,14 @@ impl<'a> ToolExecutor for WriteToolExecutor<'a> { } } +/// The tools that write to the branch. +fn is_write_tool(name: &str) -> bool { + matches!( + name, + "write_file" | "edit_file" | "batch_write" | "restore_file" + ) +} + /// True for the write refusals that mean "your copy of the file is stale". fn is_stale_write_error(msg: &str) -> bool { msg.contains("branch advanced upstream") || msg.contains("changed concurrently") diff --git a/services/worker/src/passes/incidents/a_whole_branch.rs b/services/worker/src/passes/incidents/a_whole_branch.rs index 96fdfa43e..5817118fa 100644 --- a/services/worker/src/passes/incidents/a_whole_branch.rs +++ b/services/worker/src/passes/incidents/a_whole_branch.rs @@ -28,6 +28,8 @@ fn last_step_writes_nothing(gh: &FakeGitHub, coder_notes: &str, ticket: &str) -> &tasks, &run_end::coder_questions(coder_notes), run_end::ticket_names_files(ticket), + &run_end::Writes::default(), + None, ) { Empty::Carry(files) => { end.said(format!( @@ -50,6 +52,7 @@ fn last_step_writes_nothing(gh: &FakeGitHub, coder_notes: &str, ticket: &str) -> end.said(format!("{OLD} for this issue.")); end.status = common::run_status::NEEDS_INPUT.into(); } + other => panic!("nothing was refused here: {other:?}"), } end } diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index e05ae4e62..adb80bbe0 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -32,3 +32,4 @@ mod n_suite_setup_broke; mod o_mention_resumes_held_work; mod p_finished_work_loop; mod q_run_ceiling; +mod r_github_limit; diff --git a/services/worker/src/passes/incidents/q_run_ceiling.rs b/services/worker/src/passes/incidents/q_run_ceiling.rs index daa9d4f5f..ddd7c3295 100644 --- a/services/worker/src/passes/incidents/q_run_ceiling.rs +++ b/services/worker/src/passes/incidents/q_run_ceiling.rs @@ -41,6 +41,7 @@ fn run_messages() -> Vec<(&'static str, WorkerMessage)> { ..Default::default() }; let resume = ResumeMessage { + github_wait: Default::default(), team_id: TEAM.into(), run_id: RUN.into(), installation_id: 1, diff --git a/services/worker/src/passes/incidents/r_github_limit.rs b/services/worker/src/passes/incidents/r_github_limit.rs new file mode 100644 index 000000000..6039567b1 --- /dev/null +++ b/services/worker/src/passes/incidents/r_github_limit.rs @@ -0,0 +1,161 @@ +//! r. A fix round after red sandbox checks hit the installation's hourly +//! GitHub limit around 20:05 UTC: fifteen `batch_write` and fourteen +//! `edit_file` calls came back "403 ... API rate limit exceeded", the diff +//! and the plan check's compare failed the same way, and the run ended +//! "Orchestration failed": "Stopped without a pull request: the coder wrote +//! no file (and GitHub couldn't show the branch's diff) ... That is +//! CoderHelm's miss". +//! +//! Guarantee: GitHub refusing for a while never ends a run and is never +//! blamed on the coder. The first refused call tells the model the run +//! pauses (not the raw 403), the pass ends, and the run is sent again as +//! itself at GitHub's reset, in hops of at most one SQS delay. Its page +//! says when it goes on. The wait adds no step and no pass, and the run +//! goes on from its checkpoint, plan and branch. + +use super::fixture::*; +use crate::clients::github::{self, GitHubPaused}; +use crate::models::TicketMessage; +use crate::passes::plan_coverage; +use crate::passes::run_end::{self, Empty, Writes}; +use common::github_wait::{self as gw, Cause}; + +const OLD: &str = "That is CoderHelm's miss"; +const RUN: &str = "01RUNLIMIT"; + +/// The reset the 403s named: 2026-11-06 21:05:00 UTC. +const RESET: u64 = 1_793_999_100; +/// When the round hit the limit: 20:05:00. +const HIT: u64 = RESET - 3_600; + +fn refused_write() -> Box { + "HTTP status client error (403 Forbidden) for url \ + (https://api.github.com/repos/acme/site/git/trees): API rate limit exceeded for \ + installation ID 41." + .into() +} + +#[test] +fn a_rate_limited_round_waits_for_the_reset_and_goes_on_as_itself() { + let mut end = Ending { + status: "running".into(), + ..Default::default() + }; + // The model's view of the first refused write: the pause, never the 403. + let (cause, _) = github::outside_wait(&*refused_write()).expect("GitHub's limit"); + assert_eq!(cause, Cause::RateLimit); + let told = gw::tool_result(cause, RESET); + assert!(told.contains("Do not retry")); + assert!(!told.contains("403")); + + // Had the pass gone on to the empty-step check anyway: 29 refused + // writes and an unreadable diff are a wait, not "no file". + let mut writes = Writes::default(); + for _ in 0..29 { + writes.refuse(Cause::RateLimit, RESET); + } + let tasks = plan_coverage::plan_tasks(&plan_tasks_md()); + let verdict = run_end::judge(None, &tasks, &[], true, &writes, None); + assert_eq!(verdict, Empty::Wait(Cause::RateLimit, RESET)); + + // The run waits: the same run, the same step, one wait, the pass it + // was in. + let first = TicketMessage { + team_id: "TEAM#1".into(), + ticket_id: TICKET.into(), + continuation: 2, + continuation_run_id: Some(RUN.into()), + ..Default::default() + }; + let paused = GitHubPaused { + cause, + until: RESET, + }; + let (next, hop) = + crate::passes::github_wait_message(&first, RUN, &paused, "implement", HIT).unwrap(); + assert_eq!(next.continuation, 2, "a wait is not a step"); + assert_eq!(next.model_retries, 0, "nor a model retry"); + assert_eq!(next.continuation_run_id.as_deref(), Some(RUN)); + assert_eq!(next.github_wait.waits, 1); + assert_eq!(next.github_wait.pass, "implement"); + assert!(next.same_run()); + end.said(gw::waiting_text(cause, RESET)); + + // Sent on in hops of at most one SQS delay until the reset. + let mut t = HIT + hop; + let mut hops = 1; + while let Some(h) = gw::hop(next.github_wait.until, t) { + assert!(h <= gw::MAX_HOP_SECS); + t += h; + hops += 1; + } + assert_eq!(hops, 4, "an hour is four hops"); + assert!(t >= RESET - gw::RESET_SLACK_SECS); + + // It goes on as itself: the entry guard knows its run, and entering the + // pass it was in is not a new pass. + let as_worker = common::messages::WorkerMessage::Ticket(next.clone()); + assert_eq!(as_worker.run_ref(), Some(("TEAM#1", RUN))); + crate::passes::run_guard::forgive_reentry(RUN, "implement"); + assert!(crate::passes::run_guard::take_reentry(RUN, "implement")); + assert!( + !crate::passes::run_guard::take_reentry(RUN, "implement"), + "only once" + ); + + assert!( + end.says("Waiting for GitHub's hourly limit to reset at 21:05 UTC; continues by itself") + ); + end.never_says(OLD); + end.never_says("the coder wrote no file"); + end.never_says("Orchestration failed"); + assert_eq!(end.status, "running"); +} + +/// The pipeline's own places: the tool loop ends on a refusal, the rounds +/// that swallow errors pass the pause on, the empty-step check waits, and a +/// run's error is a wait before it is a failure. +#[test] +fn the_pipeline_pauses_at_each_place_github_can_refuse() { + let anthropic = include_str!("../../agent/anthropic.rs"); + let lp = fn_src(anthropic, "pub async fn converse_tool_loop("); + assert!(lp.contains("crate::clients::github::outside_wait(&*e)")); + assert!(lp.contains("return Err(Box::new(p));")); + + let implement = include_str!("../implement.rs"); + assert_eq!( + implement + .matches("if crate::clients::github::outside_wait(&*e).is_some() {") + .count(), + 2, + "the remediation rounds don't swallow a pause" + ); + + let rp = run_passes_src(); + let judge = rp.find("let mut verdict = run_end::judge(").unwrap(); + assert!(rp[..judge].contains("let outside = github.outside()")); + assert!(rp.contains("run_end::Empty::Wait(cause, until) => {")); + + let src = include_str!("../mod.rs"); + let orch = &src[src.find("\npub async fn orchestrate_ticket(").unwrap()..]; + let orch = &orch[..orch.find("\nfn run_origin_agent(").unwrap()]; + let pause = orch + .find("github_pause_of(&*e, msg.installation_id)") + .unwrap(); + let wait = orch + .find("wait_for_github(state, &msg, &run_id, p, &mut usage)") + .unwrap(); + let fail = orch + .find("fail_run(state, &msg, &run_id, &sanitized") + .unwrap(); + assert!( + pause < wait && wait < fail, + "a wait comes before any failure" + ); + // The wait is no step: it never goes through the continuation. + let w = fn_src(src, "async fn wait_for_github("); + assert!(!w.contains("try_auto_continue(")); + assert!(!w.contains("next_message(")); + assert!(w.contains("steps::mark_queued(")); + assert!(w.contains("steps::step_number(msg.continuation)")); +} diff --git a/services/worker/src/passes/log_autofix.rs b/services/worker/src/passes/log_autofix.rs index 32bf210d4..3709c81d1 100644 --- a/services/worker/src/passes/log_autofix.rs +++ b/services/worker/src/passes/log_autofix.rs @@ -97,6 +97,7 @@ impl StartEnv for WorkerEnv<'_> { ) .await?; let msg = WorkerMessage::Ticket(TicketMessage { + github_wait: Default::default(), team_id: team_id.to_string(), installation_id, source: TicketSource::Alert, diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 700796427..0ab8e6e38 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -112,6 +112,187 @@ async fn requeue_after_model_error(state: &WorkerState, msg: &TicketMessage, run } } +/// Sends this ticket message again after `delay` seconds (at most one SQS +/// delay). +async fn send_ticket_after(state: &WorkerState, msg: &TicketMessage, delay: u64) -> bool { + if state.config.ticket_queue_url.is_empty() { + return false; + } + let Ok(body) = serde_json::to_string(&crate::models::WorkerMessage::Ticket(msg.clone())) else { + return false; + }; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .delay_seconds(delay.min(common::github_wait::MAX_HOP_SECS) as i32) + .send() + .await + { + Ok(_) => true, + Err(e) => { + warn!(error = %e, "Could not send the ticket message on"); + false + } + } +} + +/// The GitHub wait a run's error calls for, if any: the error is GitHub +/// refusing for a while (its rate limit, a 5xx, no answer), or GitHub is +/// refusing this installation right now and the error came from a read or +/// write that failed under it. A stop by a person, the policy or the run +/// guard is never a wait. +fn github_pause_of( + e: &(dyn std::error::Error + Send + Sync + 'static), + installation_id: u64, +) -> Option { + use crate::clients::github::{outside_for, outside_wait, GitHubPaused}; + if let Some((cause, wait)) = outside_wait(e) { + return Some(GitHubPaused::after(cause, wait)); + } + let stopped = e + .downcast_ref::() + .is_some() + || e.downcast_ref::().is_some() + || e.downcast_ref::().is_some() + || is_budget_exhausted(&e.to_string()) + || e.to_string().contains("cancelled by user"); + if stopped { + return None; + } + outside_for(installation_id).map(|(cause, secs)| GitHubPaused::after(cause, secs)) +} + +/// The message that carries a run's wait for GitHub, and its first SQS +/// delay: the same run (its run_id and step), one more wait, the pass it was +/// in. None once the run has waited `MAX_WAITS` times. +pub(crate) fn github_wait_message( + msg: &TicketMessage, + run_id: &str, + paused: &crate::clients::github::GitHubPaused, + pass: &str, + now: u64, +) -> Option<(TicketMessage, u64)> { + if msg.github_wait.waits >= common::github_wait::MAX_WAITS { + return None; + } + let mut next = msg.clone(); + next.continuation_run_id = Some(run_id.to_string()); + next.github_wait = Box::new(common::github_wait::GitHubWait { + until: paused.until, + waits: msg.github_wait.waits + 1, + pass: pass.to_string(), + cause: paused.cause, + }); + // At least a moment, even for a reset that already passed. + let first = common::github_wait::hop(paused.until, now) + .unwrap_or(common::github_wait::RESET_SLACK_SECS + 1); + Some((next, first)) +} + +/// What a run's wait for GitHub came to. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum GitHubWaited { + /// No wait: the error wasn't GitHub's. + No, + /// The run waits; its next message is queued. + Queued, + /// GitHub's, but the run can't wait (every wait taken, or the queue + /// refused): it stops with this reason, which names GitHub. + Stopped(String), +} + +/// The run waits for GitHub: its next message is queued for GitHub's reset, +/// the run page says so, and this step's tokens are recorded. The wait adds +/// no step, no pass and no worked time; the step's checkpoint, the plan and +/// the branch are what the run goes on from. +async fn wait_for_github( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + paused: &crate::clients::github::GitHubPaused, + usage: &mut TokenUsage, +) -> GitHubWaited { + let current = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("current_pass") + .send() + .await + .ok() + .and_then(|o| { + o.item() + .and_then(|i| i.get("current_pass").and_then(|v| v.as_s().ok()).cloned()) + }) + .unwrap_or_default(); + let now = chrono::Utc::now().timestamp().max(0) as u64; + let Some((next, first)) = github_wait_message(msg, run_id, paused, ¤t, now) else { + return GitHubWaited::Stopped(common::github_wait::gave_up_reason( + paused.cause, + msg.github_wait.waits, + )); + }; + if !send_ticket_after(state, &next, first).await { + return GitHubWaited::Stopped(format!( + "{}, but the run couldn't be queued to wait. Nothing was wrong with the work, which \ + is kept on the branch: Retry goes on from it.", + common::github_wait::waiting_text(paused.cause, paused.until) + .split(';') + .next() + .unwrap_or("Waiting for GitHub") + )); + } + let text = common::github_wait::waiting_text(paused.cause, paused.until); + warn!( + run_id, + until = paused.until, + waits = next.github_wait.waits, + cause = ?paused.cause, + "github_wait: the run waits for GitHub and goes on by itself" + ); + let delta = usage.unrecorded(); + let wrote = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET github_wait = :w, updated_at = :t, \ + tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c", + ) + .expression_attribute_names("#s", "status") + .condition_expression(common::run_status::not_ended("#s")) + .ended_values() + .usage_values(&delta) + .expression_attribute_values(":w", attr_s(&text)) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await + .is_ok(); + if wrote { + usage.mark_recorded(&delta); + } + add_progress_note(state, &msg.team_id, run_id, &text).await; + // Last write: the stuck-run sweep reads a queued time after the last + // update as "a step is waiting", not stuck. The step number is the same: + // a wait is not a step. + steps::mark_queued( + state, + &msg.team_id, + run_id, + steps::step_number(msg.continuation), + ) + .await; + GitHubWaited::Queued +} + /// What asking for the next step came to. #[derive(Debug, Clone, PartialEq)] pub(crate) enum Handoff { @@ -403,6 +584,61 @@ mod continuation_tests { assert!(!is_budget_exhausted("GitHub API 404: issue not found")); } + /// A run's error is a wait for GitHub when GitHub refused it for a + /// while, or when GitHub refuses the installation right now; a stop by + /// the guard, a person or the step budget never is. + #[test] + fn a_run_error_is_a_wait_for_github_only_when_github_refused() { + use super::{github_pause_of, github_wait_message, GitHubWaited}; + use crate::clients::github::{mark_limited, GitHubPaused}; + use common::github_wait::{Cause, MAX_WAITS}; + let limited: Box = + "HTTP status client error (403 Forbidden) for url \ + (https://api.github.com/repos/o/r/compare/main...x): API rate limit exceeded" + .into(); + let p = github_pause_of(&*limited, 888_000_001).expect("a wait"); + assert_eq!(p.cause, Cause::RateLimit); + let real: Box = + "No files modified in o/r, and its plan names no file to change.".into(); + assert_eq!(github_pause_of(&*real, 888_000_002), None); + // Any failure while GitHub refuses this installation is read as that. + let now = chrono::Utc::now().timestamp() as u64; + mark_limited(888_000_003, now + 1_200); + let under = github_pause_of(&*real, 888_000_003).expect("GitHub is refusing"); + assert!(under.until >= now + 1_200); + // Never a stop that isn't GitHub's. + let stopped: Box = + Box::new(super::run_guard::LoopStopped("handed to you".into())); + assert_eq!(github_pause_of(&*stopped, 888_000_003), None); + let steps: Box = + "Reached the maximum number of steps (60) without finishing.".into(); + assert_eq!(github_pause_of(&*steps, 888_000_003), None); + + // The wait's message is the same run and step; the waits are bounded. + let mut msg = crate::models::TicketMessage { + team_id: "T".into(), + ..Default::default() + }; + let paused = GitHubPaused { + cause: Cause::RateLimit, + until: 10_000, + }; + let (next, hop) = github_wait_message(&msg, "R", &paused, "implement", 9_000).unwrap(); + assert_eq!(hop, 900); + assert_eq!(next.continuation, 0); + assert_eq!(next.continuation_run_id.as_deref(), Some("R")); + assert!( + next.same_run(), + "the first wait of a first step is the same run" + ); + // A reset already past still goes on after a moment, never at once. + let (_, hop) = github_wait_message(&msg, "R", &paused, "implement", 10_500).unwrap(); + assert!(hop > 0); + msg.github_wait.waits = MAX_WAITS; + assert!(github_wait_message(&msg, "R", &paused, "implement", 9_000).is_none()); + assert_ne!(GitHubWaited::Queued, GitHubWaited::No); + } + fn run_passes_src() -> &'static str { let src = include_str!("mod.rs"); let start = src.find("\nasync fn run_passes(").unwrap(); @@ -935,7 +1171,7 @@ pub async fn orchestrate_ticket( ) -> Result<(), Box> { // A continuation reuses its original run_id (so it's ONE run, not a // duplicate); a fresh ticket mints a new one. - let is_continuation = (msg.continuation > 0 || msg.model_retries > 0) + let is_continuation = msg.same_run() && msg .continuation_run_id .as_deref() @@ -956,6 +1192,31 @@ pub async fn orchestrate_ticket( let mut usage = TokenUsage::default(); let start = std::time::Instant::now(); + // A run waiting for GitHub longer than one SQS delay is sent on in hops; + // a hop touches nothing on the run (see `common::github_wait`). + if is_continuation { + let now = chrono::Utc::now().timestamp().max(0) as u64; + if let Some(hop) = common::github_wait::hop(msg.github_wait.until, now) { + if send_ticket_after(state, &msg, hop).await { + info!( + run_id, + hop, + until = msg.github_wait.until, + "Still waiting for GitHub" + ); + return Ok(()); + } + warn!( + run_id, + "Could not send the GitHub wait on; the run goes on now" + ); + } + // Going on with the pass the wait interrupted is not a new pass. + if msg.github_wait.waits > 0 && !msg.github_wait.pass.is_empty() { + run_guard::forgive_reentry(&run_id, &msg.github_wait.pass); + } + } + info!(run_id, ticket_id = %msg.ticket_id, continuation = msg.continuation, "Orchestration started"); // Dedup only FRESH runs — a continuation legitimately reuses its own run_id @@ -1050,7 +1311,6 @@ pub async fn orchestrate_ticket( // The team's counters already have these tokens: each model // call is counted as it happens (common::usage). } else { - error!(run_id, error = %e, "Orchestration failed"); let checkpoint = load_checkpoint(state, &msg.team_id, &run_id).await; // The run guard fired: one ending, always (see `run_guard`). let guard_ended = run_guard::end_if_stopped( @@ -1060,6 +1320,22 @@ pub async fn orchestrate_ticket( checkpoint.as_ref().map(|c| c.1.as_str()), ) .await; + // GitHub refused the run for a while (its rate limit, a 5xx, + // no answer): never a failure and never the coder's. The run + // waits until GitHub's reset and goes on by itself, from its + // checkpoint, plan and branch (`common::github_wait`). + let paused = (!guard_ended) + .then(|| github_pause_of(&*e, msg.installation_id)) + .flatten(); + let waited = match &paused { + Some(p) => wait_for_github(state, &msg, &run_id, p, &mut usage).await, + None => GitHubWaited::No, + }; + if let GitHubWaited::No = waited { + error!(run_id, error = %e, "Orchestration failed"); + } else { + info!(run_id, error = %e, waited = ?waited, "Orchestration paused for GitHub"); + } // Budget exhausted (hit the step limit) with committed partial // work is "needs more turns", not a real failure — auto-continue // (bounded) from the branch instead of salvaging a half-finished @@ -1071,6 +1347,7 @@ pub async fn orchestrate_ticket( // stays correct even if a future non-implement pass propagates the // same step-limit message — it won't match this checkpoint. let continued = !guard_ended + && paused.is_none() && is_budget_exhausted(&err_msg) && try_auto_continue( state, @@ -1089,6 +1366,7 @@ pub async fn orchestrate_ticket( // the one requeue policy every pass uses. Decided from the // error's kind, never its text. let continued = continued + || paused.is_some() || !guard_ended && { let err: &(dyn std::error::Error + 'static) = &*e; common::model_retry::is_transient_model_error(err) @@ -1152,6 +1430,11 @@ pub async fn orchestrate_ticket( let sanitized = sanitize_error(&err_msg); fail_run(state, &msg, &run_id, &sanitized, &usage, duration).await; } + // A wait that couldn't be taken still names GitHub, never the + // coder. + if let GitHubWaited::Stopped(reason) = &waited { + fail_run(state, &msg, &run_id, reason, &usage, duration).await; + } // `?` failure paths inside run_passes bypass close_memory — // release the repo's memory lock so the next run isn't // stateless for the lock's full 15-minute TTL. @@ -1327,7 +1610,7 @@ async fn run_passes( // resumes in the repository planning settled on, from its last plan. It // first checks that the step before made progress: a new plan revision // or fewer open gaps; two steps in a row without stop the run. - let plan_resume = if msg.continuation > 0 || msg.model_retries > 0 { + let plan_resume = if msg.same_run() { let st = steps::load(state, &msg.team_id, run_id).await; let resume = st.planning(); let step = steps::step_number(msg.continuation); @@ -1784,7 +2067,7 @@ async fn run_passes( return Ok(()); } pr_holder::Claim::Free(guards) => { - if msg.continuation == 0 && msg.model_retries == 0 { + if !msg.same_run() { add_progress_note( state, &msg.team_id, @@ -1874,7 +2157,7 @@ async fn run_passes( // work on the branch was made against them. Triaging and planning again // gave a different plan (memory and history read differently a few // minutes later) for a branch built on the first one. - let same_run = msg.continuation > 0 || msg.model_retries > 0; + let same_run = msg.same_run(); // A person's Retry of an earlier run (`resume_from`) takes up that // run's plan the same way, and keeps the commits on its branch (below); // the plan becomes this run's own, so a continuation of this run reuses @@ -3259,6 +3542,7 @@ async fn run_passes( files_modified, timed_out: false, conversation_log: vec![], + writes: Default::default(), // The first attempt's lookups weren't kept; the proof check's // fix round can make them again. evidence: proof::RunEvidence { @@ -3335,7 +3619,7 @@ async fn run_passes( return Ok(()); } pr_holder::Claim::Free(guards) => { - if msg.continuation == 0 && msg.model_retries == 0 { + if !msg.same_run() { add_progress_note( state, &msg.team_id, @@ -4629,11 +4913,16 @@ async fn run_passes( .await; let ticket_names_files = run_end::ticket_names_files(&format!("{}\n{}", msg.title, msg.body)); + // Writes GitHub refused for a while, or GitHub refusing right + // now, are a wait: never "the coder wrote no file". + let outside = github.outside().map(|p| (p.cause, p.until)); let mut verdict = run_end::judge( work.as_deref(), &tasks, &run_end::coder_questions(&result.evidence.notes), ticket_names_files, + &result.writes, + outside, ); // Nothing on the branch, and the plan says what to build: one // more build, told every task, before anything is asked. @@ -4669,11 +4958,14 @@ async fn run_passes( if again.files_modified.is_empty() { let mut evidence = std::mem::take(&mut result.evidence); evidence.merge(again.evidence); + result.writes.merge(again.writes); verdict = run_end::judge( work.as_deref(), &tasks, &run_end::coder_questions(&evidence.notes), ticket_names_files, + &result.writes, + github.outside().map(|p| (p.cause, p.until)), ); result.evidence = evidence; } else { @@ -4763,10 +5055,19 @@ async fn run_passes( close_memory(state, agent_memory.take()).await; return Ok(()); } - run_end::Empty::Unbuilt(reason) => { + run_end::Empty::Unbuilt(reason) | run_end::Empty::Rejected(reason) => { close_memory(state, agent_memory.take()).await; return Err(reason.into()); } + // GitHub refused the writes (or the diff) for a while: the + // run waits and goes on by itself (`orchestrate_ticket`). + run_end::Empty::Wait(cause, until) => { + close_memory(state, agent_memory.take()).await; + return Err(Box::new(crate::clients::github::GitHubPaused { + cause, + until, + })); + } run_end::Empty::Generic => {} } } @@ -6374,11 +6675,25 @@ async fn run_repo_pipeline( let tasks = plan_coverage::tasks_for(github, repo_owner, repo_name, branch_name, &repo_plan.tasks) .await; - match run_end::judge(work.as_deref(), &tasks, &[], false) { + let outside = github.outside().map(|p| (p.cause, p.until)); + match run_end::judge( + work.as_deref(), + &tasks, + &[], + false, + &impl_result.writes, + outside, + ) { run_end::Empty::Carry(files) => impl_result.files_modified = files, - run_end::Empty::Unbuilt(reason) => { + run_end::Empty::Unbuilt(reason) | run_end::Empty::Rejected(reason) => { return Err(format!("{repo_owner}/{repo_name}: {reason}").into()) } + run_end::Empty::Wait(cause, until) => { + return Err(Box::new(crate::clients::github::GitHubPaused { + cause, + until, + })) + } _ => { return Err(format!( "No files modified in {repo_owner}/{repo_name}, and its plan names no file to change." @@ -6921,7 +7236,7 @@ async fn resume_run_to_running(state: &WorkerState, team_id: &str, run_id: &str) .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 = :r, status_run_id = :sri, updated_at = :t") + .update_expression("SET #s = :r, status_run_id = :sri, updated_at = :t REMOVE github_wait") // Nor a run the guard stopped: a step already queued doesn't undo it. .condition_expression(format!( "attribute_exists(run_id) AND attribute_not_exists(guard_open) AND {}", @@ -7137,6 +7452,11 @@ pub(crate) async fn update_pass( Some(("current_pass = :p", ":p", attr_s(pass))), ) .await?; + // Going on with the pass a wait for GitHub interrupted is not a new pass + // (the wait is GitHub's, not the run's): only the guard's stop holds. + if run_guard::take_reentry(run_id, pass) { + return run_guard::check(state, team_id, run_id).await; + } // Every pass goes through here, so a pass added later is counted too. run_guard::on_pass(state, team_id, run_id).await } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 5d1fdd359..e3b2f0f69 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -919,6 +919,14 @@ pub async fn run( ) -> Result<(), Box> { let start = std::time::Instant::now(); + // A round waiting for GitHub is sent on in hops until its reset. + let now = chrono::Utc::now().timestamp().max(0) as u64; + if let Some(hop) = common::github_wait::hop(msg.github_wait.until, now) { + if send_resume_message(state, &msg, hop).await { + return Ok(()); + } + } + // Load run record info!(run_id = %msg.run_id, table = %state.config.runs_table_name, "Loading run record"); let run_record = match state @@ -2165,7 +2173,9 @@ pub async fn run( .await; } Err(e) => { - if requeue_after_model_error(state, &msg, &*e).await { + if wait_for_github(state, &msg, &*e).await + || requeue_after_model_error(state, &msg, &*e).await + { return Ok(()); } error!(run_id = msg.run_id, error = %e, "CI fix implementation failed — the PR stays open, the round is named as not finished"); @@ -2958,6 +2968,7 @@ async fn fix_context( // Build a minimal TicketMessage for the implement/review passes let ticket_msg = TicketMessage { + github_wait: Default::default(), team_id: msg.team_id.clone(), installation_id: msg.installation_id, source: TicketSource::Github, @@ -5113,6 +5124,62 @@ async fn end_run( Ok(()) } +/// A fix round GitHub refused for a while (its rate limit, a 5xx, no +/// answer) is sent again once GitHub's reset passes, in hops, without +/// spending a model retry or a CI poll (`common::github_wait`). False when +/// the error isn't GitHub's or every wait is taken. +async fn wait_for_github( + state: &WorkerState, + msg: &ResumeMessage, + e: &(dyn std::error::Error + 'static), +) -> bool { + let Some((cause, wait)) = crate::clients::github::outside_wait(e) else { + return false; + }; + if msg.github_wait.waits >= common::github_wait::MAX_WAITS { + return false; + } + let now = chrono::Utc::now().timestamp().max(0) as u64; + let until = common::github_wait::until(now, wait); + let mut next = msg.clone(); + next.github_wait = common::github_wait::GitHubWait { + until, + waits: msg.github_wait.waits + 1, + pass: String::new(), + cause, + }; + let first = + common::github_wait::hop(until, now).unwrap_or(common::github_wait::RESET_SLACK_SECS + 1); + if !send_resume_message(state, &next, first).await { + return false; + } + let text = common::github_wait::waiting_text(cause, until); + warn!(run_id = %msg.run_id, until, "github_wait: the fix round waits for GitHub"); + super::add_progress_note(state, &msg.team_id, &msg.run_id, &text).await; + true +} + +/// Sends this resume message, as it is, to the CI fix queue after `delay` +/// seconds (at most one SQS delay). +async fn send_resume_message(state: &WorkerState, msg: &ResumeMessage, delay: u64) -> bool { + if state.config.ci_fix_queue_url.is_empty() { + return false; + } + let Ok(body) = serde_json::to_string(&crate::models::WorkerMessage::Resume(msg.clone())) else { + return false; + }; + state + .sqs + .send_message() + .queue_url(&state.config.ci_fix_queue_url) + .message_body(body) + .delay_seconds(delay.min(common::github_wait::MAX_HOP_SECS) as i32) + .send() + .await + .map_err(|e| warn!(run_id = %msg.run_id, error = %e, "Could not send the resume on")) + .is_ok() +} + /// A fix that failed on a transient model error is sent again later (the /// one requeue policy, [`common::model_retry::requeue_delay`]) instead of /// completing the run with the fix unapplied. False when the error isn't diff --git a/services/worker/src/passes/review_eval.rs b/services/worker/src/passes/review_eval.rs index 6124c66b5..2a10d60e1 100644 --- a/services/worker/src/passes/review_eval.rs +++ b/services/worker/src/passes/review_eval.rs @@ -360,6 +360,7 @@ impl Sim { fn job(&self, head: &str, dedup_key: &str) -> ReviewMessage { ReviewMessage { + limit_waits: 0, team_id: "T".into(), installation_id: 1, repo_owner: "acme".into(), @@ -616,6 +617,9 @@ impl Sim { updated_at: ts(sim.now), }); } + FailurePlan::WaitForLimit { .. } | FailurePlan::LimitOutlasted => { + unreachable!("a service error never waits for GitHub's limit") + } FailurePlan::GiveUp => { sim.failure = Some(FailureNote { head_sha: head.clone(), diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 780fc51ef..0c0546df5 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -237,8 +237,19 @@ pub(crate) enum FailurePlan { Retry { delay_secs: u64 }, /// Every retry failed: tell the PR, keep the previous verdict. GiveUp, + /// GitHub's rate limit: send the job again once it resets, in this many + /// seconds. Spends no attempt. + WaitForLimit { delay_secs: u64 }, + /// GitHub's limit held through every wait: the job ends without a note + /// on the PR (nothing failed on CoderHelm's side); the next push or a + /// re-review asks again. + LimitOutlasted, } +/// Waits for GitHub's rate limit one review job takes (a day of hourly +/// limits) before it ends quietly. +pub(crate) const MAX_LIMIT_WAITS: u32 = 24; + /// The plan for a review that failed on run `attempt` (0 = the first run). pub(crate) fn failure_plan(attempt: u32) -> FailurePlan { match common::model_retry::requeue_delay(attempt) { @@ -247,6 +258,78 @@ pub(crate) fn failure_plan(attempt: u32) -> FailurePlan { } } +/// The plan for a review that failed, given whether GitHub's rate limit was +/// the cause (`limit_wait`: seconds until it resets). A rate limit waits for +/// the reset and never spends an attempt; anything else follows +/// [`failure_plan`]. +pub(crate) fn failure_plan_for(msg: &ReviewMessage, limit_wait: Option) -> FailurePlan { + match limit_wait { + Some(_) if msg.limit_waits >= MAX_LIMIT_WAITS => FailurePlan::LimitOutlasted, + Some(wait) => FailurePlan::WaitForLimit { + delay_secs: wait.max(1) + common::github_wait::RESET_SLACK_SECS, + }, + None => failure_plan(msg.attempt), + } +} + +/// How long GitHub's rate limit holds for this failed review, when it was +/// the cause: the error says so, or the installation is limited right now. +pub(crate) fn limit_wait_of( + e: &(dyn std::error::Error + Send + Sync + 'static), + installation_id: u64, +) -> Option { + use crate::clients::github; + use common::github_wait::Cause; + match github::outside_wait(e) { + Some((Cause::RateLimit, wait)) => Some(wait), + Some((Cause::Outage, _)) => None, + None => github::outside_for(installation_id) + .filter(|(c, _)| *c == Cause::RateLimit) + .map(|(_, secs)| secs), + } +} + +/// The trigger's own dedup key, without any retry's or wait's prefix. +fn base_dedup_key(msg: &ReviewMessage, reviewed_head: &str) -> String { + let mut key = msg.dedup_key.as_str(); + loop { + let rest = key + .strip_prefix("retry#") + .or_else(|| key.strip_prefix("limit#")); + match rest { + Some(rest) => key = rest.split_once('#').map(|(_, k)| k).unwrap_or(rest), + None => break, + } + } + if key.is_empty() { + format!("head#{reviewed_head}") + } else { + key.to_string() + } +} + +/// The job that waits for GitHub's rate limit to reset, and the delay of its +/// first SQS hop. It keeps its attempt count, and has its own dedup key. +pub(crate) fn limit_wait_message( + msg: &ReviewMessage, + reviewed_head: &str, + delay_secs: u64, +) -> (ReviewMessage, u64) { + let mut next = msg.clone(); + next.limit_waits = msg.limit_waits + 1; + if next.question.is_none() && !reviewed_head.is_empty() { + next.head_sha = reviewed_head.to_string(); + } + next.dedup_key = format!( + "limit#{}#{}", + next.limit_waits, + base_dedup_key(msg, reviewed_head) + ); + let hop = delay_secs.min(SQS_MAX_DELAY_SECS); + next.wait_secs = delay_secs - hop; + (next, hop) +} + /// The job that retries `msg` after `delay_secs`, and the delay of its first /// SQS hop (the rest rides in `wait_secs`). A verdict review is pinned to the /// head it was reviewing, so a newer commit's own review supersedes it; a @@ -262,15 +345,7 @@ pub(crate) fn retry_message( next.head_sha = reviewed_head.to_string(); } // The original trigger's key, without an earlier retry's prefix. - let base = match msg.dedup_key.strip_prefix("retry#") { - Some(rest) => rest - .split_once('#') - .map(|(_, k)| k) - .unwrap_or(rest) - .to_string(), - None if msg.dedup_key.is_empty() => format!("head#{reviewed_head}"), - None => msg.dedup_key.clone(), - }; + let base = base_dedup_key(msg, reviewed_head); next.dedup_key = format!("retry#{}#{base}", next.attempt); let hop = delay_secs.min(SQS_MAX_DELAY_SECS); next.wait_secs = delay_secs - hop; @@ -968,7 +1043,8 @@ pub async fn run( FormalResult::Posted(None) } Err(e) => { - review_failed(state, &review, &head, &e.to_string(), &job).await; + let limit = limit_wait_of(&*e, review.installation_id); + review_failed(state, &review, &head, &e.to_string(), limit, &job).await; FormalResult::Failed } }; @@ -981,7 +1057,8 @@ pub async fn run( out } Err(e) => { - review_failed(state, &msg, &reviewed_head, &e.to_string(), &job).await; + let limit = limit_wait_of(&*e, msg.installation_id); + review_failed(state, &msg, &reviewed_head, &e.to_string(), limit, &job).await; Ok(()) } } @@ -1127,8 +1204,78 @@ async fn send_reply( /// A review didn't finish: log it (for the failed-review metric), then send /// it again or, once every retry failed, leave a note on the PR. Never a -/// REQUEST_CHANGES, and never touches an earlier verdict. +/// REQUEST_CHANGES, and never touches an earlier verdict. GitHub's rate +/// limit (`limit_wait`: seconds until it resets) is not a failure of the +/// review: the job waits for the reset, spends no attempt, and never ends in +/// the gave-up note. async fn review_failed( + state: &WorkerState, + msg: &ReviewMessage, + head: &str, + reason: &str, + limit_wait: Option, + job: &LiveJob, +) { + match failure_plan_for(msg, limit_wait) { + FailurePlan::WaitForLimit { delay_secs } => { + let (next, hop) = limit_wait_message(msg, head, delay_secs); + if enqueue_review(state, &next, hop).await { + let due = chrono::Utc::now().timestamp() + delay_secs as i64; + let text = common::github_wait::waiting_text( + common::github_wait::Cause::RateLimit, + due.max(0) as u64, + ); + let (title, summary) = super::review_session::limit_wait(&text); + job.hand_off_check(state, msg, &next.dedup_key, due, &title, &summary) + .await; + job.finished( + state, + msg, + common::review_live::Finished::Retrying { + reason: &text, + retry_in_secs: delay_secs as i64, + budget_secs: REVIEW_LEASE_SECS as i64, + }, + ) + .await; + info!( + pr = msg.pr_number, + waits = next.limit_waits, + delay_secs, + "review_limit_wait: the review waits for GitHub's rate limit to reset" + ); + return; + } + // The queue refused: end like an outlasted limit, quietly. + } + FailurePlan::LimitOutlasted => {} + FailurePlan::Retry { .. } | FailurePlan::GiveUp => { + return review_failed_for_service(state, msg, head, reason, job).await; + } + } + // GitHub's limit: no note on the PR, and the failed-review metric is not + // counted (nothing failed on CoderHelm's side). + warn!( + pr = msg.pr_number, + waits = msg.limit_waits, + "review_limit_outlasted: GitHub's rate limit held; the review ends without a note" + ); + let text = format!( + "GitHub's rate limit for this installation held through {} waits; the review runs again \ + on the next push, or comment @coderhelm re-review", + msg.limit_waits + ); + job.finished( + state, + msg, + common::review_live::Finished::Failed { reason: &text }, + ) + .await; +} + +/// A review that didn't finish for a service error (not GitHub's rate +/// limit): sent again by [`failure_plan`], then the gave-up note. +async fn review_failed_for_service( state: &WorkerState, msg: &ReviewMessage, head: &str, @@ -3835,6 +3982,7 @@ pub async fn review_for_run( return None; } let msg = ReviewMessage { + limit_waits: 0, team_id: team_id.to_string(), installation_id, repo_owner: owner.to_string(), @@ -5242,6 +5390,7 @@ mod superseded_tests { fn msg(head: &str, question: Option<&str>) -> ReviewMessage { ReviewMessage { + limit_waits: 0, team_id: "T".into(), installation_id: 1, repo_owner: "o".into(), @@ -5603,6 +5752,7 @@ mod failure_tests { fn msg() -> ReviewMessage { ReviewMessage { + limit_waits: 0, team_id: "T".into(), installation_id: 1, repo_owner: "o".into(), @@ -5670,6 +5820,90 @@ mod failure_tests { assert!(gave_up_note(&q, "").contains("Ask again")); } + /// The incident: a review failed on GitHub's rate limit at 20:07, was + /// retried at 20:17 and 20:32 into the same limit, and gave up with a + /// "service error" note. A rate limit now waits for the reset, spends no + /// attempt, and never ends in the gave-up note. + #[test] + fn a_rate_limited_review_waits_for_the_reset_and_never_gives_up_noisily() { + let mut m = msg(); + // Two attempts already spent on real service errors. + m.attempt = 2; + let reset_in = 1_700; + let plan = failure_plan_for(&m, Some(reset_in)); + let FailurePlan::WaitForLimit { delay_secs } = plan else { + panic!("{plan:?}"); + }; + assert!(delay_secs > reset_in, "after the reset, not before"); + assert!(delay_secs <= reset_in + 10); + let (next, hop) = limit_wait_message(&m, "a1b2c3d4", delay_secs); + assert_eq!(next.attempt, 2, "a rate limit spends no attempt"); + assert_eq!(next.limit_waits, 1); + assert_eq!(hop, SQS_MAX_DELAY_SECS, "one SQS delay at a time"); + assert_eq!(hop + next.wait_secs, delay_secs); + assert_eq!(next.dedup_key, "limit#1#head#a1b2c3d4"); + // Waiting again keeps the trigger's key, never stacks prefixes. + let (again, _) = limit_wait_message(&next, "a1b2c3d4", 60); + assert_eq!(again.dedup_key, "limit#2#head#a1b2c3d4"); + // A service error after a wait is still one of the 3 retries. + let (retry, _) = retry_message(&again, "a1b2c3d4", 120); + assert_eq!(retry.dedup_key, "retry#3#head#a1b2c3d4"); + assert_eq!(failure_plan_for(&retry, None), FailurePlan::GiveUp); + // The limit holding through every wait ends quietly: never GiveUp, + // the only plan that posts the gave-up note. + let mut long = msg(); + long.limit_waits = MAX_LIMIT_WAITS; + assert_eq!( + failure_plan_for(&long, Some(60)), + FailurePlan::LimitOutlasted + ); + for waits in 0..=MAX_LIMIT_WAITS { + for attempt in 0..5 { + let mut x = msg(); + x.limit_waits = waits; + x.attempt = attempt; + assert_ne!(failure_plan_for(&x, Some(30)), FailurePlan::GiveUp); + } + } + // The gave-up note is only sent from the service-error path. + let src = include_str!("review_pr.rs"); + let f = src.find("\nasync fn review_failed(").unwrap(); + let body = &src[f..f + src[f..] + .find("\nasync fn review_failed_for_service(") + .unwrap()]; + assert!(!body.contains("gave_up_note(")); + assert!(body.contains("review_failed_for_service(")); + } + + #[test] + fn a_rate_limit_is_read_from_the_error_or_the_installation() { + let limited: Box = Box::new( + crate::clients::github::GitHubPaused::after(common::github_wait::Cause::RateLimit, 900), + ); + assert!(limit_wait_of(&*limited, 1).is_some_and(|w| w >= 900)); + let outage: Box = Box::new( + crate::clients::github::GitHubPaused::after(common::github_wait::Cause::Outage, 60), + ); + assert_eq!(limit_wait_of(&*outage, 777_000_001), None); + let other: Box = "model overloaded".into(); + assert_eq!(limit_wait_of(&*other, 777_000_002), None); + crate::clients::github::mark_limited( + 777_000_003, + chrono::Utc::now().timestamp() as u64 + 400, + ); + assert!(limit_wait_of(&*other, 777_000_003).is_some_and(|w| w <= 400)); + let (title, summary) = + crate::passes::review_session::limit_wait(&common::github_wait::waiting_text( + common::github_wait::Cause::RateLimit, + 1_793_999_100, + )); + assert_eq!( + title, + "Review paused: Waiting for GitHub's hourly limit to reset at 21:05 UTC; continues by itself" + ); + assert!(summary.contains("nothing failed")); + } + /// The incident: the reply says nothing in the diff needs changing while /// CoderHelm's error review still requests changes → the formal review /// runs first, in the same job, and the reply follows it. diff --git a/services/worker/src/passes/review_session.rs b/services/worker/src/passes/review_session.rs index 0b8084cf9..e14e294c0 100644 --- a/services/worker/src/passes/review_session.rs +++ b/services/worker/src/passes/review_session.rs @@ -298,6 +298,18 @@ pub(crate) fn retry_wait(reason: &str, due: i64) -> (String, String) { ) } +/// The check's title and summary while the review waits for GitHub's rate +/// limit to reset (`text`: `common::github_wait::waiting_text`). +pub(crate) fn limit_wait(text: &str) -> (String, String) { + ( + format!("Review paused: {text}"), + format!( + "{text}. GitHub's hourly request limit for this installation is used up; nothing \ + failed on the review's side, and it runs in this check once the limit resets." + ), + ) +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/worker/src/passes/review_sweep.rs b/services/worker/src/passes/review_sweep.rs index 58bb3d7fd..04edec738 100644 --- a/services/worker/src/passes/review_sweep.rs +++ b/services/worker/src/passes/review_sweep.rs @@ -422,6 +422,7 @@ fn sweep_message( head: &str, ) -> ReviewMessage { ReviewMessage { + limit_waits: 0, team_id: r.team_id.clone(), installation_id, repo_owner: owner.to_string(), diff --git a/services/worker/src/passes/run_end.rs b/services/worker/src/passes/run_end.rs index 9b05e5be9..302a25f2c 100644 --- a/services/worker/src/passes/run_end.rs +++ b/services/worker/src/passes/run_end.rs @@ -23,8 +23,61 @@ //! questions then. //! - The generic questions ([`Empty::Generic`]) are only for a ticket that //! names no file and a plan with no file tasks. +//! - "Wrote no file" means the coder made no write. Writes GitHub refused +//! for a while (its rate limit, a 5xx), or a diff it couldn't show for +//! that reason, are a wait ([`Empty::Wait`]): the run pauses and goes on +//! by itself (`common::github_wait`). Writes GitHub rejected for a real +//! reason are reported with that reason ([`Empty::Rejected`]). Neither is +//! ever called CoderHelm's miss. use super::plan_coverage::PlanTask; +use common::github_wait::Cause; + +/// What became of the writes a pass tried, beyond the files it wrote. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Writes { + /// Write calls GitHub refused for a while: how many, why, and until + /// when (epoch seconds) the last one said to wait. + pub refused: usize, + pub refused_for: Option<(Cause, u64)>, + /// Write calls GitHub rejected for a real reason, as `path: reason`. + pub rejected: Vec, +} + +impl Writes { + /// One write call GitHub refused for a while. + pub fn refuse(&mut self, cause: Cause, until: u64) { + self.refused += 1; + let later = self.refused_for.map_or(until, |(_, u)| u.max(until)); + self.refused_for = Some((cause, later)); + } + + /// One write call GitHub rejected: `what` names the file(s), `why` is + /// GitHub's answer. + pub fn reject(&mut self, what: &str, why: &str) { + if self.rejected.len() < 5 { + self.rejected + .push(format!("{what}: {}", common::truncate_str(why.trim(), 300))); + } + } + + pub fn merge(&mut self, other: Writes) { + self.refused += other.refused; + if let Some((c, u)) = other.refused_for { + let later = self.refused_for.map_or(u, |(_, x)| x.max(u)); + self.refused_for = Some((c, later)); + } + for r in other.rejected { + if self.rejected.len() < 5 { + self.rejected.push(r); + } + } + } +} + +/// Why GitHub couldn't be read or written just now, when it was for a +/// while: the cause and until when (epoch seconds). +pub type Outside = Option<(Cause, u64)>; /// What a step that changed no file leads to. #[derive(Debug, Clone, PartialEq, Eq)] @@ -39,6 +92,11 @@ pub enum Empty { /// The ticket names no file and the plan has no file tasks: ask what /// should change. Generic, + /// GitHub refused the writes (or the branch's diff) for a while: the run + /// waits until then (epoch seconds) and goes on by itself. + Wait(Cause, u64), + /// GitHub rejected the writes for a real reason: stop, saying it. + Rejected(String), } /// The files the branch changes that are the run's work: everything but the @@ -104,16 +162,27 @@ pub fn ticket_names_files(text: &str) -> bool { /// files (`None` when GitHub couldn't say: then nothing is claimed either /// way and the plan decides); `tasks`: the plan's file tasks; /// `questions`: the coder's own; `ticket_names_files`: the ticket's text -/// names a file. +/// names a file; `writes`: the writes GitHub refused or rejected; +/// `outside`: GitHub is refusing requests for a while right now. pub fn judge( work: Option<&[String]>, tasks: &[PlanTask], questions: &[String], ticket_names_files: bool, + writes: &Writes, + outside: Outside, ) -> Empty { if let Some(w) = work.filter(|w| !w.is_empty()) { return Empty::Carry(w.to_vec()); } + // Writes GitHub refused for a while, or a branch GitHub couldn't show + // while it refuses: wait for it, never "wrote no file". + if let Some((cause, until)) = writes.refused_for.or(outside.filter(|_| work.is_none())) { + return Empty::Wait(cause, until); + } + if !writes.rejected.is_empty() { + return Empty::Rejected(rejected_reason(&writes.rejected)); + } if !questions.is_empty() { return Empty::Ask(questions.to_vec()); } @@ -127,6 +196,14 @@ pub fn judge( Empty::Generic } +fn rejected_reason(rejected: &[String]) -> String { + format!( + "Stopped without a pull request: GitHub rejected the coder's writes to the branch: {}. \ + The change was written but couldn't be saved; once that is fixed, Retry saves it.", + rejected.join("; ") + ) +} + fn unbuilt_reason(required: &[&PlanTask], unread: bool) -> String { let mut list = String::new(); for (i, t) in required.iter().enumerate() { @@ -145,15 +222,18 @@ fn unbuilt_reason(required: &[&PlanTask], unread: bool) -> String { } else { format!("{} planned task(s): {list}", required.len()) }; + if unread { + // Whether the work is there is unknown: never blame anyone for it. + return format!( + "Stopped without a pull request: the coder made no write in this step and GitHub \ + couldn't show the branch's diff, so whether the earlier work is there is unknown \ + ({what}). Retry checks the branch again and builds what is missing." + ); + } format!( - "Stopped without a pull request: the coder wrote no file{}, although the ticket and plan \ - say what to build ({what}). That is CoderHelm's miss, not missing detail: Retry builds it \ - from the same plan.", - if unread { - " (and GitHub couldn't show the branch's diff)" - } else { - " on the branch" - } + "Stopped without a pull request: the coder made no write to the branch, although the \ + ticket and plan say what to build ({what}). That is CoderHelm's miss, not missing \ + detail: Retry builds it from the same plan." ) } @@ -206,6 +286,10 @@ mod tests { - [ ] `e2e/test-map.json`: Register the new spec\n\ - [ ] `studio/schema.json`: Regenerate with schema extract\n"; + fn none() -> Writes { + Writes::default() + } + fn files(p: &[&str]) -> Vec { p.iter().map(|s| s.to_string()).collect() } @@ -222,7 +306,7 @@ mod tests { ]); let work = work_files(&branch, "ABC-12"); assert_eq!(work.len(), 3, "the plan files are not the work"); - let out = judge(Some(&work), &plan_tasks(PLAN), &[], true); + let out = judge(Some(&work), &plan_tasks(PLAN), &[], true, &none(), None); assert_eq!(out, Empty::Carry(work)); } @@ -231,7 +315,7 @@ mod tests { let work = work_files(&files(&["openspec/specs/abc-12/proposal.md"]), "ABC-12"); assert!(work.is_empty()); // The ticket and plan name the files: never the generic questions. - match judge(Some(&work), &plan_tasks(PLAN), &[], true) { + match judge(Some(&work), &plan_tasks(PLAN), &[], true, &none(), None) { Empty::Unbuilt(r) => { assert!(r.contains("3 planned task(s)"), "{r}"); assert!(r.contains("`web/src/blocks/hero.tsx`")); @@ -260,7 +344,7 @@ mod tests { "a bare 'ok?' is not a question worth asking" ); assert_eq!( - judge(Some(&[]), &plan_tasks(PLAN), &qs, true), + judge(Some(&[]), &plan_tasks(PLAN), &qs, true, &none(), None), Empty::Ask(qs.clone()) ); let asked = questions_from(&qs); @@ -270,15 +354,72 @@ mod tests { #[test] fn generic_questions_only_when_nothing_names_a_file() { - assert_eq!(judge(Some(&[]), &[], &[], false), Empty::Generic); + assert_eq!( + judge(Some(&[]), &[], &[], false, &none(), None), + Empty::Generic + ); assert!(matches!( - judge(Some(&[]), &[], &[], true), + judge(Some(&[]), &[], &[], true, &none(), None), Empty::Unbuilt(_) )); // An unreadable diff never claims "no changes" for a planned ticket. assert!(matches!( - judge(None, &plan_tasks(PLAN), &[], false), - Empty::Unbuilt(r) if r.contains("couldn't show") + judge(None, &plan_tasks(PLAN), &[], false, &none(), None), + Empty::Unbuilt(r) if r.contains("couldn't show") && !r.contains("CoderHelm's miss") + )); + } + + /// The incident: every write was refused with GitHub's rate limit and + /// the diff couldn't be read either. That is a wait, never "the coder + /// wrote no file", never CoderHelm's miss. + #[test] + fn writes_github_refused_for_a_while_are_a_wait_not_no_file() { + let mut writes = Writes::default(); + for _ in 0..29 { + writes.refuse(Cause::RateLimit, 1_793_999_100); + } + assert_eq!(writes.refused, 29); + let out = judge(None, &plan_tasks(PLAN), &[], true, &writes, None); + assert_eq!(out, Empty::Wait(Cause::RateLimit, 1_793_999_100)); + // No write was refused, but GitHub is refusing while the diff is + // unread: also a wait. + let out = judge( + None, + &plan_tasks(PLAN), + &[], + true, + &none(), + Some((Cause::Outage, 7)), + ); + assert_eq!(out, Empty::Wait(Cause::Outage, 7)); + // With the work readable on the branch, the run carries on. + let work = files(&["web/src/blocks/hero.tsx"]); + assert_eq!( + judge(Some(&work), &plan_tasks(PLAN), &[], true, &writes, None), + Empty::Carry(work) + ); + } + + #[test] + fn writes_github_rejected_for_a_real_reason_say_that_reason() { + let mut writes = Writes::default(); + writes.reject( + "web/src/blocks/hero.tsx", + "HTTP status client error (403 Forbidden) for url (...): Resource not accessible by integration", + ); + match judge(Some(&[]), &plan_tasks(PLAN), &[], true, &writes, None) { + Empty::Rejected(r) => { + assert!(r.contains("GitHub rejected the coder's writes"), "{r}"); + assert!(r.contains("Resource not accessible by integration")); + assert!(!r.contains("CoderHelm's miss")); + assert!(!r.contains("wrote no file")); + } + other => panic!("{other:?}"), + } + // Only a step with no write at all is "no write". + assert!(matches!( + judge(Some(&[]), &plan_tasks(PLAN), &[], true, &none(), None), + Empty::Unbuilt(r) if r.contains("made no write") )); } diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index 95283d38b..df2654877 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -485,6 +485,39 @@ pub async fn on_pass(state: &WorkerState, team_id: &str, run_id: &str) -> Result } } +/// The pass each run goes on with after a wait for GitHub, in this process: +/// entering it again is not a pass transition (`common::github_wait`). +static REENTRY: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| Mutex::new(std::collections::HashMap::new())); + +/// The run goes on with `pass` after a wait for GitHub: its next entry into +/// that pass is not counted as a new pass. +pub fn forgive_reentry(run_id: &str, pass: &str) { + if let Ok(mut m) = REENTRY.lock() { + m.insert(run_id.to_string(), pass.to_string()); + } +} + +/// Whether entering `pass` now is the run going on after a wait for GitHub +/// (once: the entry after it counts as usual). +pub fn take_reentry(run_id: &str, pass: &str) -> bool { + let Ok(mut m) = REENTRY.lock() else { + return false; + }; + match m.get(run_id) { + Some(p) if p == pass => { + m.remove(run_id); + true + } + Some(_) => { + // The run went on elsewhere: whatever it enters counts. + m.remove(run_id); + false + } + None => false, + } +} + /// A step is about to hand off (from `try_auto_continue`, so every /// continuation). `Some(reason)` when the next step must not start. pub async fn on_continuation(state: &WorkerState, team_id: &str, run_id: &str) -> Option {