From 33b6a17bf561835c9233cb9d06ec03bcf3be5fda Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 30 Nov 2026 20:48:46 -0500 Subject: [PATCH 1/6] A hand-off to a person is typed, and CoderHelm owns its own limits A hand-off is a PersonOnly from a closed set (a named permission an owner or admin grants, a product decision, an approval the rules require, a credential, work someone else holds, a real-world action), built only through common::person_only. Words about CoderHelm's sandbox, allowlist, budgets, tools, CI use, labels, tests or reads make an OwnProblem instead: an internal alert and one run-page line. The person gate, hand-backs and a fix round's NEEDS A PERSON line all go through it. On its own pull request the reviewer blocks only on what a route can satisfy (review_feasible). A pull request with no progress for a day is diagnosed, retried along its next route and alerted (own_problems::check on the sweep). Hand-offs are counted per team by reason, own problems by subject, with the time each pull request spent blocked. Incident case xd_own_limits_never_a_persons. --- .../xd_own_limits_never_a_persons.md | 5 + services/common/src/handback.rs | 38 ++ services/common/src/lib.rs | 1 + services/common/src/person_gate.rs | 136 +++- services/common/src/person_only.rs | 636 ++++++++++++++++++ .../incidents/um_own_reads_never_handed.rs | 4 +- .../xd_own_limits_never_a_persons.rs | 183 +++++ services/worker/src/passes/mod.rs | 11 + services/worker/src/passes/own_problems.rs | 379 +++++++++++ .../worker/src/passes/own_review_ledger.rs | 29 +- services/worker/src/passes/person_gate.rs | 52 ++ services/worker/src/passes/pr_watch.rs | 1 + services/worker/src/passes/review_feasible.rs | 230 +++++++ services/worker/src/passes/review_pr.rs | 16 + services/worker/src/passes/settle.rs | 7 + 15 files changed, 1685 insertions(+), 43 deletions(-) create mode 100644 docs/incidents/xd_own_limits_never_a_persons.md create mode 100644 services/common/src/person_only.rs create mode 100644 services/worker/src/passes/incidents/xd_own_limits_never_a_persons.rs create mode 100644 services/worker/src/passes/own_problems.rs create mode 100644 services/worker/src/passes/review_feasible.rs diff --git a/docs/incidents/xd_own_limits_never_a_persons.md b/docs/incidents/xd_own_limits_never_a_persons.md new file mode 100644 index 000000000..062d2acd9 --- /dev/null +++ b/docs/incidents/xd_own_limits_never_a_persons.md @@ -0,0 +1,5 @@ +# xd. `xd_own_limits_never_a_persons` + +**What happened:** A fix run's own review asked for one proof: run the fixed end-to-end test twenty times. The fix round couldn't, because CoderHelm's own sandbox couldn't reach the sites the test runs against. It ended with "NEEDS A PERSON ... outside_reach", asking someone to widen CoderHelm's own network allowlist or run the command themselves. It called a repeat run in CI "outside this ticket". CoderHelm doesn't merge over its own review, so the pull request sat with nothing moving it. The same shape came back from other limits CoderHelm owns: its time budget, its tools, a workflow's triggers it hadn't read, and a proof its review asked for that none of its routes could run. + +**The guarantee:** A hand-off to a person is a typed value (`common::person_only::PersonOnly`) from a closed set: a named permission an owner or admin grants, a product decision, an approval the repository's or team's rules require, a credential only the person holds, work someone else holds, or a real-world action. Its text is private to the module, and no variant covers CoderHelm's sandbox, network allowlist, budgets, tools, CI use, labels, tests or reads. Every written hand-off goes through one parser (`person_only::parse`, `of_reason`, `of_human_only`): the person gate's items, a fix round's `NEEDS A PERSON` line, and hand-backs. A limit CoderHelm owns comes back as an `OwnProblem`. That becomes an internal alert for CoderHelm's maintainers and one plain line on the run page, and the work goes on by another route. On its own pull request, CoderHelm's reviewer blocks only on what one of its routes can satisfy: an edit, a sandbox run, CI, or a page check. Anything else becomes one question or CoderHelm's own note (`review_feasible`). A pull request with no progress for a day gets a self-diagnosis, a retry along its next route and an internal alert (`own_problems::check`, on the 15-minute sweep). The team's hand-offs are counted by reason, its own problems by subject, along with the time each pull request spent blocked. diff --git a/services/common/src/handback.rs b/services/common/src/handback.rs index f28f433d3..5be10b37e 100644 --- a/services/common/src/handback.rs +++ b/services/common/src/handback.rs @@ -109,8 +109,14 @@ pub struct HandBack { impl HandBack { /// `None` without a need: a hand-back says exactly what is needed. + /// `None` too when the need names a limit CoderHelm owns (its sandbox, + /// allowlist, budgets, tools, CI usage, labels, tests or reads, + /// `person_only::own_subject`): that is never a person's. pub fn new(why: HumanOnly, need: &str) -> Option { let n = need.split_whitespace().collect::>().join(" "); + if !n.is_empty() && typed(why) && crate::person_only::of_human_only(why, &n).is_err() { + return None; + } (!n.is_empty()).then(|| HandBack { why, need: crate::truncate_str(&n, 600).to_string(), @@ -170,6 +176,21 @@ impl HandBack { } } +/// Reasons whose need is something a person is asked for (and so goes +/// through `person_only`). The others record what already happened (a +/// person's action, the usage limit, another holder) or are the recovery +/// ladder's own end (`Unrepaired`). +fn typed(why: HumanOnly) -> bool { + matches!( + why, + HumanOnly::Credential + | HumanOnly::MissingAccess + | HumanOnly::ProductDecision + | HumanOnly::AmbiguousTicket + | HumanOnly::Approval + ) +} + /// Reads a reason on the list from words a run, a check or the judge wrote. /// `None` when they name none, which is the case for every stall, red /// check, tool error, time limit or budget, and for a read the team's @@ -179,6 +200,11 @@ pub fn human_only_in(text: &str) -> Option { if crate::aws_role_reads::is_install_grant(text) { return None; } + // Words about CoderHelm's own limits name no reason, whatever else they + // say ("grant access ... to CoderHelm's sandbox allowlist"). + if crate::person_only::own_subject(text).is_some() { + return None; + } let t = text.to_lowercase(); let any = |marks: &[&str]| marks.iter().any(|m| t.contains(m)); if any(&[ @@ -273,6 +299,18 @@ mod tests { ); } + #[test] + fn coderhelms_own_limits_are_never_a_hand_back() { + for t in [ + "Grant access: add staging.acme-books.example to CoderHelm's sandbox network allowlist", + "No access to the preview from the sandbox: net::ERR_TUNNEL_CONNECTION_FAILED", + "The e2e workflow has no repeat input; run the test 20 times yourself", + ] { + assert_eq!(human_only_in(t), None, "{t}"); + assert!(HandBack::new(HumanOnly::MissingAccess, t).is_none(), "{t}"); + } + } + #[test] fn a_read_the_aws_role_lacks_is_the_install_item_never_a_wait() { let asked = "Grant access: the team's read-only role was denied wafv2:ListWebACLs and \ diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index abd934fb7..ae37b97a1 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -323,6 +323,7 @@ pub mod person_gate; /// A person's lines on a CoderHelm branch stay theirs: writes that would undo them are /// kept out. pub mod person_lines; +pub mod person_only; /// Plugins: packages of skills, agents, tools, triggers and outputs a team installs. pub mod plugins; /// One shape for "something is wrong": set by a check, cleared by the same diff --git a/services/common/src/person_gate.rs b/services/common/src/person_gate.rs index 352cc2633..5d688d699 100644 --- a/services/common/src/person_gate.rs +++ b/services/common/src/person_gate.rs @@ -237,6 +237,10 @@ pub enum Work { Command(String), /// Its own step, as written (a query to run, a list to post). Own(String), + /// A limit CoderHelm owns that a writer tried to hand a person + /// (`person_only`): CoderHelm takes another route, its maintainers get + /// an internal alert, and the run page says so in one line. + Problem(crate::person_only::OwnProblem), } impl Work { @@ -251,6 +255,7 @@ impl Work { ), Work::Command(c) => format!("ran `{c}` in its sandbox"), Work::Own(w) => w.clone(), + Work::Problem(p) => p.line(), } } } @@ -287,6 +292,9 @@ impl Decision { #[derive(Debug, Clone, PartialEq, Eq)] pub struct HumanItem { reason: Reason, + /// The typed hand-off it stands for (`person_only`): a `HumanItem` + /// exists only for one. + person: crate::person_only::PersonOnly, action: String, who: String, why_not: String, @@ -298,6 +306,9 @@ impl HumanItem { pub fn reason(&self) -> Reason { self.reason } + pub fn person(&self) -> &crate::person_only::PersonOnly { + &self.person + } pub fn action(&self) -> &str { &self.action } @@ -823,7 +834,7 @@ fn reason_named(t: &str) -> Option { /// A step that spends real money: "paid" before an action a customer /// takes (a paid checkout, registration, booking, order), or a purchase /// made for real. No sandbox or test card stands in for one. -fn paid_action(t: &str) -> bool { +pub(crate) fn paid_action(t: &str) -> bool { const ACTIONS: &[&str] = &[ "checkout", "registration", @@ -1010,16 +1021,14 @@ pub fn decide(a: &Ask, ctx: &Context) -> Outcome { return deploy_item(a, &t, ctx); } return match reason_in(&cause) { - Some(reason @ (Reason::Grant | Reason::Credential | Reason::Approval)) => { - Outcome::Human(HumanItem { - reason, - action: first_nonempty(&a.how, &a.text), - who: who_for(reason, &a.owner), - why_not: first_nonempty(&a.why_not, reason.label()), - options: Vec::new(), - recommendation: String::new(), - }) - } + Some(reason @ (Reason::Grant | Reason::Credential | Reason::Approval)) => human( + reason, + first_nonempty(&a.how, &a.text), + who_for(reason, &a.owner), + first_nonempty(&a.why_not, reason.label()), + Vec::new(), + String::new(), + ), _ => Outcome::Do(Work::Own(one_line(&a.text))), }; } @@ -1043,14 +1052,14 @@ pub fn decide(a: &Ask, ctx: &Context) -> Outcome { } // 2. A listed reason the item itself names. if let Some(reason) = reason_in(&t) { - return Outcome::Human(HumanItem { + return human( reason, - action: first_nonempty(&a.how, &a.text), - who: who_for(reason, &a.owner), - why_not: first_nonempty(&a.why_not, reason.label()), - options: Vec::new(), - recommendation: String::new(), - }); + first_nonempty(&a.how, &a.text), + who_for(reason, &a.owner), + first_nonempty(&a.why_not, reason.label()), + Vec::new(), + String::new(), + ); } // 3. A choice: settled by a source, else decided, else (hard to // reverse, nothing settles it) one yes/no on the recommendation. @@ -1085,14 +1094,14 @@ pub fn decide(a: &Ask, ctx: &Context) -> Outcome { if options.is_empty() { options = vec![rec.clone(), "leaving it out".to_string()]; } - return Outcome::Human(HumanItem { - reason: Reason::Irreversible, - action: format!("Yes or no: {}", trim_end(&strip_question_marks(&a.text))), - who: who_for(Reason::Irreversible, &a.owner), - why_not: Reason::Irreversible.label().to_string(), + return human( + Reason::Irreversible, + format!("Yes or no: {}", trim_end(&strip_question_marks(&a.text))), + who_for(Reason::Irreversible, &a.owner), + Reason::Irreversible.label().to_string(), options, - recommendation: rec, - }); + rec, + ); } let chose = first_nonempty(&recommendation_of(a), &a.text); return Outcome::Decided(Decision { @@ -1143,14 +1152,14 @@ fn deploy_item(a: &Ask, t: &str, ctx: &Context) -> Outcome { } (m, _) => sentence_start(m), }; - Outcome::Human(HumanItem { + human( reason, action, - who: who_for(reason, &a.owner), - why_not: first_nonempty(&a.why_not, reason.label()), - options: Vec::new(), - recommendation: String::new(), - }) + who_for(reason, &a.owner), + first_nonempty(&a.why_not, reason.label()), + Vec::new(), + String::new(), + ) } impl Ask { @@ -1197,16 +1206,57 @@ pub fn for_reason(why: HumanOnly, a: &Ask) -> Option { HumanOnly::Approval => Reason::Approval, _ => return None, }; - Some(HumanItem { + human_item( + reason, + first_nonempty(&a.how, &a.text), + who_for(reason, &a.owner), + first_nonempty(&a.why_not, reason.label()), + Vec::new(), + String::new(), + ) + .ok() +} + +/// The one way a [`HumanItem`] is made: from a typed hand-off +/// (`person_only::of_reason`) for its reason and words. Words about +/// CoderHelm's own limits (its sandbox, allowlist, budgets, tools, CI +/// usage, labels, tests, reads) make no hand-off: they are its own problem. +fn human_item( + reason: Reason, + action: String, + who: String, + why_not: String, + options: Vec, + recommendation: String, +) -> Result { + let person = crate::person_only::of_reason(reason, &format!("{action}. {why_not}"))?; + Ok(HumanItem { reason, - action: first_nonempty(&a.how, &a.text), - who: who_for(reason, &a.owner), - why_not: first_nonempty(&a.why_not, reason.label()), - options: Vec::new(), - recommendation: String::new(), + person, + action, + who, + why_not, + options, + recommendation, }) } +/// [`human_item`] as the gate's outcome: an item for a person, or +/// CoderHelm's own problem ([`Work::Problem`]). +fn human( + reason: Reason, + action: String, + who: String, + why_not: String, + options: Vec, + recommendation: String, +) -> Outcome { + match human_item(reason, action, who, why_not, options, recommendation) { + Ok(h) => Outcome::Human(h), + Err(p) => Outcome::Do(Work::Problem(p)), + } +} + /// The stable key of an item's decision: its kind and topic, or its /// content words when it has no topic. pub fn key(a: &Ask) -> String { @@ -1259,6 +1309,18 @@ impl Gated { .collect() } + /// CoderHelm's own problems a writer tried to hand a person + /// (`person_only`): each is an internal alert and one run-page line. + pub fn problems(&self) -> Vec<&crate::person_only::OwnProblem> { + self.items + .iter() + .filter_map(|(_, o)| match o { + Outcome::Do(Work::Problem(p)) => Some(p), + _ => None, + }) + .collect() + } + /// What CoderHelm does itself. pub fn work(&self) -> Vec<&Work> { self.items diff --git a/services/common/src/person_only.rs b/services/common/src/person_only.rs new file mode 100644 index 000000000..d2e9f2c36 --- /dev/null +++ b/services/common/src/person_only.rs @@ -0,0 +1,636 @@ +//! The typed hand-off: the only value that lets CoderHelm hand work to a +//! person. +//! +//! A fix round once ended "NEEDS A PERSON ... outside_reach: add the hosts to +//! CoderHelm's sandbox network allowlist, or run the command yourself", and +//! its pull request sat for days. The same shape came back from other +//! limits CoderHelm owns itself: its time budget, its tools, a workflow's +//! triggers it hadn't read, a proof its own review asked for. Each time the +//! default was to stop and hand the job to a person. +//! +//! [`PersonOnly`] is a closed set of things only a person has. Every variant +//! carries the exact named thing (the permission, the secret, the rule, the +//! question) as a [`Named`], whose text field is private: a `Named` is made +//! only by this module, after [`own_subject`] found nothing of CoderHelm's +//! own in it. There is no variant for CoderHelm's sandbox, its network +//! allowlist, its budgets or time, its tools, its use of CI (repeats, +//! reruns, dispatches), labels, tests or reads, so a hand-off about any of +//! them can't be built: +//! +//! ```compile_fail +//! use common::person_only::{Named, PersonOnly}; +//! // The text field is private: a hand-off can't be built from loose words. +//! let p = PersonOnly::Credential { secret: Named("add the hosts to the allowlist".into()) }; +//! ``` +//! +//! Free text (a model's `NEEDS A PERSON` line, a gate reason code, an +//! outside step) goes through [`parse`] or [`admit`], which return +//! `Result`. An [`OwnProblem`] is CoderHelm's: the +//! caller tries its other routes, records an internal alert for CoderHelm's +//! maintainers and writes one plain line on the run page +//! ([`OwnProblem::line`]). It never reaches a person as a to-do. + +use std::fmt; + +/// Who grants a permission only a person can grant. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Grantor { + /// The GitHub organization's owner. + OrgOwner, + /// The repository's admin. + RepoAdmin, + /// The team's admin in CoderHelm's settings (a connection, a role). + TeamAdmin, +} + +impl Grantor { + pub fn words(self) -> &'static str { + match self { + Grantor::OrgOwner => "an organization owner", + Grantor::RepoAdmin => "a repository admin", + Grantor::TeamAdmin => "a team admin", + } + } +} + +/// The exact thing a person is asked for, in one line. Made only here, +/// after [`own_subject`] found nothing CoderHelm owns in it. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Named(String); + +impl Named { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for Named { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +/// The only things a person is handed. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum PersonOnly { + /// A permission only an owner or admin can grant, named (`actions: + /// write on the GitHub App`, `connect the ticket tracker`). + Grant { permission: Named, by: Grantor }, + /// A product or business decision nothing settles: one yes/no question. + ProductDecision { question: Named }, + /// An approval the repository's or team's own rules require, named. + Approval { rule: Named }, + /// A credential only the person holds, named. + Credential { secret: Named }, + /// Someone else already holds the work: CoderHelm waits on them. + HeldByAnother { holder: Named }, + /// An action in the physical or paying world (a purchase with real + /// money, a real device), named. + RealWorld { action: Named }, +} + +/// What kind of hand-off a writer asks for, before its words are checked. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Want { + Grant(Grantor), + ProductDecision, + Approval, + Credential, + HeldByAnother, + RealWorld, +} + +impl PersonOnly { + /// The reason code kept on the run and in the team's counts. + pub fn code(&self) -> &'static str { + match self { + PersonOnly::Grant { .. } => "grant", + PersonOnly::ProductDecision { .. } => "product_decision", + PersonOnly::Approval { .. } => "approval", + PersonOnly::Credential { .. } => "credential", + PersonOnly::HeldByAnother { .. } => "held_by_another", + PersonOnly::RealWorld { .. } => "real_world", + } + } + + /// The named thing. + pub fn named(&self) -> &Named { + match self { + PersonOnly::Grant { permission: n, .. } + | PersonOnly::ProductDecision { question: n } + | PersonOnly::Approval { rule: n } + | PersonOnly::Credential { secret: n } + | PersonOnly::HeldByAnother { holder: n } + | PersonOnly::RealWorld { action: n } => n, + } + } + + /// One line a person reads: who, and exactly what. + pub fn line(&self) -> String { + match self { + PersonOnly::Grant { permission, by } => { + format!("Needs {} to grant: {permission}", by.words()) + } + PersonOnly::ProductDecision { question } => format!("Your call: {question}"), + PersonOnly::Approval { rule } => { + format!("Needs the approval your rules require: {rule}") + } + PersonOnly::Credential { secret } => { + format!("Needs a credential only you hold: {secret}") + } + PersonOnly::HeldByAnother { holder } => format!("Held by someone else: {holder}"), + PersonOnly::RealWorld { action } => { + format!("Needs a person in the real world: {action}") + } + } + } +} + +/// What CoderHelm owns itself: never a person's to-do. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum OwnSubject { + /// Its sandbox: a browser, a package, a build that won't start there. + Sandbox, + /// Its sandbox's network allowlist. + Egress, + /// Its own time, turns, spend or round budgets. + Budget, + /// A tool it lacks or that failed. + Tooling, + /// Its use of CI: repeats, reruns, dispatches, a workflow's inputs. + CiUsage, + /// Labels on its pull request. + Labels, + /// Running tests, suites or end-to-end checks. + Testing, + /// Reading a log, a result, an artifact or a page. + Reads, + /// Words that name no reason a person has: CoderHelm finds another + /// route. + Unnamed, +} + +/// Every CoderHelm-owned subject. +pub const OWN_SUBJECTS: &[OwnSubject] = &[ + OwnSubject::Sandbox, + OwnSubject::Egress, + OwnSubject::Budget, + OwnSubject::Tooling, + OwnSubject::CiUsage, + OwnSubject::Labels, + OwnSubject::Testing, + OwnSubject::Reads, + OwnSubject::Unnamed, +]; + +impl OwnSubject { + pub fn code(self) -> &'static str { + match self { + OwnSubject::Sandbox => "sandbox", + OwnSubject::Egress => "egress", + OwnSubject::Budget => "budget", + OwnSubject::Tooling => "tooling", + OwnSubject::CiUsage => "ci_usage", + OwnSubject::Labels => "labels", + OwnSubject::Testing => "testing", + OwnSubject::Reads => "reads", + OwnSubject::Unnamed => "unnamed", + } + } + + fn words(self) -> &'static str { + match self { + OwnSubject::Sandbox => "its sandbox", + OwnSubject::Egress => "its sandbox's network allowlist", + OwnSubject::Budget => "its own time or budget", + OwnSubject::Tooling => "its tools", + OwnSubject::CiUsage => "how it runs CI", + OwnSubject::Labels => "labels on its pull request", + OwnSubject::Testing => "running the tests", + OwnSubject::Reads => "reading a result", + OwnSubject::Unnamed => "a step it has no route for yet", + } + } +} + +/// A limit CoderHelm owns, met while it worked: tried another way, sent to +/// CoderHelm's maintainers as an internal alert, and said on the run page +/// in one plain line. Never a person's step. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OwnProblem { + pub subject: OwnSubject, + /// The writer's words, one line. + pub text: String, +} + +impl OwnProblem { + /// The run page's one line. + pub fn line(&self) -> String { + format!( + "CoderHelm met a limit in {} and is taking another route; its maintainers were alerted: {}", + self.subject.words(), + crate::truncate_str(&self.text, 240) + ) + } +} + +fn one_line(s: &str) -> String { + s.split_whitespace().collect::>().join(" ") +} + +fn any(t: &str, marks: &[&str]) -> bool { + marks.iter().any(|m| t.contains(m)) +} + +/// A refusal GitHub sent on a named API, recorded with the permission it +/// needs: a permission a person grants, whatever CI words come with it. +fn recorded_refusal(t: &str) -> bool { + !t.contains(&crate::github_grants::INSTALL_LEVEL.to_lowercase()) + && crate::github_grants::Denial::parse(t).is_some() +} + +/// The CoderHelm-owned subject the words name, if any. +pub fn own_subject(text: &str) -> Option { + let t = one_line(text).to_lowercase(); + if t.is_empty() { + return Some(OwnSubject::Unnamed); + } + if any( + &t, + &[ + "allowlist", + "allow list", + "egress", + "err_tunnel_connection_failed", + "coderhelm_egress_blocked", + ], + ) { + return Some(OwnSubject::Egress); + } + if crate::stop_rules::tooling::names_own_tooling(&t) { + return Some(OwnSubject::Sandbox); + } + if any( + &t, + &[ + "time budget", + "time limit", + "step's time", + "ran out of time", + "spend cap", + "spend ceiling", + "fix budget", + "its budget", + "turn limit", + "fix rounds", + "out of turns", + ], + ) { + return Some(OwnSubject::Budget); + } + if any( + &t, + &[ + // A tool missing in its sandbox; never "the app isn't + // installed" on a repository, which is a person's grant. + "isn't installed in", + "is not installed in", + "command not found", + "missing tool", + "a tool failed", + "tool error", + ], + ) { + return Some(OwnSubject::Tooling); + } + // A recorded refusal names a real permission, even about a workflow. + if recorded_refusal(&t) { + return None; + } + if any( + &t, + &[ + "repeat-each", + "repeat run", + "repeat input", + "repeat_each", + "repeats", + "re-run the", + "rerun the", + "dispatch the", + "a ci change", + "outside this ticket", + "run the workflow", + "start the workflow", + ], + ) { + return Some(OwnSubject::CiUsage); + } + if any( + &t, + &[ + "add the label", + "add a label", + "add labels", + "label the pull request", + ], + ) && !t.contains("deploy") + { + return Some(OwnSubject::Labels); + } + if any( + &t, + &[ + "run the test", + "run the e2e", + "run the end-to-end", + "run the suite", + "run playwright", + "npx playwright", + "npx cypress", + "yourself", + ], + ) { + return Some(OwnSubject::Testing); + } + if crate::stop_rules::tooling::names_own_read(&t) { + return Some(OwnSubject::Reads); + } + None +} + +/// The hand-off `want` asks for, if its words name nothing CoderHelm owns. +pub fn admit(want: Want, text: &str) -> Result { + let line = one_line(text); + if let Some(subject) = own_subject(&line) { + return Err(OwnProblem { + subject, + text: line, + }); + } + let n = Named(crate::truncate_str(&line, 600).to_string()); + Ok(match want { + Want::Grant(by) => PersonOnly::Grant { permission: n, by }, + Want::ProductDecision => PersonOnly::ProductDecision { question: n }, + Want::Approval => PersonOnly::Approval { rule: n }, + Want::Credential => PersonOnly::Credential { secret: n }, + Want::HeldByAnother => PersonOnly::HeldByAnother { holder: n }, + Want::RealWorld => PersonOnly::RealWorld { action: n }, + }) +} + +/// A gate reason (`person_gate::Reason`) with the item's words. The +/// catch-all "outside every system" is a person's only when the words name +/// a real-world action (real money, a real device); else it is CoderHelm's +/// to find a route for. +pub fn of_reason(reason: crate::person_gate::Reason, text: &str) -> Result { + use crate::person_gate::Reason as R; + let t = text.to_lowercase(); + let want = match reason { + R::Credential => Want::Credential, + R::Grant => Want::Grant(grantor_in(&t)), + R::Irreversible => Want::ProductDecision, + R::HeldByAnother => Want::HeldByAnother, + R::Approval => Want::Approval, + R::OutsideReach if real_world(&t) => Want::RealWorld, + R::OutsideReach => match want_in(&t) { + Some(w) => w, + None => { + return Err(OwnProblem { + subject: own_subject(&t).unwrap_or(OwnSubject::Unnamed), + text: one_line(text), + }) + } + }, + }; + admit(want, text) +} + +/// A hand-back reason (`handback::HumanOnly`) with its need. +pub fn of_human_only( + why: crate::handback::HumanOnly, + need: &str, +) -> Result { + use crate::handback::HumanOnly as H; + let t = need.to_lowercase(); + let want = match why { + H::Credential => Want::Credential, + H::MissingAccess => Want::Grant(grantor_in(&t)), + H::ProductDecision | H::AmbiguousTicket => Want::ProductDecision, + H::HeldByAnother | H::PersonAction => Want::HeldByAnother, + H::Approval | H::UsageLimit => Want::Approval, + // An error CoderHelm couldn't get past is its own problem. + H::Unrepaired => { + return Err(OwnProblem { + subject: own_subject(&t).unwrap_or(OwnSubject::Unnamed), + text: one_line(need), + }) + } + }; + admit(want, need) +} + +/// A model's line ` :: ` (the fix +/// round's `NEEDS A PERSON` line): the one parser for written hand-offs. +pub fn parse(code: &str, what: &str) -> Result { + let reason = crate::person_gate::REASONS + .iter() + .copied() + .find(|r| r.code() == code.trim()); + match reason { + Some(r) => of_reason(r, what), + None => match want_in(&what.to_lowercase()) { + Some(w) => admit(w, what), + None => Err(OwnProblem { + subject: own_subject(what).unwrap_or(OwnSubject::Unnamed), + text: one_line(what), + }), + }, + } +} + +/// What a person must do that words ask for outright ("only an org owner +/// can grant ...", "needs the production credentials", "a manual check on a +/// real device"), as a typed hand-off. `None` when they ask nothing only a +/// person has, or name a CoderHelm-owned subject. +pub fn person_need_in(text: &str) -> Option { + let t = one_line(text).to_lowercase(); + let asks = any( + &t, + &[ + "only a person", + "a person must", + "needs a person", + "needs someone", + "only an org owner", + "only an organization owner", + "only an admin", + "an admin must", + "requires approval", + "needs approval", + "credentials only", + "credentials to", + "access to production", + "manual check on a real device", + "real device", + "product decision", + "business decision", + ], + ); + if !asks { + return None; + } + admit(want_in(&t)?, text).ok() +} + +fn real_world(t: &str) -> bool { + crate::person_gate::paid_action(t) + || any( + t, + &[ + "physical device", + "real device", + "real-device", + "in person", + "phone call", + "by phone", + "on site", + ], + ) +} + +fn grantor_in(t: &str) -> Grantor { + if any( + t, + &["org owner", "organization owner", "organisation owner"], + ) { + Grantor::OrgOwner + } else if any(t, &["settings", "connect ", "team admin"]) { + Grantor::TeamAdmin + } else { + Grantor::RepoAdmin + } +} + +/// The kind of hand-off plain words ask for, when they name one. +fn want_in(t: &str) -> Option { + if any(t, &["api key", "secret", "token", "password", "credential"]) { + return Some(Want::Credential); + } + if recorded_refusal(t) + || any( + t, + &[ + "org owner", + "organization owner", + "repository admin", + "grant the app", + "not turned on", + "app isn't installed", + "connect ", + ], + ) + { + return Some(Want::Grant(grantor_in(t))); + } + if any( + t, + &["product decision", "business decision", "product choice"], + ) { + return Some(Want::ProductDecision); + } + if any(t, &["approv"]) && any(t, &["policy", "rule", "codeowners", "required review"]) { + return Some(Want::Approval); + } + if real_world(t) { + return Some(Want::RealWorld); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::person_gate::Reason; + + /// Words about CoderHelm's own limits, as fix rounds and passes wrote + /// them (invented: the acme bookstore). + pub(crate) const OWN: &[&str] = &[ + "Add staging.acme-books.example and *.preview-web.acme-books.example to CoderHelm's sandbox network allowlist, or run the command yourself", + "The sandbox's network allowlist blocks the preview", + "net::ERR_TUNNEL_CONNECTION_FAILED on every repeat run", + "The e2e workflow runs each test once and has no repeat input; adding one would be a CI change outside this ticket", + "Run `npx playwright test tests/cart.spec.ts --repeat-each=20` yourself", + "The step reached its time limit before the repeat run finished", + "CoderHelm's fix budget for this run is spent", + "`terraform` isn't installed in CoderHelm's sandbox", + "Add the label run-e2e to the pull request", + "Re-run the end-to-end workflow on the head", + "Read the end-to-end result in the workflow's log", + ]; + + #[test] + fn coderhelms_own_limits_never_become_a_person_hand_off() { + for t in OWN { + assert!(own_subject(t).is_some(), "{t}"); + for r in crate::person_gate::REASONS { + assert!(of_reason(*r, t).is_err(), "{:?}: {t}", r); + } + for w in [ + Want::Grant(Grantor::OrgOwner), + Want::ProductDecision, + Want::Approval, + Want::Credential, + Want::HeldByAnother, + Want::RealWorld, + ] { + assert!(admit(w, t).is_err(), "{:?}: {t}", w); + } + assert!(parse("outside_reach", t).is_err(), "{t}"); + } + } + + #[test] + fn what_only_a_person_has_is_named_exactly() { + let p = parse( + "credential", + "Add the BOOKSTORE_PAYMENTS_KEY secret in the repository's settings", + ) + .unwrap(); + assert_eq!(p.code(), "credential"); + assert!(p.line().contains("BOOKSTORE_PAYMENTS_KEY")); + let g = of_reason( + Reason::Grant, + "An organization owner grants the CoderHelm app access to the catalog repository", + ) + .unwrap(); + assert!(matches!( + g, + PersonOnly::Grant { + by: Grantor::OrgOwner, + .. + } + )); + let paid = of_reason(Reason::OutsideReach, "complete a purchase on the preview").unwrap(); + assert_eq!(paid.code(), "real_world"); + } + + #[test] + fn outside_reach_with_no_named_reason_is_coderhelms() { + let e = parse("outside_reach", "Ask someone to look at the cart page").unwrap_err(); + assert_eq!(e.subject, OwnSubject::Unnamed); + assert!(e.line().contains("maintainers were alerted")); + // An unknown code with no named reason is CoderHelm's too. + assert!(parse("nonsense", "do the thing").is_err()); + } + + #[test] + fn an_unrepaired_error_is_coderhelms_own_problem() { + assert!(of_human_only(crate::handback::HumanOnly::Unrepaired, "the build fails").is_err()); + assert!(of_human_only( + crate::handback::HumanOnly::Credential, + "the API key for the shipping sandbox" + ) + .is_ok()); + } +} diff --git a/services/worker/src/passes/incidents/um_own_reads_never_handed.rs b/services/worker/src/passes/incidents/um_own_reads_never_handed.rs index 00d3341b5..1dafe573d 100644 --- a/services/worker/src/passes/incidents/um_own_reads_never_handed.rs +++ b/services/worker/src/passes/incidents/um_own_reads_never_handed.rs @@ -58,5 +58,7 @@ fn the_plan_and_the_review_ledger_keep_reads_as_coderhelms() { let plan = include_str!("../outside_work.rs"); assert!(plan.contains("names_own_read(&t)")); let ledger = include_str!("../own_review_ledger.rs"); - assert!(ledger.contains("tooling::names_own_read(&what)")); + // Read through the one hand-off parser, which counts reads as + // CoderHelm's own (`person_only::own_subject`). + assert!(ledger.contains("common::person_only::parse(&code, &what)")); } diff --git a/services/worker/src/passes/incidents/xd_own_limits_never_a_persons.rs b/services/worker/src/passes/incidents/xd_own_limits_never_a_persons.rs new file mode 100644 index 000000000..e4e7ce9b5 --- /dev/null +++ b/services/worker/src/passes/incidents/xd_own_limits_never_a_persons.rs @@ -0,0 +1,183 @@ +//! xd. A fix run for the acme bookstore's flaky checkout test opened its +//! pull request, and CoderHelm's own review asked for twenty repeat runs. +//! The fix round couldn't run them: CoderHelm's sandbox couldn't reach the +//! bookstore's staging site or the pull request's preview. It wrote +//! "NEEDS A PERSON ... outside_reach :: add the hosts to CoderHelm's +//! sandbox network allowlist, or run the command yourself", and called a +//! repeat input on CI "a CI change outside this ticket". CoderHelm does not +//! merge over its own review, so the pull request sat. +//! +//! Guarantee: a hand-off is a typed `PersonOnly` from a closed set, made +//! only through `person_only`. A limit CoderHelm owns is an `OwnProblem`: +//! an internal alert and one run-page line, never a person's step. Its own +//! reviewer blocks only on what a route it has can satisfy, a quiet pull +//! request is diagnosed and retried after a day, and hand-offs are counted +//! by reason. + +use common::person_gate::{self, Ask, Context, Kind, Outcome}; +use common::person_only::{self, OwnSubject, PersonOnly}; + +use crate::passes::own_review_ledger::{Blocker, Ledger, NEEDS_A_PERSON}; + +const FINDING: &str = + "Fix is unproven: no repeat run shows the checkout spec passes (`tests/checkout.spec.ts:12`)"; + +/// What the fix round and its passes wrote, invented for the bookstore. +const OWN_WORDS: &[&str] = &[ + "Add staging.acme-books.example and *.preview-shop.acme-books.example to CoderHelm's sandbox network allowlist, or run `npx playwright test tests/checkout.spec.ts --repeat-each=20 --retries=0` yourself", + "The e2e workflow runs each test once and has no repeat input; adding one would be a CI change outside this ticket", + "The step reached its time limit before the repeat run finished", + "`playwright` isn't installed in CoderHelm's sandbox", +]; + +#[test] +fn the_fix_rounds_hand_off_is_coderhelms_own_block() { + let mut l = Ledger::default(); + l.observe(&[FINDING.to_string()], ""); + l.start_round(&[FINDING.to_string()]); + l.end_round( + Vec::new(), + &format!( + "Every attempt failed before the page loaded.\n{NEEDS_A_PERSON} {FINDING} :: outside_reach :: {}", + OWN_WORDS[0] + ), + ); + l.observe(&[FINDING.to_string()], ""); + // Said as CoderHelm's own problem (an internal alert and one run-page + // line) when the round ends. + let account = format!( + "{NEEDS_A_PERSON} {FINDING} :: outside_reach :: {}", + OWN_WORDS[0] + ); + let own = crate::passes::own_review_ledger::own_problems_in(&account); + assert_eq!(own.len(), 1); + assert_eq!(own[0].subject, OwnSubject::Egress); + let t = &l.findings[0]; + assert_eq!(t.person_claims, 0, "no person claim was counted"); + assert!(t.person_reason.is_empty()); + assert_eq!(t.last_blocked, vec![Blocker::Tooling]); +} + +#[test] +fn no_coderhelm_owned_limit_ever_reaches_a_person() { + for w in OWN_WORDS { + assert!(person_only::own_subject(w).is_some(), "{w}"); + assert!(person_only::parse("outside_reach", w).is_err(), "{w}"); + for kind in [ + Kind::Assumption, + Kind::OpenItem, + Kind::Step, + Kind::Question, + Kind::Attempt, + ] { + let mut a = Ask::new(kind, w); + a.why_not = "outside_reach: it is outside every system CoderHelm reaches".into(); + let o = person_gate::decide(&a, &Context::default()); + assert!(!matches!(o, Outcome::Human(_)), "{kind:?}: {w}"); + } + assert_eq!(common::handback::human_only_in(w), None, "{w}"); + assert!( + common::handback::HandBack::new(common::handback::HumanOnly::MissingAccess, w) + .is_none(), + "{w}" + ); + } + // Written as a hand-off, it becomes CoderHelm's own problem with its + // run-page line, and it is counted by subject, not as a person's. + let g = person_gate::gate( + vec![Ask::new( + Kind::Step, + "Only a person can add staging.acme-books.example to CoderHelm's sandbox network allowlist (outside every system CoderHelm reaches)", + )], + &Context::default(), + ); + assert!(g.human().is_empty()); + let counts = crate::passes::own_problems::handoff_counts(&g); + assert!(counts.iter().all(|(k, _)| !k.starts_with("person_"))); + if let Some(p) = g.problems().first() { + assert_eq!(p.subject, OwnSubject::Egress); + assert!(p.line().contains("maintainers were alerted")); + } +} + +#[test] +fn what_only_a_person_has_still_reaches_them_named() { + let p = person_only::parse( + "credential", + "Add the ACME_BOOKS_PAYMENTS_KEY secret in the repository's Actions secrets", + ) + .unwrap(); + assert!(matches!(p, PersonOnly::Credential { .. })); + assert!(p.line().contains("ACME_BOOKS_PAYMENTS_KEY")); + let g = person_gate::gate( + vec![Ask::new( + Kind::OpenItem, + "Add the ACME_BOOKS_PAYMENTS_KEY secret: a credential only a person can provide", + )], + &Context::default(), + ); + let h = g.human(); + assert_eq!(h.len(), 1); + assert_eq!(h[0].person().code(), "credential"); + let counts = crate::passes::own_problems::handoff_counts(&g); + assert_eq!(counts, vec![("person_credential".to_string(), 1)]); +} + +#[test] +fn its_own_review_blocks_only_on_what_a_route_can_satisfy() { + use crate::passes::review_agent::Finding; + use crate::passes::review_feasible::{apply, check, Available}; + let proof = Finding { + file: "tests/checkout.spec.ts".into(), + line: 12, + severity: "blocking".into(), + category: "testing".into(), + title: "Fix is unproven".into(), + body: "Prove it with 20 repeat runs (`--repeat-each=20 --retries=0`).".into(), + evidence: Some("verified-defect".into()), + ..Default::default() + }; + // CI is a route even when the sandbox can't reach the sites: a block. + assert_eq!( + check( + &proof, + &Available { + sandbox: false, + ci: true + } + ), + None + ); + // No route at all: CoderHelm's own gap, never a block. + let mut v = vec![proof]; + let (_, gaps) = apply( + &mut v, + &Available { + sandbox: false, + ci: false, + }, + ); + assert_eq!(gaps.len(), 1); + assert!(!v[0].holds_merge()); + // The reviewer calls the check on CoderHelm's own pull request. + let src = include_str!("../review_pr.rs"); + assert!(src.contains("super::review_feasible::apply(&mut findings, &avail)")); +} + +#[test] +fn a_pull_request_quiet_for_a_day_is_diagnosed_and_retried() { + use crate::passes::own_problems::{stall, Route}; + let s = stall( + true, + "2030-03-01T09:00:00Z", + "", + "CoderHelm's review asks for changes", + "2030-03-02T10:00:00Z", + ) + .unwrap(); + assert_eq!(s.route, Route::Ready); + assert!(s.diagnosis.contains("No progress on this pull request")); + // The 15-minute sweep runs the detector on every pull request it looks at. + let src = include_str!("../pr_watch.rs"); + assert!(src.contains("super::own_problems::check(state, &c).await;")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index a4b9f1a00..4dd315f44 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1382,6 +1382,7 @@ pub mod outcome; pub mod outcome_learning; pub mod outside_exec; pub mod outside_work; +pub(crate) mod own_problems; pub mod own_review; pub mod own_review_ledger; pub mod ownership; @@ -1440,6 +1441,7 @@ pub mod review_configs; pub mod review_discipline; #[cfg(test)] mod review_eval; +pub(crate) mod review_feasible; pub(crate) mod review_fingerprint; pub mod review_fix; pub mod review_labels; @@ -9883,6 +9885,15 @@ async fn report_also_outside( // over: the hand-off analytics read these. if let Some(c) = decision.outside_change.as_ref() { person_gate::record_counts(state, &msg.team_id, run_id, &outside_work::counts(c)).await; + // The team's hand-offs by reason, and CoderHelm's own problems the + // steps named (each an internal alert): `own_problems`. + let mut asks: Vec = outside_work::steps_now(c, true) + .iter() + .map(|s| s.ask()) + .collect(); + asks.extend(outside_work::person_checks(c).iter().map(|s| s.ask())); + let gated = common::person_gate::gate(asks, &common::person_gate::Context::default()); + own_problems::record_handoffs(state, &msg.team_id, run_id, &gated).await; } // The ticket gets only what a person must do; with nothing for anyone // the comment says nothing (the conversation layer drops it from the diff --git a/services/worker/src/passes/own_problems.rs b/services/worker/src/passes/own_problems.rs new file mode 100644 index 000000000..d39d34bf5 --- /dev/null +++ b/services/worker/src/passes/own_problems.rs @@ -0,0 +1,379 @@ +//! CoderHelm's own problems, its hand-off counts and its stalls. +//! +//! - [`record`]: a limit CoderHelm owns that a writer tried to hand a +//! person (`common::person_only::OwnProblem`) is an internal alert for +//! CoderHelm's maintainers (an error log line carrying [`ALERT_MARK`], +//! which the log alarm reads, and a row under [`ALERT_PK`]) and one plain +//! line on the run page. The work goes on by another route. +//! - [`record_handoffs`]: the team's counts of hand-offs by reason and of +//! its own problems by subject ([`STATS_SK`]), so a rise shows. +//! - [`stall`]: a CoderHelm pull request or run with no progress for +//! [`STALL_HOURS`] gets a self-diagnosis line, a retry along its next +//! route, and an internal alert. It never sits silent for days. + +use aws_sdk_dynamodb::types::AttributeValue; +use common::person_only::{OwnProblem, OwnSubject, PersonOnly}; +use tracing::{error, warn}; + +use super::{attr_n, attr_s}; +use crate::WorkerState; + +/// The marker on every internal alert's log line. +pub const ALERT_MARK: &str = "CODERHELM_OWN_PROBLEM"; +/// Where internal alerts are kept, across teams (settings table). +pub const ALERT_PK: &str = "CODERHELM#OWN_PROBLEMS"; +/// The team's hand-off counts (settings table, under the team). +pub const STATS_SK: &str = "HANDOFF_STATS"; +/// Hours without progress before a pull request or run counts as stalled. +pub const STALL_HOURS: i64 = 24; +/// Alerts are kept this long. +const ALERT_DAYS: i64 = 30; + +/// The count attribute for a hand-off reason. +pub fn person_attr(p: &PersonOnly) -> String { + format!("person_{}", p.code()) +} + +/// The count attribute for an own problem's subject. +pub fn own_attr(s: OwnSubject) -> String { + format!("own_{}", s.code()) +} + +/// Records one own problem: the internal alert and the run page's line. +pub async fn record(state: &WorkerState, team_id: &str, run_id: &str, p: &OwnProblem) { + alert(state, team_id, run_id, p.subject.code(), &p.text).await; + super::add_progress_note(state, team_id, run_id, &p.line()).await; + add(state, team_id, &[(own_attr(p.subject), 1)]).await; +} + +/// An internal alert for CoderHelm's maintainers: never shown to the team +/// as a to-do. +pub async fn alert(state: &WorkerState, team_id: &str, run_id: &str, kind: &str, text: &str) { + error!( + marker = ALERT_MARK, + team_id, run_id, kind, text, "CoderHelm met a limit it owns" + ); + let now = chrono::Utc::now(); + let ttl = (now + chrono::Duration::days(ALERT_DAYS)).timestamp(); + if let Err(e) = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", attr_s(ALERT_PK)) + .item( + "sk", + attr_s(&format!("{}#{team_id}#{run_id}#{kind}", now.to_rfc3339())), + ) + .item("team_id", attr_s(team_id)) + .item("run_id", attr_s(run_id)) + .item("kind", attr_s(kind)) + .item("text", attr_s(common::truncate_str(text, 1_000))) + .item("ttl", AttributeValue::N(ttl.to_string())) + .send() + .await + { + warn!(team_id, run_id, error = %e, "Could not keep the internal alert"); + } +} + +/// The counts one gated list adds: each hand-off by its reason, each own +/// problem by its subject. +pub fn handoff_counts(g: &common::person_gate::Gated) -> Vec<(String, u64)> { + let mut out: Vec<(String, u64)> = Vec::new(); + let mut bump = |k: String| match out.iter_mut().find(|(a, _)| *a == k) { + Some((_, n)) => *n += 1, + None => out.push((k, 1)), + }; + for h in g.human() { + bump(person_attr(h.person())); + } + for p in g.problems() { + bump(own_attr(p.subject)); + } + out +} + +/// Keeps a gated list's hand-offs and own problems: the team's counts, and +/// each own problem as an internal alert with its run-page line. +pub async fn record_handoffs( + state: &WorkerState, + team_id: &str, + run_id: &str, + g: &common::person_gate::Gated, +) { + let counts = handoff_counts(g); + if counts.is_empty() { + return; + } + add(state, team_id, &counts).await; + let mut seen: Vec<&str> = Vec::new(); + for p in g.problems() { + if seen.contains(&p.text.as_str()) { + continue; + } + seen.push(&p.text); + alert(state, team_id, run_id, p.subject.code(), &p.text).await; + super::add_progress_note(state, team_id, run_id, &p.line()).await; + } +} + +/// Adds to the team's counts. Best effort. +async fn add(state: &WorkerState, team_id: &str, counts: &[(String, u64)]) { + if counts.is_empty() { + return; + } + let mut req = state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(STATS_SK)); + let mut parts = Vec::new(); + for (i, (k, n)) in counts.iter().enumerate() { + parts.push(format!("#k{i} :v{i}")); + req = req + .expression_attribute_names(format!("#k{i}"), k.clone()) + .expression_attribute_values(format!(":v{i}"), attr_n(*n)); + } + if let Err(e) = req + .update_expression(format!("ADD {}", parts.join(", "))) + .send() + .await + { + warn!(team_id, error = %e, "Could not keep the team's hand-off counts"); + } +} + +// ── stalls ─────────────────────────────────────────────────────────────── + +/// The run attribute holding when the stall detector last acted, and how +/// many times, as `#`. +pub const STALL_FIELD: &str = "stall_seen"; +/// The run attribute holding the seconds its pull request spent blocked. +pub const BLOCKED_FIELD: &str = "blocked_secs"; + +/// The next route a stalled pull request takes, by how many times the +/// detector already acted on the same stall. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Route { + /// Ask the ready decision again (it re-reads checks, previews, holds). + Ready, + /// Ask CoderHelm's review of the head again, with what the run settled. + Review, + /// Ask the ready decision and the review again together. + Both, +} + +/// What the detector does about one pull request now, or `None`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Stall { + pub route: Route, + pub tries: u32, + /// The run page's self-diagnosis line. + pub diagnosis: String, +} + +fn hours_between(from: &str, to: &str) -> Option { + let a = chrono::DateTime::parse_from_rfc3339(from).ok()?; + let b = chrono::DateTime::parse_from_rfc3339(to).ok()?; + Some((b - a).num_hours()) +} + +/// Whether the run's pull request stalled: open, no change to the run for +/// [`STALL_HOURS`], and not already acted on in the last [`STALL_HOURS`] +/// (`seen`: [`STALL_FIELD`]). `waiting` is what the pull request waits on +/// as the run page says it. Pure. +pub fn stall(open: bool, updated_at: &str, seen: &str, waiting: &str, now: &str) -> Option { + if !open || updated_at.is_empty() { + return None; + } + if hours_between(updated_at, now)? < STALL_HOURS { + return None; + } + let (at, tries) = match seen.split_once('#') { + Some((at, n)) => (at, n.parse::().unwrap_or(0)), + None => ("", 0), + }; + if !at.is_empty() && hours_between(at, now).is_some_and(|h| h < STALL_HOURS) { + return None; + } + let route = match tries % 3 { + 0 => Route::Ready, + 1 => Route::Review, + _ => Route::Both, + }; + let what = if waiting.trim().is_empty() { + "nothing it recorded".to_string() + } else { + waiting.trim().trim_end_matches('.').to_string() + }; + let next = match route { + Route::Ready => "asking the ready decision again", + Route::Review => "asking its own review of the head again", + Route::Both => "asking the ready decision and its review again", + }; + Some(Stall { + route, + tries: tries + 1, + diagnosis: format!( + "No progress on this pull request for {} hours. It was waiting on: {what}. CoderHelm is {next}, and its maintainers were alerted.", + hours_between(updated_at, now).unwrap_or(STALL_HOURS) + ), + }) +} + +/// Seconds a pull request spent blocked since the last look: the time +/// between looks while its standing said it waits on something other than +/// CoderHelm. Pure. +pub fn blocked_delta(standing_json: &str, looked_at: &str, now: &str) -> i64 { + let Some(s) = common::merge_standing::Standing::from_json(standing_json) else { + return 0; + }; + let blocked = s.needs_person + || matches!( + s.code.as_str(), + "review_changes_requested" | "draft" | "checks_failing" | "conflict" + ); + if !blocked || looked_at.is_empty() { + return 0; + } + let (Ok(a), Ok(b)) = ( + chrono::DateTime::parse_from_rfc3339(looked_at), + chrono::DateTime::parse_from_rfc3339(now), + ) else { + return 0; + }; + (b - a).num_seconds().clamp(0, 6 * 3600) +} + +/// The detector, for one pull request the 15-minute sweep looked at: keeps +/// the time it spent blocked, and acts on a stall. +pub async fn check(state: &WorkerState, c: &super::pr_watch::Candidate) { + let now = chrono::Utc::now().to_rfc3339(); + let open = super::pr_watch::watched(&c.status) && c.status != "merged"; + let blocked = blocked_delta(&c.standing, &c.looked_at, &now); + if blocked > 0 { + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&c.team_id)) + .key("run_id", attr_s(&c.run_id)) + .update_expression("ADD #b :d") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_names("#b", BLOCKED_FIELD) + .expression_attribute_values(":d", attr_n(blocked as u64)) + .send() + .await; + add( + state, + &c.team_id, + &[("pr_blocked_secs".to_string(), blocked as u64)], + ) + .await; + } + let standing = common::merge_standing::Standing::from_json(&c.standing); + let waiting = c.waiting_line(standing.as_ref()); + let seen = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&c.team_id)) + .key("run_id", attr_s(&c.run_id)) + .projection_expression("#s") + .expression_attribute_names("#s", STALL_FIELD) + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get(STALL_FIELD).and_then(|v| v.as_s().ok()).cloned()) + .unwrap_or_default(); + let Some(s) = stall(open, &c.updated_at, &seen, &waiting, &now) else { + return; + }; + // Claimed first: a second sweep never acts on the same stall. + let claimed = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&c.team_id)) + .key("run_id", attr_s(&c.run_id)) + .update_expression("SET #s = :new") + .condition_expression( + "attribute_exists(run_id) AND (attribute_not_exists(#s) OR #s = :old)", + ) + .expression_attribute_names("#s", STALL_FIELD) + .expression_attribute_values(":new", attr_s(&format!("{now}#{}", s.tries))) + .expression_attribute_values(":old", attr_s(&seen)) + .send() + .await + .is_ok(); + if !claimed { + return; + } + super::add_progress_note(state, &c.team_id, &c.run_id, &s.diagnosis).await; + alert(state, &c.team_id, &c.run_id, "stall", &s.diagnosis).await; + add(state, &c.team_id, &[("stalls".to_string(), 1)]).await; + if matches!(s.route, Route::Ready | Route::Both) { + super::ready::request_for( + state, + &c.team_id, + c.installation_id, + &c.owner, + &c.repo, + c.pr, + ) + .await; + } + if matches!(s.route, Route::Review | Route::Both) { + let head = super::pr_watch::Probe::parse(&c.probe) + .map(|p| p.seen.head) + .unwrap_or_default(); + if !head.is_empty() { + super::review_pr::review_for_ready( + state, + &c.team_id, + c.installation_id, + (&c.owner, &c.repo, c.pr), + &head, + ) + .await; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pull_request_quiet_for_a_day_is_diagnosed_and_retried_along_routes() { + let now = "2026-11-20T12:00:00Z"; + assert!(stall(true, "2026-11-20T00:00:00Z", "", "a review", now).is_none()); + let s = stall(true, "2026-11-18T12:00:00Z", "", "CoderHelm's review", now).unwrap(); + assert_eq!(s.route, Route::Ready); + assert!(s.diagnosis.contains("48 hours")); + assert!(s.diagnosis.contains("CoderHelm's review")); + // Acted on within the day: nothing more yet. + assert!(stall( + true, + "2026-11-18T12:00:00Z", + "2026-11-20T06:00:00Z#1", + "", + now + ) + .is_none()); + // A day later the next route. + let s = stall( + true, + "2026-11-18T12:00:00Z", + "2026-11-19T06:00:00Z#1", + "", + now, + ) + .unwrap(); + assert_eq!((s.route, s.tries), (Route::Review, 2)); + // Closed or merged: never. + assert!(stall(false, "2026-11-01T00:00:00Z", "", "", now).is_none()); + } +} diff --git a/services/worker/src/passes/own_review_ledger.rs b/services/worker/src/passes/own_review_ledger.rs index 4f379dbe0..3daf492c7 100644 --- a/services/worker/src/passes/own_review_ledger.rs +++ b/services/worker/src/passes/own_review_ledger.rs @@ -507,11 +507,12 @@ impl Ledger { Some((code, rest.get(1).map(|w| w.to_string()).unwrap_or_default())) }) { - if common::stop_rules::tooling::names_own_tooling(&what) - || common::stop_rules::tooling::names_own_read(&what) - { - // "Add the hosts to CoderHelm's sandbox allowlist": its - // own setup, a block the next round removes. + // The one parser for a written hand-off (`person_only`): + // "add the hosts to CoderHelm's sandbox allowlist", "run it + // 20 times yourself", "a CI change outside this ticket" make + // no hand-off. + if common::person_only::parse(&code, &what).is_err() { + // CoderHelm's own setup, a block the next round removes. if !blocked.contains(&Blocker::Tooling) { blocked.push(Blocker::Tooling); } @@ -976,6 +977,24 @@ pub async fn record_round_end( let mut l = load(state, team_id, run_id).await; l.end_round(blocked, account); save(state, team_id, run_id, &l).await; + // A hand-off the round wrote about CoderHelm's own limits is its own + // problem: an internal alert and one run-page line (`person_only`). + for p in own_problems_in(account) { + super::own_problems::record(state, team_id, run_id, &p).await; + } +} + +/// The `NEEDS A PERSON` lines of a round's account that name no reason only +/// a person has (`person_only::parse`): CoderHelm's own problems. +pub fn own_problems_in(account: &str) -> Vec { + marked(account, NEEDS_A_PERSON) + .into_iter() + .filter_map(|(_, rest)| { + let code = rest.first().copied().unwrap_or(""); + let what = rest.get(1).copied().unwrap_or(code); + common::person_only::parse(code, what).err() + }) + .collect() } /// The ticket, the comments people wrote on it and the plan's cause, from diff --git a/services/worker/src/passes/person_gate.rs b/services/worker/src/passes/person_gate.rs index dcbef307a..cf34b4db5 100644 --- a/services/worker/src/passes/person_gate.rs +++ b/services/worker/src/passes/person_gate.rs @@ -399,6 +399,58 @@ mod tests { ); } + /// A hand-off to a person is a typed `person_only::PersonOnly`: every + /// place that builds one, or reads one a model wrote, goes through that + /// module. A new builder that doesn't fails here. + #[test] + fn every_hand_off_is_typed_and_none_is_coderhelms_own() { + // The gate's items: one constructor, built from a typed hand-off. + let pg = src("../common/src/person_gate.rs"); + let pg = code(&pg); + let literals = pg.matches("HumanItem {").count() + - pg.matches("pub struct HumanItem {").count() + - pg.matches("impl HumanItem {").count(); + assert_eq!(literals, 1, "a HumanItem is built outside `human_item`"); + assert!(body_of(pg, "fn human_item(").contains("person_only::of_reason(")); + // Hand-backs. + let hb = src("../common/src/handback.rs"); + assert!(body_of(code(&hb), "pub fn new(").contains("person_only::of_human_only(")); + assert!(body_of(code(&hb), "pub fn human_only_in(").contains("person_only::own_subject(")); + // Every file that reads a model's `NEEDS A PERSON` line, writes the + // catch-all reason into a step, or counts hand-offs goes through it. + // (Rendering an item the gate already typed is not a builder.) + const BUILDERS: &[&str] = &[ + "NEEDS_A_PERSON)", + "reason: \"outside_reach\"", + "handoff_human", + ]; + const TYPED_ELSEWHERE: &[&str] = &[ + // Defines the reasons and maps them through `human_item`. + "person_gate.rs", + "handback.rs", + "person_only.rs", + ]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let mut files = Vec::new(); + rs_files(&root.join("src"), &mut files); + rs_files(&root.join("../common/src"), &mut files); + for f in files { + let name = f.file_name().unwrap().to_string_lossy().to_string(); + if TYPED_ELSEWHERE.contains(&name.as_str()) { + continue; + } + let text = std::fs::read_to_string(&f).unwrap(); + let body = code(&text); + if BUILDERS.iter().any(|b| body.contains(b)) { + assert!( + body.contains("person_only::") || body.contains("own_problems::"), + "{} builds or reads a hand-off without `person_only`", + f.display() + ); + } + } + } + #[test] fn the_standard_is_in_front_of_every_model_that_writes_for_people() { for rel in [ diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 84bd624a0..e41f1eed7 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -1249,6 +1249,7 @@ pub async fn sweep(state: &WorkerState) -> SweepReport { } report.looked_at += 1; let act = look(state, &clients[&c.installation_id], &c).await; + super::own_problems::check(state, &c).await; if act != Act::Nothing { report .acted diff --git a/services/worker/src/passes/review_feasible.rs b/services/worker/src/passes/review_feasible.rs new file mode 100644 index 000000000..1d7f25c81 --- /dev/null +++ b/services/worker/src/passes/review_feasible.rs @@ -0,0 +1,230 @@ +//! A blocking finding on CoderHelm's own pull request is one some route +//! CoderHelm has can satisfy. +//! +//! A fix run's own review once asked for a proof (twenty repeat runs) that +//! CoderHelm's sandbox could not run at the time, and held the pull request +//! for days: CoderHelm "does not merge over its own review", and its review +//! asked for what none of its routes could do. Before CoderHelm's reviewer +//! posts a blocking finding on its own pull request, [`check`] asks whether +//! a route can satisfy it: an edit to the code, a run in the sandbox, a CI +//! run (dispatched, labelled or re-run), a page check. When none can: +//! +//! - what only a person has (a permission, a credential, an approval, a +//! product decision, a real-world action) is one typed question +//! (`common::person_only::PersonOnly`), never a block; +//! - anything else is CoderHelm's own gap: a note on the finding and an +//! internal alert, never a block. + +use common::person_only::PersonOnly; + +use super::review_agent::Finding; + +/// The routes CoderHelm has on this pull request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Available { + /// Its sandbox is set up for this install. + pub sandbox: bool, + /// It can start the repository's CI on the head (a dispatch, a label, + /// a re-run): true unless the install has no Actions access at all. + pub ci: bool, +} + +/// A route that can satisfy a finding. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Route { + Edit, + Sandbox, + Ci, + PageCheck, +} + +/// What [`check`] found for a blocking finding no route satisfies. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Infeasible { + /// Only a person has it: one typed question. + Person(PersonOnly), + /// CoderHelm lacks every route for it: its own gap. + Own(String), +} + +fn asks_for_proof(t: &str) -> bool { + [ + "unproven", + "not proven", + "no proof", + "prove ", + "repeat run", + "repeat-each", + "runs in a row", + "never ran", + "not run", + "run the test", + ] + .iter() + .any(|m| t.contains(m)) +} + +/// The routes that could satisfy `f`, given what is available. +pub fn routes(f: &Finding, a: &Available) -> Vec { + let t = format!("{} {}", f.title, f.body).to_lowercase(); + let mut out = Vec::new(); + // A finding on a line of the change is answered by an edit, unless it + // asks only for proof. + if !f.file.trim().is_empty() && !asks_for_proof(&t) { + out.push(Route::Edit); + } + if a.sandbox { + out.push(Route::Sandbox); + } + if a.ci { + out.push(Route::Ci); + } + if t.contains("page") || t.contains("preview") { + out.push(Route::PageCheck); + } + out +} + +/// Whether `f`, which holds the merge, is one CoderHelm can satisfy. +/// `None`: it can, and it stays a block. +pub fn check(f: &Finding, a: &Available) -> Option { + if !f.holds_merge() { + return None; + } + let text = format!("{} {}", f.title, f.body); + // What only a person has is never satisfied by CoderHelm's routes, + // when no edit answers it. + if f.suggestion.is_none() { + if let Some(p) = common::person_only::person_need_in(&text) { + return Some(Infeasible::Person(p)); + } + } + if routes(f, a).is_empty() { + return Some(Infeasible::Own(format!( + "no route CoderHelm has satisfies \"{}\" (no edit answers it, and neither its sandbox nor CI is available)", + common::truncate_str(&f.title, 160) + ))); + } + None +} + +/// Makes each blocking finding no route satisfies a note: the person's one +/// question, or CoderHelm's own gap. Returns what changed, as +/// `(title, why)`, and the own gaps to alert on. +pub fn apply(findings: &mut [Finding], a: &Available) -> (Vec<(String, String)>, Vec) { + let mut made = Vec::new(); + let mut gaps = Vec::new(); + for f in findings.iter_mut() { + let Some(why) = check(f, a) else { continue }; + let note = match &why { + Infeasible::Person(p) => format!( + "A question, not a block: nothing CoderHelm can do settles this. {}", + p.line() + ), + Infeasible::Own(g) => { + gaps.push(g.clone()); + format!("A note, not a block: {g}; CoderHelm's maintainers were alerted.") + } + }; + super::review_policy::demote(f, ¬e); + made.push((f.title.clone(), note)); + } + (made, gaps) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn f(title: &str, body: &str, file: &str) -> Finding { + Finding { + file: file.into(), + line: if file.is_empty() { 0 } else { 3 }, + severity: "blocking".into(), + category: "bug".into(), + title: title.into(), + body: body.into(), + evidence: Some("verified-defect".into()), + ..Default::default() + } + } + + const ALL: Available = Available { + sandbox: true, + ci: true, + }; + + #[test] + fn a_proof_some_route_can_run_stays_a_block() { + let proof = f( + "Fix is unproven", + "Prove it with 20 repeat runs of the cart checkout spec.", + "tests/cart.spec.ts", + ); + assert_eq!(check(&proof, &ALL), None); + // Only CI is left: still a route. + assert_eq!( + check( + &proof, + &Available { + sandbox: false, + ci: true + } + ), + None + ); + } + + #[test] + fn a_proof_no_route_can_run_is_coderhelms_gap_not_a_block() { + let mut v = vec![f( + "Fix is unproven", + "Prove it with 20 repeat runs.", + "tests/cart.spec.ts", + )]; + let (made, gaps) = apply( + &mut v, + &Available { + sandbox: false, + ci: false, + }, + ); + assert_eq!(made.len(), 1); + assert_eq!(gaps.len(), 1); + assert!(!v[0].holds_merge()); + } + + #[test] + fn what_only_a_person_has_is_one_question_never_a_block() { + let mut v = vec![f( + "Storefront key", + "Only an org owner can grant the app access to the bookstore's payments repository.", + "src/pay.ts", + )]; + let (made, gaps) = apply(&mut v, &ALL); + assert!(gaps.is_empty()); + assert!(made[0].1.contains("A question, not a block")); + assert!(!v[0].holds_merge()); + } + + #[test] + fn a_code_defect_stays_a_block() { + let bug = f( + "Off by one in the page count", + "`pages` skips the last page of the catalog.", + "src/catalog.ts", + ); + assert_eq!(check(&bug, &ALL), None); + // Even with no sandbox or CI, an edit answers it. + assert_eq!( + check( + &bug, + &Available { + sandbox: false, + ci: false + } + ), + None + ); + } +} diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 4ec54f427..ec44cb861 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -4232,6 +4232,22 @@ async fn run_once( for m in &made { info!(pr = msg.pr_number, file = %m.file, title = %m.title, why = %m.why, "A finding that would hold the merge made a note"); } + // On CoderHelm's own pull request a block is only what some route it + // has can satisfy (`review_feasible`). + if let Some(run_id) = &own_run { + let avail = super::review_feasible::Available { + sandbox: !state.config.sandbox_bucket_name.is_empty(), + ci: true, + }; + let (made, gaps) = super::review_feasible::apply(&mut findings, &avail); + for (title, why) in &made { + info!(pr = msg.pr_number, title = %title, why = %why, "A block no route satisfies made a note"); + } + for g in &gaps { + super::own_problems::alert(state, &msg.team_id, run_id, "review_infeasible", g) + .await; + } + } } info!( pr = msg.pr_number, diff --git a/services/worker/src/passes/settle.rs b/services/worker/src/passes/settle.rs index 21f9a2dda..3a0645748 100644 --- a/services/worker/src/passes/settle.rs +++ b/services/worker/src/passes/settle.rs @@ -1746,6 +1746,13 @@ async fn write_down( "Settle: the open items" ); super::person_gate::record_counts(w.state, &w.msg.team_id, w.run_id, &settled.counts).await; + // The team's hand-offs by reason, and CoderHelm's own problems the open + // items named (each an internal alert): `own_problems`. + let gated = person_gate::gate( + settled.open.iter().map(ask_of).collect(), + &person_gate::Context::default(), + ); + super::own_problems::record_handoffs(w.state, &w.msg.team_id, w.run_id, &gated).await; if !settled.closed.is_empty() || !settled.dropped.is_empty() { super::add_progress_note( w.state, From 63fd47c9974e1ba072a63c3a93fc381f2362c148 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 30 Nov 2026 15:09:03 -0500 Subject: [PATCH 2/6] Waiting runs go on by themselves, and texts say what actually happens A run waiting on a person resumes when what it waits for arrives: a comment or reply on its ticket (Jira, or a plain comment on the GitHub issue), access granted on GitHub or a repository turned on, or usage limits saved that allow runs. Wait actions name the one thing to do and where, never "then press Retry". The wrong-repo note names the `Repo:` line and cuts its reason at a word. Tests-and-scope notes no longer quote the coding model's instructions. Fix rounds get update_pr_description with the feedback round's guard. PR labels are CoderHelm's to add, and an unblock never ends in "or run the command yourself". The updater waits out a busy stack and retries a rollback caused by throttling by itself; a failed update stack in another account gets one AWS admin action. person_text guards each of these texts. --- docs/api/openapi.json | 2 +- .../incidents/wz_waits_go_on_by_themselves.md | 5 + lambda/tests/test_updater_access.py | 11 +- lambda/tests/test_updater_busy.py | 31 ++ lambda/updater/handler.py | 57 ++- services/common/src/description_handoff.rs | 34 +- services/common/src/lib.rs | 2 + services/common/src/live/permissions.rs | 56 ++- services/common/src/merged_ticket.rs | 36 +- services/common/src/messages.rs | 11 + services/common/src/person_gate.rs | 22 +- services/common/src/pr_steps.rs | 41 ++- services/common/src/rendered.rs | 72 ++++ services/common/src/run_fail.rs | 2 +- services/common/src/run_recovery.rs | 104 ++++-- services/common/src/run_wake.rs | 142 ++++++++ services/gateway/src/routes/api.rs | 72 +++- services/gateway/src/routes/github_webhook.rs | 14 + services/gateway/src/routes/jira_webhook.rs | 12 + services/gateway/src/routes/mod.rs | 1 + services/gateway/src/routes/run_wake.rs | 343 ++++++++++++++++++ .../gateway/src/routes/ticket_comments.rs | 188 +++++++++- services/worker/src/passes/dep_fix.rs | 1 + services/worker/src/passes/feedback.rs | 18 +- services/worker/src/passes/habits_check.rs | 47 ++- services/worker/src/passes/implement.rs | 28 ++ .../vo_pass_errors_recover_not_fail.rs | 6 +- .../incidents/wz_waits_go_on_by_themselves.rs | 240 ++++++++++++ services/worker/src/passes/jira_comment.rs | 122 +++++-- services/worker/src/passes/mod.rs | 12 +- services/worker/src/passes/repo_pick.rs | 91 ++++- services/worker/src/passes/resume.rs | 7 +- services/worker/src/passes/review_eval.rs | 1 + services/worker/src/passes/triage.rs | 9 +- 34 files changed, 1681 insertions(+), 159 deletions(-) create mode 100644 docs/incidents/wz_waits_go_on_by_themselves.md create mode 100644 services/common/src/run_wake.rs create mode 100644 services/gateway/src/routes/run_wake.rs create mode 100644 services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 18d2c348e..2c0ad4268 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -6286,7 +6286,7 @@ "detail": { "description": "Why, or what is still open. May be empty.", "examples": [ - "Open on the pull request: the link check couldn't reach /pricing. Mark it ready once that is dealt with, push a fix or comment on it, and CoderHelm picks it up from there." + "Open on the pull request: the link check couldn't reach /pricing. Push a fix or comment on it, and CoderHelm picks it up from there." ], "type": "string" }, diff --git a/docs/incidents/wz_waits_go_on_by_themselves.md b/docs/incidents/wz_waits_go_on_by_themselves.md new file mode 100644 index 000000000..2e2cc98cc --- /dev/null +++ b/docs/incidents/wz_waits_go_on_by_themselves.md @@ -0,0 +1,5 @@ +# wz. `wz_waits_go_on_by_themselves` + +**What happened:** A second pass over what CoderHelm showed people found texts that still handed people work CoderHelm does, or promised what didn't happen. A run stopped for a person said "Look at what stopped the run, put it right, then press Retry", and a comment on its ticket was only kept as context, so a person's answer left the run waiting. A merged-ticket stop told people to reply on the ticket as if the reply started a run. A wrong-repo note said "set the repo and re-run" without saying where, after a reason cut in the middle of a word. A tests-and-scope note quoted the coding model's instruction ("Put it back with `restore_file` (omit `from_ref`)"). A fix round wrote that it had no tool to edit the pull request's description and that someone had to paste in the new sections. An outside-change report asked a person to add pull request labels CoderHelm adds itself, and to "run the command yourself". The updater said "press Update again" when AWS was busy, and the access check said to delete a failed stack and press Update again. + +**The guarantee:** A run that waits on a person goes on by itself when what it waits for arrives: a comment or reply on its ticket, access granted on GitHub or a repository turned on, or the usage limit raised. Its action names the one thing to do, where, and that the run goes on by itself; only a decision about the run itself (an approval, a person's own stop) waits for that decision. Notes a person reads never carry the coding model's instructions. Every fix round can have the description rebuilt. Pull request labels are CoderHelm's to add. The updater waits out a busy stack or AWS throttling and starts the update again by itself, and a failed stack in another account gets one action for an AWS admin. Tests hold each text to `common::rendered::person_text`. diff --git a/lambda/tests/test_updater_access.py b/lambda/tests/test_updater_access.py index 4d52897b6..cca276059 100644 --- a/lambda/tests/test_updater_access.py +++ b/lambda/tests/test_updater_access.py @@ -706,11 +706,18 @@ def test_a_policy_that_differs_is_never_skipped(self): u.native_poll(self.store, self.env, base.NOW) self.assertEqual(len(self.sent), 1, "told once") - def test_an_update_while_stuck_is_refused_in_words(self): + def test_an_update_while_stuck_waits_and_starts_by_itself(self): + # Not a refusal that asks for another press: the update waits like + # one AWS throttled, and starts by itself once the rollback is done. self.release(json.loads(base.TEMPLATE)) u.fetch_template = lambda url, opener=None: json.dumps(json.loads(base.TEMPLATE)).encode() - with self.assertRaisesRegex(ValueError, "still stuck"): + with self.assertRaises(u.AwsBusy) as busy: u.begin(self.store, self.env, base.NOW, "v1.1.0", "owner@example.org", "update") + self.assertIn("earlier update's rollback", busy.exception.cause) + self.assertNotIn("press update", busy.exception.cause.lower()) + # Its failure record, if AWS stays busy past the bound, asks nothing. + d = u.explain_failure(busy.exception.cause, "v1.1.0", "v1.0.0", u.PREPARE, retry_at=base.NOW) + self.assertTrue(d["fix"].startswith("Nothing to do: CoderHelm starts it again by itself"), d["fix"]) def test_an_update_whose_rollback_stops_ends_rolled_back_once_recovered(self): self.release(json.loads(base.TEMPLATE)) diff --git a/lambda/tests/test_updater_busy.py b/lambda/tests/test_updater_busy.py index ff15a4288..60bfada55 100644 --- a/lambda/tests/test_updater_busy.py +++ b/lambda/tests/test_updater_busy.py @@ -279,6 +279,37 @@ def test_the_status_route_answers_while_aws_is_busy(self): row = next(h for h in r["history"] if h["id"] == hid) self.assertEqual((row["status"], row["reason"]), ("preparing", "AWS is busy, retrying (attempt 1)")) + def test_a_busy_stack_waits_and_the_update_starts_by_itself(self): + # "AWS is still working on the install's stack; press Update again + # once it has finished": now a wait, tried again by itself. + self.cfn.stack_status = "UPDATE_IN_PROGRESS" + r = u.handle({"action": "update_now", "version": "v1.1.0", "actor": ADMIN}, ROLE_ENV, self.store, NOW, + fetch=lambda repo: [], probe=lambda env, p: {"results": []}) + self.assertEqual(r["request"]["status"], "waiting") + self.assertTrue(no_press(r["request"]["waiting_for"])) + later = NOW + u.BUSY_LIMIT + timedelta(minutes=1) + req = u.follow_request(self.store, ROLE_ENV, later) + row = self.store.get(req["failed_id"]) + self.assertIn("still working on the install's stack", row["summary"]) + self.assertTrue(row["fix"].startswith("Nothing to do: CoderHelm starts it again by itself"), row["fix"]) + self.assertTrue(no_press(row["reason"])) + self.cfn.stack_status = "UPDATE_COMPLETE" + req = u.follow_request(self.store, ROLE_ENV, later + u.BUSY_RETRY_AFTER) + self.assertEqual(req["status"], "started") + + def test_an_update_rolled_back_for_throttling_starts_again_by_itself(self): + hid = self.prepared() + later = NOW + timedelta(minutes=20) + u.native_finish(self.store, ROLE_ENV, later, hid, "rolled_back", + "Resource handler returned message: Rate exceeded (Service: Lambda, Status Code: 429)") + row = self.store.get(hid) + at = later + u.BUSY_RETRY_AFTER + self.assertEqual(row["retry_at"], at.isoformat()) + self.assertEqual(row["fix"], f"Nothing to do: CoderHelm starts it again by itself at {at.strftime('%H:%M')} UTC.") + self.assertTrue(no_press(row["reason"])) + req = self.store.get("UPDATE_REQUEST") + self.assertEqual((req["status"], req["version"], req["failed_id"]), ("waiting", "v1.1.0", hid)) + def test_no_throttling_message_hands_the_retry_to_a_person(self): raw = "ClientError: An error occurred (Throttling) when calling the DescribeChangeSet operation: Rate exceeded" for phase in (u.PREPARE, u.ROLLED_BACK): diff --git a/lambda/updater/handler.py b/lambda/updater/handler.py index 96e0dd0a7..bb6462a25 100644 --- a/lambda/updater/handler.py +++ b/lambda/updater/handler.py @@ -545,6 +545,27 @@ def busy_why(e): return f"{type(e).__name__}: {str(e)[:250]}" +STACK_BUSY = "AWS is still working on the install's stack" + + +def stack_busy_why(st): + """What a stack that can't take a change yet says, for the update's wait + and its failure record: still working, or finishing an earlier rollback + (which CoderHelm finishes by itself).""" + if st == STUCK: + return f"{STACK_BUSY} ({st}): CoderHelm is finishing an earlier update's rollback by itself" + return f"{STACK_BUSY} ({st})" + + +def busy_text(raw): + """True when `raw` (an error's text) says AWS turned calls away for being + busy, or its stack was still working: never the release, and never a + person's job to press again.""" + low = (raw or "").lower() + return ("rate exceeded" in low or "throttl" in low or "too many requests" in low + or STACK_BUSY.lower() in low or throttled(Exception(raw or ""))) + + def retry_time(at): if isinstance(at, str): try: @@ -2563,11 +2584,15 @@ def native_propose(store, env, version, mode, extra=None, cfn=None, opener=None) raise ValueError(f"{version} is not a version this install ran before, so it can't be rolled back to") stack = cfn.describe_stacks(StackName=env["NATIVE_STACK"])["Stacks"][0] st = stack.get("StackStatus") or "" + if (st == STUCK or st.endswith("_IN_PROGRESS")) and mode == "update": + # Not a refusal: a wait like AWS throttling, tried again by itself + # (busy_request) until the stack is free. + raise AwsBusy(stack_busy_why(st)) if st == STUCK: raise ValueError("the install's stack is still stuck after an earlier update's rollback stopped; CoderHelm finishes " - "that rollback by itself (Settings, System says how far it is), then press Update again") + "that rollback by itself first (Settings, System says how far it is)") if st.endswith("_IN_PROGRESS"): - raise ValueError(f"AWS is still working on the install's stack ({st}); press Update again once it has finished") + raise ValueError(f"AWS is still working on the install's stack ({st}); this change can start once it has finished") overrides = {} if mode == "domain" and extra: attach = extra.get("DOMAIN_ACTION") != "remove" @@ -5867,15 +5892,23 @@ def _cause(raw, access=None, phase=None, retry_at=None): if m or "accessdenied" in low or "access denied" in low: return ("CoderHelm's update role isn't allowed to do something this release needs", _NEXT_RELEASE + " If that one fails the same way, send the technical details to CoderHelm support.") - if "rate exceeded" in low or "throttl" in low or "too many requests" in low or throttled(Exception(text)): + if STACK_BUSY.lower() in low: + # The stack was still busy for the whole wait: tried again by itself. + what = f"AWS was still working on the install's stack for {int(BUSY_LIMIT.total_seconds() // 60)} minutes while CoderHelm waited" + if retry_at: + return (what, f"Nothing to do: CoderHelm starts it again by itself {retry_time(retry_at)}.") + return (what, "It wasn't the release or the install: run the same change again once the stack has finished.") + if busy_text(text): # Never the release, and never a person's job to press again. if phase == PREPARE: what = f"AWS was busy and kept turning calls away for {int(BUSY_LIMIT.total_seconds() // 60)} minutes while CoderHelm retried" - if retry_at: - return (what, f"Nothing to do: CoderHelm starts it again by itself {retry_time(retry_at)}.") - return (what, "It wasn't the release or the install: try it again once AWS is less busy, in a few minutes.") - return ("AWS was busy and turned some calls away", - "It wasn't the release or the install: try it again once AWS is less busy, in a few minutes.") + else: + what = "AWS was busy and turned some calls away" + if retry_at: + return (what, f"Nothing to do: CoderHelm starts it again by itself {retry_time(retry_at)}.") + # Only a rollback or a switch a person started ends here (an update + # always gets its own retry: native_finish, busy_request). + return (what, "It wasn't the release or the install: try it again once AWS is less busy, in a few minutes.") if "limitexceeded" in low or "limit exceeded" in low or "quota" in low: return ("your AWS account reached one of its limits", "Raise the limit the technical details name (AWS console, Service Quotas) or remove what you don't use, then press Update again.") @@ -5935,6 +5968,14 @@ def native_finish(store, env, now, hid, status, reason, phase=None): if status != "succeeded": entry = store.get(hid, {}) or {} phase = phase or (ROLLED_BACK if status == "rolled_back" else STOPPED) + if phase in (PREPARE, ROLLED_BACK) and not entry.get("retry_at") and busy_text(str(reason or "")): + # AWS turned calls away and the stack is back as it was: the + # update starts again by itself, never a person's press. + at = busy_retry_at(entry, now) + if at: + entry["retry_at"] = at.isoformat() + store.put(hid, entry) + busy_retry_later(store, now, entry, at, hid) access = entry.get("access") denied = deploy_role_denied(reason) if phase != PREPARE else "" if denied or PREFLIGHT_MARK.lower() in str(reason or "").lower(): diff --git a/services/common/src/description_handoff.rs b/services/common/src/description_handoff.rs index 7cdc5b044..73f2f5dea 100644 --- a/services/common/src/description_handoff.rs +++ b/services/common/src/description_handoff.rs @@ -5,11 +5,15 @@ //! corrections for a person to make. The description stayed wrong. //! //! The description is CoderHelm's: after every push it is rebuilt from the -//! branch (`worker::passes::description`). A round has no tool that writes -//! it and needs none, so the round is told that ([`ROUND_NOTE`]) and its -//! account is checked ([`handoffs`]): a sentence that says the description -//! can't be edited, or leaves an edit of it to a person, is taken out -//! ([`scrub`]) and the rebuild runs, whether or not the round pushed code. +//! branch (`worker::passes::description`). Every fix round has the +//! `update_pr_description` tool, with the guard of the description writer: +//! a round CoderHelm started asks for the rebuild through it, and a +//! person's round has their wording applied. The round is told so +//! ([`ROUND_NOTE`]) and its account is checked ([`handoffs`]): a sentence +//! that says the description can't be edited, or leaves an edit of it to a +//! person ("someone needs to paste in the replacement sections"), is taken +//! out ([`scrub`]) and the rebuild runs, whether or not the round pushed +//! code. //! //! The check is narrow on purpose. It reads one sentence at a time and needs //! both the description as the thing edited and either an inability or a @@ -21,12 +25,13 @@ use std::sync::OnceLock; use regex::Regex; /// What every fix round is told about the description. -pub const ROUND_NOTE: &str = "The pull request's description is kept by CoderHelm: right after \ +pub const ROUND_NOTE: &str = "The pull request's description is kept by CoderHelm: after \ this round it is rebuilt from the branch as it stands (the versions the lockfile resolves, \ - the counts, the changes, the verification and the open items). You have no tool that writes \ - it and need none. When a finding says the description is wrong, fix what is wrong in the \ - code if anything is, and say in your account which statement was wrong; never write that \ - you cannot edit the description, and never leave an edit of it to a person."; + the counts, the changes, the verification and the open items). When a finding says the \ + description is wrong, fix what is wrong in the code if anything is, then call \ + `update_pr_description` with which statement is wrong: CoderHelm rebuilds the description \ + from the branch when the round ends. Never write that you cannot edit the description, and \ + never leave an edit of it to a person."; /// What replaces a handed-off edit in a round's account. pub const REBUILT: &str = @@ -40,6 +45,9 @@ const EDIT: &str = r"(?:edit|update|change|modify|rewrite|fix|correct|amend|touc const EDITED: &str = r"(?:edited|updated|changed|modified|rewritten|fixed|corrected|amended|adjusted|revised)"; const CANNOT: &str = r"(?:can't|cannot|can not|couldn't|could not|won't be able to|am unable to|was unable to|unable to|am not able to|not able to|have no way to|no way to|don't have (?:a |the |any )?(?:way|tool|tools|access|permission|permissions|ability) to|do not have (?:a |the |any )?(?:way|tool|tools|access|permission|permissions|ability) to|have no (?:tool|tools|access|permission|ability) to|lack (?:a |the )?(?:tool|tools|access|permission|ability) to)"; +/// "I have no tool that edits the PR description": the tool named by what it +/// does, not "to edit". +const NO_TOOL_THAT: &str = r"(?:have no|don't have (?:a|any)|do not have (?:a|any)|there is no|there's no|lack (?:a|any)) (?:tool|tools|way) (?:that|which|to) (?:edits?|updates?|changes?|writes?|rewrites?|modif(?:y|ies))"; const PERSON: &str = r"(?:you|someone|somebody|a person|a human|a maintainer|the maintainer|the author|a reviewer|the reviewer|the team|a teammate)"; fn patterns() -> &'static [Regex] { @@ -58,6 +66,10 @@ fn patterns() -> &'static [Regex] { r"(?i)\b(?:description|pr body|pull request body)\b[^.;!?]{0,60}?\b(?:needs?|requires?|will need|still needs?) (?:a |to be )?(?:manual|manually|hand|human)".to_string(), // "The description must be updated by hand." format!(r"(?i)\b(?:description|pr body|pull request body)\b[^.;!?]{{0,60}}?\b{EDITED} (?:by hand|manually|by a person|by someone|by a maintainer|by the author)"), + // "I have no tool that edits the PR description." + format!(r"(?i)\b{NO_TOOL_THAT}\s+(?:{OBJECT}|{IN_OBJECT})"), + // "Someone needs to paste in the replacement sections below." + format!(r"(?i)\b{PERSON}(?:'ll| will| would| should| must| may| can)?(?: need to| needs to| have to| has to)?\s+(?:please\s+)?(?:manually\s+)?(?:paste|copy)\b[^.;!?]{{0,40}}?\b(?:section|sections|text|replacement|description|body)"), // "I left the description corrections for you." format!(r"(?i)\b(?:left|leave|leaving)\b[^.;!?]{{0,50}}?\b(?:description|pr body|pull request body)\b[^.;!?]{{0,50}}?\b(?:for|to) {PERSON}"), ] @@ -156,6 +168,8 @@ mod tests { "I left the description corrections for the author.", "Someone should fix the headline in the PR body.", "I can\u{2019}t edit the PR description from here.", + "I have no tool that edits the PR description, so someone needs to paste in the replacement sections below.", + "Someone needs to paste in the replacement sections below.", ] { assert_eq!(handoffs(s), vec![s.to_string()], "{s}"); } diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index abd934fb7..672413887 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -380,6 +380,8 @@ pub mod run_round; pub mod run_status; /// What a run waiting on a person is waiting for: never nothing. pub mod run_wait; +/// A run that waits on a person goes on by itself when the input arrives. +pub mod run_wake; /// Proof that a repository builds and starts after its dependencies change: /// what to run (found in its CI and manifests), the sandbox script, and what /// the bumps are blamed for. diff --git a/services/common/src/live/permissions.rs b/services/common/src/live/permissions.rs index a0c107f89..d29385c45 100644 --- a/services/common/src/live/permissions.rs +++ b/services/common/src/live/permissions.rs @@ -269,7 +269,9 @@ impl PermissionCheck { } else { format!("The update stack {stack} failed in AWS ({status}: {reason}).") }, - fix: "Open the stack's Events tab for the cause, delete the failed stack, then press Update again.".into(), + // CoderHelm's role in the account only reads: it can't delete + // or create a stack there, so one AWS admin action is named. + fix: stack_failed_fix(status, &stack, a, &self.region), }), UpdateStack::Found { status, .. } if status.ends_with("_IN_PROGRESS") => Some(Problem { code: "stack_in_progress", @@ -410,6 +412,39 @@ fn failed(status: &str) -> bool { status.contains("FAILED") || status.contains("ROLLBACK") } +/// The one thing an AWS admin does for an update stack left failed in +/// account `account`: a stack that never finished creating +/// (`ROLLBACK_COMPLETE`, `CREATE_FAILED`) is deleted and created again; one +/// whose update rolled back still works and is updated again. CoderHelm's +/// read-only role there can't do either, and this page checks again by +/// itself once the stack is done. +pub fn stack_failed_fix(status: &str, stack: &str, account: &str, region: &str) -> String { + let at = if region.is_empty() { + format!("account {account}") + } else { + format!("account {account} ({region})") + }; + if status == "UPDATE_ROLLBACK_FAILED" { + format!( + "An AWS admin in {at} continues the rollback of the stack {stack} (CloudFormation, \ + Stack actions, Continue update rollback). This page checks again by itself once the \ + stack is back." + ) + } else if status.starts_with("UPDATE_") { + format!( + "An AWS admin in {at} runs this page's one-click update again on the stack {stack}; its \ + Events tab names what failed the last time. This page checks again by itself once \ + the stack reaches UPDATE_COMPLETE." + ) + } else { + format!( + "An AWS admin in {at} deletes the stack {stack} in CloudFormation (its Events tab names \ + what failed) and creates it again with this page's one-click update. This page checks \ + again by itself once the stack reaches CREATE_COMPLETE." + ) + } +} + /// Pure: the simulator's answers folded into a check. pub fn apply_simulation(c: &mut PermissionCheck, results: &[Simulated]) { c.method = "simulate".into(); @@ -972,6 +1007,25 @@ mod tests { let p = c.problem(true).unwrap(); assert_eq!(p.code, "stack_failed"); assert!(p.message.contains("cannot be found")); + // One action for an AWS admin, never "press Update again". + assert!( + p.fix.starts_with("An AWS admin in account 111122223333"), + "{}", + p.fix + ); + assert!(p.fix.contains("deletes the stack"), "{}", p.fix); + assert!(!p.fix.to_lowercase().contains("press update"), "{}", p.fix); + assert_eq!(crate::rendered::person_text(&p.fix), None, "{}", p.fix); + for status in ["UPDATE_ROLLBACK_COMPLETE", "UPDATE_ROLLBACK_FAILED"] { + let f = stack_failed_fix( + status, + "CoderHelmLogReaderUpdate", + "111122223333", + "us-east-1", + ); + assert!(!f.contains("deletes"), "{f}"); + assert_eq!(crate::rendered::person_text(&f), None, "{f}"); + } c.update_stack = UpdateStack::NotFound; assert!(c.problem(false).is_none()); let p = c.problem(true).unwrap(); diff --git a/services/common/src/merged_ticket.rs b/services/common/src/merged_ticket.rs index 985c31a79..cc8b60251 100644 --- a/services/common/src/merged_ticket.rs +++ b/services/common/src/merged_ticket.rs @@ -295,16 +295,18 @@ fn where_when(pr: &MergedPr) -> String { format!("{into}{on}") } -/// How a person runs the ticket anyway. +/// How a person runs the ticket anyway. A reply that asks for work starts +/// the run by itself (the worker reads it: `jira_comment`), with the merge +/// check off for that merge. fn how(source: &TicketSource) -> &'static str { match source { TicketSource::Jira => { - "press Retry on this run in CoderHelm, or reply on the ticket with what is still to \ - do" + "reply on the ticket with what is still to do (a reply that asks for work starts the \ + run by itself), or press Retry on this run in CoderHelm" } _ => { - "press Retry on this run in CoderHelm, or mention @coderhelm on the issue with what \ - is still to do" + "mention @coderhelm on the issue with what is still to do (that comment starts the \ + run by itself), or press Retry on this run in CoderHelm" } } } @@ -432,15 +434,17 @@ pub fn replace_note(instructions: &str, carried: Option<&str>, fresh: Option<&st with_note(&base, fresh) } -/// What the run's wait asks for. +/// What the run's wait asks for: a reply is the answer, and the waiting +/// run goes on by itself when it arrives (`run_wake`). pub fn wait_action(source: &TicketSource) -> &'static str { match source { TicketSource::Jira => { - "Press Retry to run the ticket anyway, or reply on the ticket with what is still to do" + "Reply on the ticket with what is still to do, or that it should be built anyway; the \ + run continues by itself when the reply arrives" } _ => { - "Press Retry to run the issue anyway, or mention @coderhelm on the issue with what is \ - still to do" + "Comment on the issue with what is still to do, or that it should be built anyway; \ + the run continues by itself when the comment arrives" } } } @@ -774,7 +778,10 @@ mod tests { "{jira}" ); assert!(jira.contains("press Retry on this run"), "{jira}"); - assert!(jira.contains("reply on the ticket"), "{jira}"); + assert!( + jira.contains("reply on the ticket with what is still to do (a reply that asks for work starts the run by itself)"), + "{jira}" + ); assert!(!jira.contains("reopen"), "{jira}"); let bare = MergedPr { base: String::new(), @@ -820,7 +827,12 @@ mod tests { let part = partial_note(&both, "They add the index.", &["the CSV export".into()]); assert!(part.contains("acme/app#30 merged into `develop` on 2026-11-10, after acme/app#12, and together they already do part of this ticket: They add the index."), "{part}"); assert!(part.contains("adds to acme/app#30."), "{part}"); - assert!(wait_action(&TicketSource::Github).contains("mention @coderhelm")); - assert!(wait_action(&TicketSource::Jira).contains("reply on the ticket")); + assert!(wait_action(&TicketSource::Github).contains("Comment on the issue")); + assert!(wait_action(&TicketSource::Jira).starts_with("Reply on the ticket")); + for s in [TicketSource::Jira, TicketSource::Github] { + let a = wait_action(&s); + assert!(a.contains("the run continues by itself"), "{a}"); + assert_eq!(crate::rendered::person_text(a), None, "{a}"); + } } } diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 0d8d6e0a1..ca92be404 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -387,6 +387,17 @@ pub struct JiraCommentMessage { pub context_hash: String, #[serde(default)] pub action: Option>, + /// The ticket's run waits on a person and a comment answers its wait + /// (`run_wake::wakes`): the comment resumes it, whatever its words, + /// unless it only reports status or says the work is done elsewhere. + /// `None` from a gateway that didn't say: a `needs_input` or `failed` + /// run is then taken as waiting for the answer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resumes: Option, + /// What the waiting run asked for (its wait's action), so the comment + /// is read as the answer to it. + #[serde(default)] + pub waiting_for: String, } /// A lesson job (gateway on a closed PR, or the feedback pass on a comment). diff --git a/services/common/src/person_gate.rs b/services/common/src/person_gate.rs index 352cc2633..dcb6f0ba5 100644 --- a/services/common/src/person_gate.rs +++ b/services/common/src/person_gate.rs @@ -511,13 +511,29 @@ fn asks_testing(a: &Ask) -> bool { } /// Whether the item's action is adding labels to a pull request. -fn adds_labels(a: &Ask) -> bool { +/// CoderHelm adds labels itself through the issues API, whatever workflow a +/// label starts (a preview deploy, an end-to-end run): a label that starts +/// a deploy needs no deploy permission. Only a label that releases to +/// production stays the team's call. +pub fn adds_labels(a: &Ask) -> bool { let t = one_line(&a.text).to_lowercase(); let t = t .trim_start_matches("after merging: ") .trim_start_matches("before merging: "); - (t.starts_with("add pr label") || t.starts_with("add labels") || t.starts_with("add the label")) - && !t.contains("deploy") + [ + "add pr label", + "add labels", + "add label", + "add the label", + "add the pr label", + "apply the label", + "apply labels", + "label the pr", + "label the pull request", + ] + .iter() + .any(|p| t.starts_with(p)) + && !t.contains("production") } /// Whether the item's action is a deploy: its words start with one, or the diff --git a/services/common/src/pr_steps.rs b/services/common/src/pr_steps.rs index 81f4447cf..f84293059 100644 --- a/services/common/src/pr_steps.rs +++ b/services/common/src/pr_steps.rs @@ -171,6 +171,32 @@ pub fn is_command(how: &str) -> bool { .contains(&first) } +/// `unblock` as the one way to let CoderHelm: an alternative that hands the +/// step back to the reader ("..., or run the command yourself", "or a +/// person runs the command") is taken out. The step's line already says +/// what to run; the unblock is what lets CoderHelm run it. +pub fn one_way(unblock: &str) -> String { + let t = one_line(unblock); + let low = t.to_lowercase(); + let cut = [ + ", or run the command yourself", + " or run the command yourself", + ", or run it yourself", + " or run it yourself", + ", or a person runs the command", + " or a person runs the command", + ", or do it yourself", + " or do it yourself", + ] + .iter() + .filter_map(|p| low.find(p)) + .min(); + match cut { + Some(i) => t[..i].trim_end_matches([',', ';', ' ']).to_string(), + None => t, + } +} + /// `text` without the names of CoderHelm's own tools. pub fn plain(text: &str) -> String { let mut t = one_line(text); @@ -197,7 +223,8 @@ pub fn plain_error(raw: &str) -> (String, String) { return match crate::github_grants::Denial::from_error("POST", raw, "actions", "write") { Some(d) => ( d.line(), - "an organization owner accepts Actions: write for the app once for the install, or a person runs the command".into(), + "an organization owner accepts Actions: write for the app once for the install" + .into(), ), None => ( crate::github_grants::install_item( @@ -374,7 +401,10 @@ impl Step { sentence_part(cause) ); if !unblock.trim().is_empty() { - t.push_str(&format!(" To let it: {}.", sentence_part(unblock))); + t.push_str(&format!( + " To let it: {}.", + sentence_part(&one_way(unblock)) + )); } t } @@ -389,7 +419,10 @@ impl Step { // "none: ..." is a reason there is no way, not a way. if !unblock.trim().is_empty() && !unblock.trim().to_lowercase().starts_with("none") { - t.push_str(&format!(" To let it: {}.", sentence_part(&plain(unblock)))); + t.push_str(&format!( + " To let it: {}.", + sentence_part(&plain(&one_way(unblock))) + )); } t } @@ -550,7 +583,7 @@ mod tests { let failed = deploy(State::Failed { cause, unblock }); assert_eq!( failed.line(), - "After merging: Deploy the staging admin app: run `cd apps/admin && npm run deploy:staging`. CoderHelm could not: GitHub answered 403 to `POST /repos/acme/site/actions/workflows/test.yml/dispatches`: the GitHub App needs Actions: write. To let it: an organization owner accepts Actions: write for the app once for the install, or a person runs the command." + "After merging: Deploy the staging admin app: run `cd apps/admin && npm run deploy:staging`. CoderHelm could not: GitHub answered 403 to `POST /repos/acme/site/actions/workflows/test.yml/dispatches`: the GitHub App needs Actions: write. To let it: an organization owner accepts Actions: write for the app once for the install." ); let done = deploy(State::Done { evidence: "the deploy workflow passed".into(), diff --git a/services/common/src/rendered.rs b/services/common/src/rendered.rs index 2b8a8fda1..e95e51cee 100644 --- a/services/common/src/rendered.rs +++ b/services/common/src/rendered.rs @@ -112,6 +112,41 @@ const HANDOFFS: &[(&str, &str)] = &[ ("follow the runbook", "names no one action"), ("update link", "a link the reader has to find"), ("set the repo and re-run", "names no place to do it"), + ( + "and re-run", + "the run starts by itself once the change is made", + ), + ("put it right", "names no one action"), + ( + "press update again", + "the updater tries again by itself, or names an AWS admin's one action", + ), + ( + "delete the failed stack, then", + "one action for an AWS admin, never a chore list", + ), + ("add pr label", "CoderHelm adds labels itself"), + ( + "no tool that edits", + "the description is CoderHelm's to rebuild", + ), + ( + "paste in the replacement", + "the description is CoderHelm's to rebuild", + ), +]; + +/// Words written for the coding model, never for a person: CoderHelm's own +/// tool arguments and the model's evidence lines. A refusal the coder reads +/// ("Put it back with `restore_file` (omit `from_ref`)") is said to a person +/// as what is wrong, never as the instruction (`habits_check::fixing_note`). +const MODEL_FACING: &[(&str, &str)] = &[ + ("(omit code)", "a tool's argument"), + ("in your evidence", "an instruction to the coding model"), + ( + "put it back with code", + "a tool call the coding model makes", + ), ]; /// A raw internal name a reader can't use: a bracketed snake_case key @@ -143,6 +178,11 @@ pub fn person_text(text: &str) -> Option { return Some(format!("a hand-off (\"{p}\": {why}): {body}")); } } + for (p, why) in MODEL_FACING { + if low.contains(p) { + return Some(format!("words for the model (\"{p}\": {why}): {body}")); + } + } if body.contains("(s)") { return Some(format!("a template plural: {body}")); } @@ -270,6 +310,38 @@ mod tests { } } + /// The texts the second sweep found, each held here so it can't come + /// back: a wait that ends in "then press Retry" or names no action, a + /// note that quotes the coding model's instructions, a hand-off of + /// labels or of the description, and the updater's "press Update + /// again". + #[test] + fn the_second_sweeps_texts_are_caught() { + for bad in [ + "Look at what stopped the run, put it right, then press Retry", + "Give CoderHelm the access the run needs, then press Retry", + "If the work belongs in a different repo, set the repo and re-run.", + "This ticket is for acme/bookstore-docs. Turn it on in Repositories and re-run.", + "Tests and scope check found 1 item, fixing: `package.json` was changed and is no task of the plan. Put it back with `restore_file` (omit `from_ref`), or say why in your Evidence.", + "I have no tool that edits the PR description, so someone needs to paste in the replacement sections below.", + "1. Add PR labels e2e:checkout and CI:E2E, sending the existing labels too.", + "Give the app Actions: write (GitHub, Settings), or run the command yourself.", + "AWS is still working on the install's stack; press Update again once it has finished.", + "Open the stack's Events tab for the cause, delete the failed stack, then press Update again.", + ] { + assert!(person_text(bad).is_some(), "{bad}"); + } + for ok in [ + "Write the product decision in a comment on the ticket; the run continues by itself when the comment arrives", + "Decide whether the run goes on: press Retry on the run in CoderHelm to start it again, or leave it stopped", + "Tests and scope check found 1 item; CoderHelm is fixing it now. `package.json` was changed and is no task of the plan.", + "Nothing to do: CoderHelm starts it again by itself at 14:30 UTC.", + "An AWS admin in account 111122223333 deletes the stack CoderHelmLogReaderUpdate in CloudFormation and creates it again with this page's one-click update.", + ] { + assert_eq!(person_text(ok), None, "{ok}"); + } + } + #[test] fn clipping_never_cuts_a_word() { let title = "Show the gift wrap option on every order in the checkout summary"; diff --git a/services/common/src/run_fail.rs b/services/common/src/run_fail.rs index b3cd37b61..63c02973c 100644 --- a/services/common/src/run_fail.rs +++ b/services/common/src/run_fail.rs @@ -173,7 +173,7 @@ pub fn update(run_id: &str, f: &RunFailure<'_>, now: &str) -> Update { let wait = crate::run_wait::WaitingOn::action(&needs.action, &needs.detail, "") .unwrap_or_else(|| { crate::run_wait::WaitingOn::fixed( - "Look at what stopped the run, then press Retry", + "Put right what the error below names, then say so in a comment on the ticket; the run continues by itself when the comment arrives", &needs.detail, "", ) diff --git a/services/common/src/run_recovery.rs b/services/common/src/run_recovery.rs index d740b6228..d18c04faa 100644 --- a/services/common/src/run_recovery.rs +++ b/services/common/src/run_recovery.rs @@ -731,7 +731,9 @@ pub enum Next { #[derive(Debug, Clone, PartialEq, Eq)] pub struct NeedsYou { pub why: HumanOnly, - /// One action ("Restore the branch `main` in acme/site, then press Retry"). + /// One action, ending in how the run goes on by itself ("Restore the + /// branch `main` in acme/site, then say so in a comment on the ticket; + /// the run continues by itself when the comment arrives": `run_wake`). pub action: String, /// Why, in plain words. pub detail: String, @@ -757,7 +759,9 @@ pub fn next(c: &Classified, ledger: &Ledger, mark: &str) -> Next { Next::NeedsYou(NeedsYou { kind: c.kind, why: HumanOnly::Unrepaired, - action: "Press Retry once the service is answering again".into(), + action: crate::run_wake::by_comment( + "Check that the service the error below names answers again", + ), detail: format!( "{} CoderHelm tried again {repeats} times with longer waits each time and \ it still didn't answer.", @@ -809,7 +813,7 @@ pub fn unknown_stop(c: &Classified, retries: usize) -> NeedsYou { NeedsYou { kind: c.kind, why: HumanOnly::Unrepaired, - action: "Look at what stopped the run, put it right, then press Retry".into(), + action: unrepaired_action(), detail: format!( "CoderHelm met an error it doesn't know how to repair, {tried}: {}", c.plain @@ -830,27 +834,51 @@ pub fn usage_limit(reason: &str) -> NeedsYou { needs_person(&c) } +/// The action for an error CoderHelm couldn't get past by itself: the one +/// thing the error names, put right by a person, and how the run goes on. +fn unrepaired_action() -> String { + crate::run_wake::by_comment( + "Put right what the error below names (CoderHelm can't change it from the run)", + ) +} + +/// What a person does for a wait on `why`, and how the run goes on: by +/// itself, when what it waits for arrives (`run_wake`). Only an approval and +/// a person's own stop of the run are decisions the run waits for where +/// they are made. +pub fn person_action(why: HumanOnly) -> String { + use crate::run_wake::by_comment; + match why { + HumanOnly::Credential => by_comment("Add the credential the error below names"), + HumanOnly::MissingAccess => "Give the CoderHelm GitHub app the access the error below \ + names (on GitHub: Settings, Installed GitHub Apps, CoderHelm, Repository access); the run \ + continues by itself once GitHub reports the access, or when a comment on the \ + ticket says it is given" + .to_string(), + HumanOnly::ProductDecision => "Write the product decision in a comment on the ticket; \ + the run continues by itself when the comment arrives" + .to_string(), + HumanOnly::AmbiguousTicket => "Say in a comment on the ticket which reading is meant; \ + the run continues by itself when the comment arrives" + .to_string(), + HumanOnly::HeldByAnother => by_comment("Finish or hand over the other work on this ticket"), + HumanOnly::UsageLimit => "Raise or clear the team's usage limit in Settings; the run \ + continues by itself once the new limit is saved and allows it" + .to_string(), + HumanOnly::Approval => "Answer the approval the team's agent policy asks for".to_string(), + HumanOnly::PersonAction => "Decide whether the run goes on: press Retry on the run in \ + CoderHelm to start it again, or leave it stopped" + .to_string(), + HumanOnly::Unrepaired => unrepaired_action(), + } +} + fn needs_person(c: &Classified) -> NeedsYou { let why = c.person.unwrap_or(HumanOnly::Unrepaired); - let action = match why { - HumanOnly::Credential => "Add the credential the run needs, then press Retry", - HumanOnly::MissingAccess => "Give CoderHelm the access the run needs, then press Retry", - HumanOnly::ProductDecision => "Make the product decision on the ticket, then press Retry", - HumanOnly::AmbiguousTicket => "Say on the ticket which reading is meant, then press Retry", - HumanOnly::HeldByAnother => { - "Finish or hand over the other work on this ticket, then press Retry" - } - HumanOnly::UsageLimit => { - "Raise or clear the team's usage limit in Settings, then press Retry" - } - HumanOnly::Approval => "Answer the approval the team's agent policy asks for", - HumanOnly::PersonAction => "Look at the run's last action, then press Retry", - HumanOnly::Unrepaired => "Look at what stopped the run, put it right, then press Retry", - }; NeedsYou { kind: c.kind, why, - action: action.into(), + action: person_action(why), detail: c.plain.clone(), } } @@ -862,28 +890,28 @@ fn unrepaired(c: &Classified, repair: &Repair, tried: usize) -> NeedsYou { repo, base, head, - } if head.is_empty() && !base.is_empty() => format!( - "Restore the branch `{base}` in {owner}/{repo} or set the repository's default branch, \ - then press Retry" + } if head.is_empty() && !base.is_empty() => crate::run_wake::by_comment(&format!( + "Restore the branch `{base}` in {owner}/{repo}, or set the repository's default \ + branch on GitHub" + )), + Repair::MissingRef { owner, repo, .. } if !owner.is_empty() => crate::run_wake::by_comment( + &format!("Restore the branch the error below names in {owner}/{repo} on GitHub"), ), Repair::MissingRef { .. } => { - "Check the run's branches on GitHub, then press Retry".to_string() - } - Repair::BranchBehind { .. } => { - "Resolve the conflicts with the base branch on the pull request, then press Retry" - .to_string() - } - Repair::ClosedOwnPr { .. } => { - "Reopen the pull request, or press Retry to start a new one".to_string() - } - Repair::MissingLabel { name, .. } => { - format!("Create the label `{name}` in the repository, then press Retry") - } - Repair::ExpiredToken => { - "Check the CoderHelm GitHub app's installation (reinstall it if it was removed), then \ - press Retry" - .to_string() + crate::run_wake::by_comment("Restore the branch the error below names on GitHub") } + Repair::BranchBehind { .. } => crate::run_wake::by_comment( + "Resolve the conflicts with the base branch on the pull request", + ), + Repair::ClosedOwnPr { .. } => "Decide whether the work goes on: reopen the pull request \ + on GitHub to go on with it, or press Retry on the run in CoderHelm to start a new one" + .to_string(), + Repair::MissingLabel { name, .. } => crate::run_wake::by_comment(&format!( + "Create the label `{name}` in the repository (GitHub, Issues, Labels)" + )), + Repair::ExpiredToken => "Install the CoderHelm GitHub app again on GitHub if it was \ + removed or suspended; the run continues by itself once GitHub reports the install" + .to_string(), }; NeedsYou { kind: c.kind, diff --git a/services/common/src/run_wake.rs b/services/common/src/run_wake.rs new file mode 100644 index 000000000..76b585e8a --- /dev/null +++ b/services/common/src/run_wake.rs @@ -0,0 +1,142 @@ +//! A run that waits on a person goes on by itself once the person's input +//! arrives. +//! +//! A run that stopped for a person used to say "... then press Retry", and +//! a comment on its ticket was only kept as context for some later run. The +//! person answered and the run went on waiting. Now what the run waits for +//! wakes it, the way a person's Retry would (`POST /api/runs/{id}/retry`): +//! +//! - [`Wake::Comment`]: a person's comment or reply on the run's ticket +//! (a Jira comment, or a comment on the GitHub issue); +//! - [`Wake::Access`]: GitHub reports access granted to the CoderHelm app +//! (a repository added to its installation, a permission accepted, the +//! app installed again); +//! - [`Wake::Limit`]: the team's usage limit raised or cleared so runs may +//! start again. +//! +//! Every wait names one of these in its action ([`CONTINUES`]), so what a +//! person reads is what happens. Only a decision a person makes about the +//! run itself (an approval its policy asks for) waits for that decision, +//! where it is made. + +use crate::handback::HumanOnly; + +/// What a waiting run's action ends with: the run goes on by itself. +pub const CONTINUES: &str = "the run continues by itself when the comment arrives"; + +/// The action of a wait a comment on the ticket answers: `what` a person +/// does, then that a comment says so, then that the run goes on by itself. +pub fn by_comment(what: &str) -> String { + format!( + "{}, then say so in a comment on the ticket; {CONTINUES}", + what.trim().trim_end_matches('.') + ) +} + +/// What wakes a waiting run. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Wake { + /// A person's comment or reply on the run's ticket. + Comment, + /// Access granted to the CoderHelm GitHub app. + Access, + /// The team's usage limit raised or cleared. + Limit, +} + +/// The status of a run that waits on a person. +pub const WAITING: &str = "needs_input"; + +/// Whether `wake` starts a run that waits on a person for `why` (the wait's +/// `handback`; `None` when the wait names none). A comment answers every +/// wait but the two a comment can't settle: the usage limit (only the +/// setting lifts it) and an approval the team's policy asks for (answered +/// where the policy asks). +pub fn wakes(why: Option, wake: Wake) -> bool { + match wake { + Wake::Comment => !matches!(why, Some(HumanOnly::UsageLimit | HumanOnly::Approval)), + Wake::Access => matches!(why, Some(HumanOnly::MissingAccess | HumanOnly::Credential)), + Wake::Limit => why == Some(HumanOnly::UsageLimit), + } +} + +/// [`wakes`] for a run with `status` whose wait recorded `handback` (its +/// code, `HumanOnly::code`): only a run that waits on a person is woken. +pub fn wakes_run(status: &str, handback: &str, wake: Wake) -> bool { + status == WAITING && wakes(HumanOnly::from_code(handback), wake) +} + +/// Whether a run waiting for access in `repo` (`owner/name`, the run's own; +/// empty when it has none) is the one access granted to `added` repositories +/// wakes: its own repository was added, or its wait names one that was. +/// Access granted without a repository list (a permission accepted, the app +/// installed again) wakes every run waiting for access. +pub fn access_reaches(repo: &str, wait_text: &str, added: &[String]) -> bool { + if added.is_empty() { + return true; + } + let text = wait_text.to_ascii_lowercase(); + added.iter().any(|a| { + let a = a.trim().to_ascii_lowercase(); + !a.is_empty() && (repo.eq_ignore_ascii_case(&a) || text.contains(&a)) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_comment_wakes_every_wait_a_comment_can_answer() { + for why in [ + HumanOnly::ProductDecision, + HumanOnly::AmbiguousTicket, + HumanOnly::Credential, + HumanOnly::MissingAccess, + HumanOnly::HeldByAnother, + HumanOnly::PersonAction, + HumanOnly::Unrepaired, + ] { + assert!(wakes(Some(why), Wake::Comment), "{why:?}"); + } + assert!(wakes(None, Wake::Comment)); + assert!(!wakes(Some(HumanOnly::UsageLimit), Wake::Comment)); + assert!(!wakes(Some(HumanOnly::Approval), Wake::Comment)); + } + + #[test] + fn access_and_the_limit_wake_only_their_own_waits() { + assert!(wakes(Some(HumanOnly::MissingAccess), Wake::Access)); + assert!(wakes(Some(HumanOnly::Credential), Wake::Access)); + assert!(!wakes(Some(HumanOnly::ProductDecision), Wake::Access)); + assert!(wakes(Some(HumanOnly::UsageLimit), Wake::Limit)); + assert!(!wakes(Some(HumanOnly::MissingAccess), Wake::Limit)); + assert!(wakes_run("needs_input", "usage_limit", Wake::Limit)); + assert!(!wakes_run("completed", "usage_limit", Wake::Limit)); + assert!(wakes_run("needs_input", "", Wake::Comment)); + } + + #[test] + fn access_to_a_repository_wakes_the_runs_that_wait_for_it() { + let added = vec!["acme/bookstore-web".to_string()]; + assert!(access_reaches("acme/bookstore-web", "", &added)); + assert!(access_reaches( + "", + "This ticket is for acme/bookstore-web, which isn't connected", + &added + )); + assert!(!access_reaches("acme/bookstore-api", "", &added)); + assert!(access_reaches("acme/bookstore-api", "", &[])); + } + + #[test] + fn the_action_says_the_run_goes_on_by_itself() { + let a = by_comment("Restore the branch `main` in acme/bookstore-web."); + assert_eq!( + a, + "Restore the branch `main` in acme/bookstore-web, then say so in a comment on the \ + ticket; the run continues by itself when the comment arrives" + ); + assert_eq!(crate::rendered::person_text(&a), None, "{a}"); + } +} diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index fd89bbffb..0feadf306 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -975,7 +975,7 @@ pub struct RunWaitingOn { pub action: String, /// Why, or what is still open. May be empty. #[schema( - example = "Open on the pull request: the link check couldn't reach /pricing. Mark it ready once that is dealt with, push a fix or comment on it, and CoderHelm picks it up from there." + example = "Open on the pull request: the link check couldn't reach /pricing. Push a fix or comment on it, and CoderHelm picks it up from there." )] pub detail: String, /// Where to do it (the pull request, the ticket), when known. @@ -2862,6 +2862,29 @@ pub(crate) async fn retry_message( state: &AppState, claims: &Claims, item: &std::collections::HashMap, +) -> Result { + retry_message_as( + state, + &claims.team_id, + claims + .github_login + .clone() + .unwrap_or_else(|| claims.email.clone()), + common::requester::Requester::member(claims.github_login.as_deref(), &claims.email), + item, + ) + .await +} + +/// [`retry_message`] for `team_id`, started for `sender` (who `requester` +/// names): a person's Retry, or CoderHelm itself when what a waiting run +/// waited for arrived (`run_wake`). +pub(crate) async fn retry_message_as( + state: &AppState, + team_id: &str, + sender: String, + requester: Option, + item: &std::collections::HashMap, ) -> Result { let repo = item .get("repo") @@ -2880,7 +2903,7 @@ pub(crate) async fn retry_message( .and_then(|n| n.parse::().ok()) .unwrap_or(0); if installation_id == 0 { - installation_id = get_team_installation_id(state, &claims.team_id).await?; + installation_id = get_team_installation_id(state, team_id).await?; } let issue_number = item .get("issue_number") @@ -2925,7 +2948,7 @@ pub(crate) async fn retry_message( }; Ok(TicketMessage { - team_id: claims.team_id.clone(), + team_id: team_id.to_string(), installation_id, source, ticket_id: ticket_id.to_string(), @@ -2939,14 +2962,8 @@ pub(crate) async fn retry_message( repo_owner: retry_owner, repo_name: retry_name, issue_number, - sender: claims - .github_login - .clone() - .unwrap_or_else(|| claims.email.clone()), - requester: common::requester::Requester::member( - claims.github_login.as_deref(), - &claims.email, - ), + sender, + requester, image_attachments: item .get("image_attachments") .and_then(|v| v.as_s().ok()) @@ -4881,6 +4898,19 @@ pub async fn update_repo( })?; } + // A run that waited for this repository to be turned on goes on by + // itself (`run_wake`). + if enabled { + super::run_wake::wake_team( + &state, + &claims.team_id, + common::run_wake::Wake::Access, + std::slice::from_ref(&repo), + &format!("{repo} was turned on for runs"), + ) + .await; + } + // When enabling a repo, trigger onboarding to generate voice, instructions, etc. if enabled { let installation_id = get_team_installation_id(&state, &claims.team_id).await?; @@ -5968,6 +5998,7 @@ pub async fn update_budget( })?; // Knowledge sources the limit stopped look for room now. super::knowledge_sources::resume_budget_stopped(&state, &claims.team_id).await; + wake_after_limit(&state, &claims.team_id).await; return Ok(StatusCode::OK); } @@ -5991,10 +6022,29 @@ pub async fn update_budget( StatusCode::INTERNAL_SERVER_ERROR })?; super::knowledge_sources::resume_budget_stopped(&state, &claims.team_id).await; + wake_after_limit(&state, &claims.team_id).await; Ok(StatusCode::OK) } +/// The limits were saved: when they now allow runs, the runs that waited +/// for the limit go on by themselves (`run_wake`). +async fn wake_after_limit(state: &AppState, team_id: &str) { + if super::github_webhook::check_run_budget(state, team_id) + .await + .is_none() + { + super::run_wake::wake_team( + state, + team_id, + common::run_wake::Wake::Limit, + &[], + "the team's usage limit allowed runs again", + ) + .await; + } +} + /// GET /api/usage — token usage for the current month + configured limits. #[utoipa::path( get, diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 67fe6870c..efb171bd2 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -428,6 +428,20 @@ async fn route( let team = resolve_team_by_installation(state, installation_id) .await .unwrap_or_default(); + // Access granted on GitHub: the runs that waited for it go on by + // themselves (`run_wake`). + if let Some(added) = super::run_wake::access_granted(event_type, payload) { + if !team.is_empty() && r.is_ok() { + super::run_wake::wake_team( + state, + &team, + common::run_wake::Wake::Access, + &added, + "GitHub reported the access granted", + ) + .await; + } + } d.target = team.clone(); return (r, team); } diff --git a/services/gateway/src/routes/jira_webhook.rs b/services/gateway/src/routes/jira_webhook.rs index a3a0db0b4..58b5cdd31 100644 --- a/services/gateway/src/routes/jira_webhook.rs +++ b/services/gateway/src/routes/jira_webhook.rs @@ -807,6 +807,7 @@ async fn process_jira_payload( ..Default::default() }, ))), + ..Default::default() }); let result = send_to_queue(state, &state.config.ticket_queue_url, &message).await; let repo_display = format!("{}/{}", pr.repo_owner, pr.repo_name); @@ -1430,6 +1431,10 @@ async fn handle_jira_comment( let expected_keys = super::trigger_gate::expected_attachment_keys(team_id, ticket_key, payload); let context_hash = common::ticket_context_hash(&fresh_title, &fresh_body, &expected_keys); + // A run that waits on a person: this comment is the answer, and the run + // it starts takes up the waiting run's plan and branch, as Retry does + // (`run_wake`). + let (resumes, waiting_for) = super::run_wake::comment_wakes(run_item); // What the comment would start if it asks for work: feedback on the // run's PR while that PR is open, otherwise a run with the comment as // added context. The worker reads the comment first and decides. @@ -1479,6 +1484,11 @@ async fn handle_jira_comment( .unwrap_or_default() }, ticket_type: common::messages::ticket_type_of_jira(issue), + resume_from: if resumes { + super::run_wake::resumed_from(run_item) + } else { + None + }, ..Default::default() }) }; @@ -1497,6 +1507,8 @@ async fn handle_jira_comment( comment: comment_body.to_string(), context_hash, action: Some(Box::new(action)), + resumes: Some(resumes), + waiting_for, }); info!( team_id, diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 5d11c1073..21817c6d9 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -97,6 +97,7 @@ pub mod run_outputs; pub mod run_search; pub mod run_start; pub mod run_trigger; +pub mod run_wake; pub mod scorecard; pub mod search; pub mod security; diff --git a/services/gateway/src/routes/run_wake.rs b/services/gateway/src/routes/run_wake.rs new file mode 100644 index 000000000..8e89ade2f --- /dev/null +++ b/services/gateway/src/routes/run_wake.rs @@ -0,0 +1,343 @@ +//! Runs that wait on a person, started again by themselves when what they +//! wait for arrives (`common::run_wake`). +//! +//! - A comment or reply on the ticket: the webhooks send it to the worker +//! with [`comment_wakes`] (the run waits for it) and a ticket run that +//! takes up the waiting run's plan and branch ([`resumed_from`]), the way +//! Retry does. The worker reads the comment and starts that run. +//! - Access granted on GitHub (a repository added to the app's +//! installation, a permission accepted, the app installed again) or a +//! repository turned on for runs: [`wake_team`] with `Wake::Access`. +//! - The team's usage limit raised or cleared: [`wake_team`] with +//! `Wake::Limit`. +//! +//! A woken run is the same start as a person's Retry: the ticket again, +//! with the waiting run's plan and branch when its plan wasn't what stopped +//! it, and the waiting run marked as superseded by the new one. Only a run +//! still waiting is woken (a conditional write), so two events never start +//! two runs. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::run_ending::EndWrite; +use common::run_wait::WaitingOn; +use common::run_wake::{self, Wake}; +use serde_json::Value; +use tracing::{info, warn}; + +use crate::models::WorkerMessage; +use crate::AppState; + +type Item = HashMap; + +fn text<'a>(item: &'a Item, k: &str) -> &'a str { + item.get(k) + .and_then(|v| v.as_s().ok()) + .map(|s| s.as_str()) + .unwrap_or("") +} + +/// Whether a comment on the ticket of the run `item` resumes it, and what +/// the run waits for (its wait's action), for the worker's reading of the +/// comment. +pub fn comment_wakes(item: &Item) -> (bool, String) { + let wait = WaitingOn::of_item(item).unwrap_or_default(); + let resumes = run_wake::wakes_run(text(item, "status"), &wait.handback, Wake::Comment); + (resumes, if resumes { wait.action } else { String::new() }) +} + +/// The run a ticket run started for a waiting run takes up (its plan and +/// branch), as Retry does: unless the plan was what stopped it +/// (`run_status::retry_resumes`). +pub fn resumed_from(item: &Item) -> Option { + let run_id = text(item, "run_id"); + let error = format!("{} {}", text(item, "error_message"), text(item, "error")); + (!run_id.is_empty() && common::run_status::retry_resumes(text(item, "current_pass"), &error)) + .then(|| run_id.to_string()) +} + +/// What GitHub's installation event grants: the repositories added (`Some` +/// with their full names), or access without a list (a permission +/// accepted, the app installed again or unsuspended: `Some` and empty). +/// `None` for an event that grants nothing. +pub fn access_granted(event_type: &str, payload: &Value) -> Option> { + let action = payload["action"].as_str().unwrap_or(""); + match (event_type, action) { + ("installation_repositories", "added") => Some( + payload["repositories_added"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| r["full_name"].as_str().map(str::to_string)) + .collect::>(), + ) + .filter(|v| !v.is_empty()), + ("installation", "created" | "new_permissions_accepted" | "unsuspend") => Some(Vec::new()), + _ => None, + } +} + +/// The waiting runs of a team that `wake` starts again: waiting on a person +/// for what `wake` brings, and (for access) for one of `added` when it +/// names repositories. +pub fn woken<'a>(runs: &'a [Item], wake: Wake, added: &[String]) -> Vec<&'a Item> { + runs.iter() + .filter(|i| { + let wait = WaitingOn::of_item(i).unwrap_or_default(); + run_wake::wakes_run(text(i, "status"), &wait.handback, wake) + && (wake != Wake::Access + || run_wake::access_reaches( + text(i, "repo"), + &format!("{} {}", wait.action, wait.detail), + added, + )) + }) + .collect() +} + +/// Most waiting runs one event starts again. +const MAX_WOKEN: usize = 25; + +/// The team's runs that wait on a person, newest first. +async fn waiting_runs(state: &AppState, team_id: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut start: Option = None; + for _ in 0..10 { + let page = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .index_name("status-index") + .key_condition_expression("team_id = :tid AND begins_with(status_run_id, :p)") + .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":p", AttributeValue::S(format!("{}#", run_wake::WAITING))) + .scan_index_forward(false) + .limit(100) + .set_exclusive_start_key(start.take()) + .send() + .await; + let page = match page { + Ok(p) => p, + Err(e) => { + warn!(team_id, error = %e, "Could not read the team's waiting runs"); + break; + } + }; + out.extend(page.items().iter().cloned()); + match page.last_evaluated_key() { + Some(k) => start = Some(k.clone()), + None => break, + } + } + out +} + +/// Starts again every run of `team_id` that waits for what `wake` brings +/// (`added`: the repositories access was granted to, empty for access +/// without a list). `what`: what arrived, for the waiting run's ending. +/// Returns how many runs were started. +pub async fn wake_team( + state: &AppState, + team_id: &str, + wake: Wake, + added: &[String], + what: &str, +) -> usize { + let runs = waiting_runs(state, team_id).await; + let mut started = 0; + for item in woken(&runs, wake, added).into_iter().take(MAX_WOKEN) { + if wake_one(state, team_id, item, what).await { + started += 1; + } + } + if started > 0 { + info!(team_id, wake = ?wake, started, what, "Waiting runs started again by themselves"); + } + started +} + +/// Starts the waiting run `item` again: its ticket, as a person's Retry +/// would, after the run is marked superseded (only while it still waits). +async fn wake_one(state: &AppState, team_id: &str, item: &Item, what: &str) -> bool { + let run_id = text(item, "run_id").to_string(); + let mut ticket = + match super::api::retry_message_as(state, team_id, "CoderHelm".to_string(), None, item) + .await + { + Ok(t) => t, + Err(_) => { + warn!( + run_id, + "A waiting run's ticket couldn't be read to start it again" + ); + return false; + } + }; + ticket.resume_from = resumed_from(item); + // Only a run still waiting: a second event, or a person's Retry + // meanwhile, already started it. + let ended = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.clone())) + .update_expression("SET #status = :s, status_run_id = :sri, updated_at = :t") + .condition_expression("#status = :waiting") + .expression_attribute_names("#status", "status") + .run_status( + ":s", + &common::run_ending::gate( + &run_id, + &common::run_ending::superseded(&format!( + "the run CoderHelm started by itself when {what}" + )), + ), + ) + .expression_attribute_values(":waiting", AttributeValue::S(run_wake::WAITING.into())) + .expression_attribute_values(":t", AttributeValue::S(chrono::Utc::now().to_rfc3339())) + .send() + .await; + if ended.is_err() { + info!(run_id, "Waiting run already moved on — not started again"); + return false; + } + super::api::delete_ticket_lock(state, team_id, &ticket.ticket_id).await; + let body = match serde_json::to_string(&WorkerMessage::Ticket(ticket)) { + Ok(b) => b, + Err(e) => { + warn!(run_id, error = %e, "Could not serialize the woken run's ticket"); + return false; + } + }; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .send() + .await + { + Ok(_) => { + info!(run_id, what, "Waiting run started again by itself"); + true + } + Err(e) => { + warn!(run_id, error = %e, "Could not queue the woken run's ticket"); + false + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn run(id: &str, status: &str, handback: &str, repo: &str, action: &str) -> Item { + let wait = WaitingOn { + action: action.into(), + handback: handback.into(), + ..Default::default() + }; + HashMap::from([ + ("run_id".to_string(), AttributeValue::S(id.into())), + ("status".to_string(), AttributeValue::S(status.into())), + ("repo".to_string(), AttributeValue::S(repo.into())), + ( + "current_pass".to_string(), + AttributeValue::S("implement".into()), + ), + ( + common::run_wait::FIELD_WAITING_ON.to_string(), + wait.to_attr(), + ), + ]) + } + + #[test] + fn a_comment_resumes_a_run_waiting_on_its_answer() { + let r = run( + "01A", + "needs_input", + "product_decision", + "acme/bookstore-web", + "Write the product decision in a comment on the ticket", + ); + let (resumes, waiting_for) = comment_wakes(&r); + assert!(resumes); + assert!(waiting_for.starts_with("Write the product decision")); + // Retry's rule: the plan and branch are taken up after planning. + assert_eq!(resumed_from(&r).as_deref(), Some("01A")); + let limit = run("01B", "needs_input", "usage_limit", "", "Raise the limit"); + assert_eq!(comment_wakes(&limit), (false, String::new())); + let done = run("01C", "completed", "", "", "x"); + assert!(!comment_wakes(&done).0); + } + + #[test] + fn access_granted_wakes_the_runs_waiting_for_it() { + let runs = vec![ + run( + "01A", + "needs_input", + "missing_access", + "acme/bookstore-web", + "Give access", + ), + run( + "01B", + "needs_input", + "missing_access", + "acme/bookstore-api", + "Give access", + ), + run( + "01C", + "needs_input", + "product_decision", + "acme/bookstore-web", + "Decide", + ), + run( + "01D", + "needs_input", + "usage_limit", + "acme/bookstore-web", + "Raise", + ), + ]; + let added = vec!["acme/bookstore-web".to_string()]; + let ids = |v: Vec<&Item>| { + v.iter() + .map(|i| text(i, "run_id").to_string()) + .collect::>() + }; + assert_eq!(ids(woken(&runs, Wake::Access, &added)), vec!["01A"]); + assert_eq!(ids(woken(&runs, Wake::Access, &[])), vec!["01A", "01B"]); + assert_eq!(ids(woken(&runs, Wake::Limit, &[])), vec!["01D"]); + } + + #[test] + fn githubs_installation_events_say_what_access_they_grant() { + let added = + json!({"action": "added", "repositories_added": [{"full_name": "acme/bookstore-web"}]}); + assert_eq!( + access_granted("installation_repositories", &added), + Some(vec!["acme/bookstore-web".to_string()]) + ); + let removed = json!({"action": "removed", "repositories_removed": [{"full_name": "acme/bookstore-web"}]}); + assert_eq!(access_granted("installation_repositories", &removed), None); + for action in ["created", "new_permissions_accepted", "unsuspend"] { + assert_eq!( + access_granted("installation", &json!({ "action": action })), + Some(vec![]) + ); + } + assert_eq!( + access_granted("installation", &json!({"action": "deleted"})), + None + ); + } +} diff --git a/services/gateway/src/routes/ticket_comments.rs b/services/gateway/src/routes/ticket_comments.rs index 0713f403b..89068f77c 100644 --- a/services/gateway/src/routes/ticket_comments.rs +++ b/services/gateway/src/routes/ticket_comments.rs @@ -159,6 +159,7 @@ pub async fn receive(state: &AppState, inc: &Incoming<'_>) -> Result { @@ -376,7 +377,9 @@ pub async fn on_github_issue_comment( let name = payload["repository"]["name"].as_str().unwrap_or(""); let ticket_id = format!("GH-{number}"); let Some(run) = working_run(state, team_id, &ticket_id).await else { - return false; + // No run works on the issue: one that waits on a person for this + // answer goes on by itself (`run_wake`). + return answer_waiting_run(state, payload, installation_id, team_id, &ticket_id).await; }; if !run.repo.eq_ignore_ascii_case(&format!("{owner}/{name}")) { return false; @@ -431,6 +434,189 @@ pub async fn on_github_issue_comment( .is_ok() } +/// A person's comment on a GitHub issue whose newest run waits on a person +/// for it: kept, and sent to the worker with the issue's run that takes up +/// the waiting run (its plan and branch, as Retry does), so the run goes on +/// by itself. `false` when the issue's newest run doesn't wait for a +/// comment, or the commenter has no standing. +async fn answer_waiting_run( + state: &AppState, + payload: &Value, + installation_id: u64, + team_id: &str, + ticket_id: &str, +) -> bool { + let owner = payload["repository"]["owner"]["login"] + .as_str() + .unwrap_or(""); + let name = payload["repository"]["name"].as_str().unwrap_or(""); + let Some(item) = newest_run(state, team_id, ticket_id, &format!("{owner}/{name}")).await else { + return false; + }; + let (resumes, waiting_for) = super::run_wake::comment_wakes(&item); + if !resumes { + return false; + } + let user = &payload["comment"]["user"]; + let author = user["login"].as_str().unwrap_or(""); + let kind = user["type"].as_str().unwrap_or(""); + let text = payload["comment"]["body"].as_str().unwrap_or(""); + if !tc::is_person(Source::Github, author, kind, text) { + return false; + } + if !super::github_webhook::may_start_work( + state, + team_id, + installation_id, + payload, + &payload["comment"], + "comment", + ) + .await + { + return false; + } + let id = payload["comment"]["id"] + .as_u64() + .map(|i| i.to_string()) + .unwrap_or_default(); + let issue = &payload["issue"]; + let field = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let run_id = field("run_id"); + // Kept as context for the run it starts, which reads the issue's + // comments; the worker reads this one first. + keep( + state, + &Incoming { + team_id, + installation_id, + source: Source::Github, + ticket_id, + comment_id: &id, + author, + author_kind: kind, + text, + ..Default::default() + }, + ) + .await; + let message = WorkerMessage::JiraComment(JiraCommentMessage { + team_id: team_id.to_string(), + installation_id, + ticket_id: ticket_id.to_string(), + title: issue["title"].as_str().unwrap_or("").to_string(), + run_id: run_id.clone(), + run_status: field("status"), + pr_number: 0, + repo_owner: owner.to_string(), + repo_name: name.to_string(), + author: author.to_string(), + comment: text.to_string(), + context_hash: String::new(), + action: Some(Box::new(WorkerMessage::Ticket(answer_run( + team_id, + installation_id, + payload, + super::run_wake::resumed_from(&item), + )))), + resumes: Some(true), + waiting_for, + }); + let body = match serde_json::to_string(&message) { + Ok(b) => b, + Err(e) => { + warn!(error = %e, "Could not serialize the answer to a waiting run"); + return false; + } + }; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .send() + .await + { + Ok(_) => { + info!( + ticket_id, + run_id, "Comment on a waiting run's issue: the run goes on" + ); + true + } + Err(e) => { + warn!(ticket_id, error = %e, "Could not send the answer to a waiting run"); + false + } + } +} + +/// The issue's run an answer to its waiting run starts: the issue as a +/// ticket, its commenter as the one asking, and the waiting run to take up. +pub fn answer_run( + team_id: &str, + installation_id: u64, + payload: &Value, + resume_from: Option, +) -> crate::models::TicketMessage { + let issue = &payload["issue"]; + let repo = &payload["repository"]; + let login = payload["comment"]["user"]["login"].as_str().unwrap_or(""); + crate::models::TicketMessage { + team_id: team_id.to_string(), + installation_id, + source: crate::models::TicketSource::Github, + ticket_id: format!("GH-{}", issue["number"].as_u64().unwrap_or(0)), + title: issue["title"].as_str().unwrap_or("").to_string(), + body: issue["body"].as_str().unwrap_or("").to_string(), + repo_owner: repo["owner"]["login"].as_str().unwrap_or("").to_string(), + repo_name: repo["name"].as_str().unwrap_or("").to_string(), + issue_number: issue["number"].as_u64().unwrap_or(0), + sender: login.to_string(), + requester: common::requester::Requester::github(login), + ticket_type: common::messages::ticket_type_of_github(issue), + resume_from, + ..Default::default() + } +} + +/// The issue's newest run in `repo`, whatever its status. +async fn newest_run( + state: &AppState, + team_id: &str, + ticket_id: &str, + repo: &str, +) -> Option> { + let out = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .index_name("ticket-index") + .key_condition_expression("team_id = :tid AND ticket_id = :ticket") + .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":ticket", AttributeValue::S(ticket_id.to_string())) + .send() + .await + .map_err(|e| warn!(ticket_id, error = %e, "Could not look up the issue's runs")) + .ok()?; + let s = |i: &std::collections::HashMap, k: &str| { + i.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + out.items() + .iter() + .filter(|i| s(i, "repo").eq_ignore_ascii_case(repo)) + .max_by_key(|i| s(i, "run_id")) + .cloned() +} + /// The ticket's run that is working now. struct WorkingRun { run_id: String, diff --git a/services/worker/src/passes/dep_fix.rs b/services/worker/src/passes/dep_fix.rs index 597b2578d..89667f131 100644 --- a/services/worker/src/passes/dep_fix.rs +++ b/services/worker/src/passes/dep_fix.rs @@ -1740,6 +1740,7 @@ pub async fn implement_result( outside_plan: Vec::new(), refused: Vec::new(), owed: Vec::new(), + description_rebuild: false, evidence: super::proof::RunEvidence { notes: run.report_md(), checks: run diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 72017b930..3a7312112 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -2605,8 +2605,10 @@ fn suite_passed(evidence: &[String]) -> bool { .is_some_and(|l| l.starts_with("Full test suite passed")) } -/// The tool a person's comment reaches the PR description through. -fn update_description_tool() -> ToolDefinition { +/// The tool a person's comment reaches the PR description through. A fix +/// round CoderHelm started itself has it too (`implement`): there it asks +/// for the description to be rebuilt from the branch. +pub(crate) fn update_description_tool() -> ToolDefinition { ToolDefinition { name: "update_pr_description".to_string(), description: "Change this pull request's description as the person asked (remove a \ @@ -2632,7 +2634,7 @@ fn update_description_tool() -> ToolDefinition { /// What people asked to change in the PR description this round, and /// whether the person who asked may have it changed. -struct DescriptionRequests { +pub(crate) struct DescriptionRequests { allowed: bool, /// A person triggered the round (false: CoderHelm's own review or a /// follow-up it sent itself). @@ -2648,7 +2650,7 @@ impl DescriptionRequests { Self::for_round(allowed, true) } - fn for_round(allowed: bool, person: bool) -> Self { + pub(crate) fn for_round(allowed: bool, person: bool) -> Self { Self { allowed, person, @@ -2659,12 +2661,12 @@ impl DescriptionRequests { /// The round asked for a rebuild from the branch (no person's words to /// apply). - fn wants_rebuild(&self) -> bool { + pub(crate) fn wants_rebuild(&self) -> bool { self.rebuild.load(std::sync::atomic::Ordering::Relaxed) } /// Records one request and says what happens with it. - fn ask(&self, change: &str) -> String { + pub(crate) fn ask(&self, change: &str) -> String { let change = change.split_whitespace().collect::>().join(" "); if change.is_empty() { return "Say what to change in the description.".to_string(); @@ -4837,7 +4839,9 @@ mod description_request_tests { .contains("never answer that you cannot edit the description")); // The round's instructions and the tool are in every round. let src = include_str!("feedback.rs"); - let run = &src[..src.find("\nfn update_description_tool()").unwrap()]; + let run = &src[..src + .find("\npub(crate) fn update_description_tool()") + .unwrap()]; assert!(run.contains("tools.push(update_description_tool());\n let mut full_system")); assert!(run.contains("common::description_handoff::ROUND_NOTE")); } diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index 5ae036c26..5c24c9a4b 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -878,6 +878,41 @@ pub fn blocking(f: &PrFacts, plan: &PlanResult) -> Vec { out } +/// The run page's note for a fix round on the check's items: what each item +/// is, in a person's words (its first sentence), never the instructions the +/// coding model gets for it (which name CoderHelm's own tools and arguments: +/// "Put it back with `restore_file` (omit `from_ref`)", "say why in your +/// Evidence"). Those stay in [`fix_feedback`]. +pub fn fixing_note(lines: &[String]) -> String { + let items: Vec = lines.iter().map(|l| person_line(l)).collect(); + let n = items.len(); + common::rendered::clip( + &format!( + "Tests and scope check found {}; CoderHelm is fixing {} now. {}", + if n == 1 { + "1 item".to_string() + } else { + format!("{n} items") + }, + if n == 1 { "it" } else { "them" }, + items.join(" ") + ), + 700, + ) +} + +/// One blocking line as a person reads it: its first sentence, which says +/// what is wrong; what follows is the model's instruction. +pub fn person_line(line: &str) -> String { + let first = line + .split(". ") + .next() + .unwrap_or(line) + .trim() + .trim_end_matches('.'); + format!("{first}.") +} + /// The fix round's instructions. pub fn fix_feedback(lines: &[String]) -> String { format!( @@ -1952,17 +1987,7 @@ async fn check_and_fix( }; w.ledger.update(|l| l.habits.start_fix(licence)); w.save_ledger().await; - super::add_progress_note( - w.state, - &w.msg.team_id, - w.run_id, - &format!( - "Tests and scope check found {} item(s), fixing: {}", - blocking.len(), - common::truncate_str(&blocking.join(" "), 600) - ), - ) - .await; + super::add_progress_note(w.state, &w.msg.team_id, w.run_id, &fixing_note(&blocking)).await; let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "implement").await; let fixed = super::implement::run( w.state, diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 36383da83..58b2daec0 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -119,6 +119,10 @@ pub struct ImplementResult { /// counts as cut short, and the round continues in a fresh step that /// runs them first ([`owed_first`]). pub owed: Vec, + /// A fix round asked for the pull request's description to be rebuilt + /// (`update_pr_description`): the round's caller rebuilds it from the + /// branch, whether or not the round pushed code. + pub description_rebuild: bool, } /// The name an owed `run_checks` call carries in [`ImplementResult::owed`]. @@ -717,6 +721,14 @@ pub async fn run( ); tools.push(super::github_history::tool()); full_system.push_str(super::github_history::prompt_line()); + // A fix round on the pull request has the same description tool a + // person's comment round has, with the same guard: a round CoderHelm + // started (no person's wording) gets the description rebuilt from the + // branch, never an edit a person has to paste in. + let description = review_feedback.map(|_| { + tools.push(super::feedback::update_description_tool()); + super::feedback::DescriptionRequests::for_round(false, false) + }); // The code graph: exact structural lookups so the coder (and CI fixes, // which run through here) KNOWS who calls what it's changing. A repo // without a graph yet gets its first build queued here. @@ -939,6 +951,7 @@ pub async fn run( team_id: &msg.team_id, script_repos, script_runs: std::sync::atomic::AtomicUsize::new(0), + description, }; // Attach the ticket's design mockups as images — the implementer must SEE @@ -1376,6 +1389,10 @@ pub async fn run( // A file this round (or the rounds before it) changed and then put // back leaves no commit of its own on the pull request. super::round::fold_churn(github, &msg.repo_owner, &msg.repo_name, branch).await; + let description_rebuild = executor + .description + .as_ref() + .is_some_and(|d| d.wants_rebuild()); // How much the build explored before its first write, and whether it // started from the code map: kept on the run to compare runs with and // without one. @@ -1409,6 +1426,7 @@ pub async fn run( // Run by the settle stage, after the coder. audits: Vec::new(), }, + description_rebuild, }) } @@ -4250,6 +4268,9 @@ struct CombinedWriteToolExecutor<'a> { script_repos: Vec, /// Skill scripts this pass ran. script_runs: std::sync::atomic::AtomicUsize, + /// What a fix round asked of the pull request's description (`None` + /// outside a fix round: there is no description to change yet). + description: Option, } #[async_trait::async_trait] @@ -4261,6 +4282,13 @@ impl<'a> ToolExecutor for CombinedWriteToolExecutor<'a> { ) -> Result> { // Every call counts toward the exploration before the first write. self.write_executor.explore.counter.call(); + if name == "update_pr_description" { + if let Some(d) = &self.description { + return Ok(serde_json::json!( + d.ask(input["change"].as_str().unwrap_or("")) + )); + } + } if name == "bash" { if let Some(out) = self.bash_with_tools(input).await? { return Ok(out); diff --git a/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs b/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs index e003d5e1b..b010ca223 100644 --- a/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs +++ b/services/worker/src/passes/incidents/vo_pass_errors_recover_not_fail.rs @@ -70,7 +70,11 @@ async fn an_unclassified_error_is_tried_once_then_needs_you_never_failed() { assert!(!w.run_to_end(6).await); let n = w.stopped.clone().expect("stopped for a person"); assert_eq!(n.why, common::handback::HumanOnly::Unrepaired); - assert!(n.action.contains("press Retry")); + assert!( + n.action.contains("the run continues by itself"), + "{}", + n.action + ); assert!(n.detail.contains("tried again once")); assert_eq!(rr::classify(odd).kind, Kind::Unknown); // The one failed-status write never writes it as failed. diff --git a/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs b/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs new file mode 100644 index 000000000..157fa61ce --- /dev/null +++ b/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs @@ -0,0 +1,240 @@ +//! wz. The second pass of the same sweep (`wx`) found texts that still +//! handed people work CoderHelm does, or promised what didn't happen. A run +//! stopped for a person said "Look at what stopped the run, put it right, +//! then press Retry", and a comment on its ticket was only kept as context: +//! the person answered and the run went on waiting. A merged-ticket stop +//! said "reply on the ticket" as if a reply started a run. A wrong-repo +//! note said "set the repo and re-run" without saying where, after a reason +//! cut mid-word. A tests-and-scope note quoted the coding model's own +//! instruction ("Put it back with `restore_file` (omit `from_ref`)"). A fix +//! round wrote that it had "no tool that edits the PR description, so +//! someone needs to paste in the replacement sections". An outside-change +//! report asked a person to add pull request labels CoderHelm adds itself, +//! and to "run the command yourself". The updater said "press Update +//! again" when AWS was busy, and the access check said to delete a failed +//! stack and press Update again. +//! +//! Guarantees: a run that waits on a person goes on by itself when what it +//! waits for arrives: a comment or reply on its ticket, access granted on +//! GitHub or a repository turned on, the usage limit raised +//! (`common::run_wake`). Its action names the one thing to do and where, +//! and says so. Notes a person reads never carry the model's instructions. +//! Every fix round can ask for the description to be rebuilt. Labels are +//! CoderHelm's. The updater waits out a busy stack or AWS throttling and +//! starts the update again itself; a failed stack in another account gets +//! one action for an AWS admin. `rendered::person_text` holds each text. + +use common::handback::HumanOnly; +use common::rendered::person_text; +use common::run_recovery::{person_action, unknown_stop, Classified, Kind}; + +const RUN_RECOVERY: &str = include_str!("../../../../common/src/run_recovery.rs"); +const RUN_FAIL: &str = include_str!("../../../../common/src/run_fail.rs"); +const JIRA_WEBHOOK: &str = include_str!("../../../../gateway/src/routes/jira_webhook.rs"); +const TICKET_COMMENTS: &str = include_str!("../../../../gateway/src/routes/ticket_comments.rs"); +const GITHUB_WEBHOOK: &str = include_str!("../../../../gateway/src/routes/github_webhook.rs"); +const API: &str = include_str!("../../../../gateway/src/routes/api.rs"); +const IMPLEMENT: &str = include_str!("../implement.rs"); +const RESUME: &str = include_str!("../resume.rs"); +const PERMISSIONS: &str = include_str!("../../../../common/src/live/permissions.rs"); +const UPDATER: &str = include_str!("../../../../../lambda/updater/handler.py"); + +#[test] +fn a_wait_says_the_run_goes_on_by_itself() { + for why in common::handback::HUMAN_ONLY { + let a = person_action(*why); + assert_eq!(person_text(&a), None, "{why:?}: {a}"); + assert!(!a.contains("then press Retry"), "{why:?}: {a}"); + match why { + // A decision about the run itself, made where it is made. + HumanOnly::Approval | HumanOnly::PersonAction => {} + _ => assert!(a.contains("continues by itself"), "{why:?}: {a}"), + } + } + let odd = Classified { + kind: Kind::Unknown, + repair: None, + person: None, + plain: "The frobnicator answered something nobody expected.".into(), + signature: "s".into(), + }; + let n = unknown_stop(&odd, 1); + assert!(!n.action.contains("put it right"), "{}", n.action); + assert!( + n.action.contains("the run continues by itself"), + "{}", + n.action + ); + for src in [RUN_RECOVERY, RUN_FAIL] { + assert!(!src.contains("then press Retry\"")); + assert!(!src.contains("put it right, then")); + } +} + +#[test] +fn a_comment_on_a_waiting_run_resumes_it() { + use crate::passes::jira_comment::{decide_waiting, Act, ActionKind}; + use common::ticket_state::Intent; + // "Done, I granted the access", "use the second reading", a question + // back: each resumes the run that waits for it. + for intent in [ + None, + Some(Intent::NewRequirement), + Some(Intent::Other), + Some(Intent::Question), + ] { + assert_eq!(decide_waiting(intent, true, ActionKind::Run), Act::Dispatch); + } + // Which runs a comment wakes: the gateway reads the run's wait. + assert!(common::run_wake::wakes_run( + "needs_input", + HumanOnly::ProductDecision.code(), + common::run_wake::Wake::Comment + )); + assert!(!common::run_wake::wakes_run( + "needs_input", + HumanOnly::UsageLimit.code(), + common::run_wake::Wake::Comment + )); + // Jira: the comment is sent with the wait, and the run it starts takes + // up the waiting run as Retry does. + assert!(JIRA_WEBHOOK.contains("super::run_wake::comment_wakes(run_item)")); + assert!(JIRA_WEBHOOK.contains("super::run_wake::resumed_from(run_item)")); + assert!(JIRA_WEBHOOK.contains("resumes: Some(resumes),")); + // GitHub: a plain comment on the issue of a waiting run, mention or not. + assert!(TICKET_COMMENTS.contains( + "return answer_waiting_run(state, payload, installation_id, team_id, &ticket_id).await;" + )); + // Access granted and the limit raised wake the runs that waited. + assert!(GITHUB_WEBHOOK.contains("super::run_wake::access_granted(event_type, payload)")); + assert!(API.contains("common::run_wake::Wake::Access,")); + assert!(API.contains("wake_after_limit(&state, &claims.team_id).await;")); +} + +#[test] +fn a_merged_ticket_promises_only_what_a_reply_does() { + use common::messages::TicketSource; + for s in [TicketSource::Jira, TicketSource::Github] { + let a = common::merged_ticket::wait_action(&s); + assert!(a.contains("the run continues by itself"), "{a}"); + assert_eq!(person_text(a), None, "{a}"); + } +} + +#[test] +fn the_wrong_repo_note_names_the_place_and_cuts_at_a_word() { + let why = "it holds the storefront's Next.js components for the bookstore's search page and \ + the shared product card with its price, cover image and stock badge, which the \ + ticket names, while the api repository only serves the search results as JSON \ + through the catalog endpoint and its pagination helpers, and the docs repository \ + only describes the search page for the bookstore's editors"; + let n = crate::passes::repo_pick::no_changes_repo_note("acme/bookstore-web", why); + assert_eq!(person_text(&n), None, "{n}"); + assert!(n.contains("`Repo: owner/name`"), "{n}"); + assert!(n.contains("by itself"), "{n}"); + assert!(!n.contains("set the repo and re-run"), "{n}"); + let quoted = n.split("Why that repo: ").nth(1).unwrap(); + let quoted = quoted.split(" If the work").next().unwrap(); + assert!(quoted.ends_with('…'), "{quoted}"); + let kept = quoted.trim_end_matches('…'); + assert!( + why[kept.len()..].starts_with(' '), + "cut inside a word: {quoted}" + ); +} + +#[test] +fn a_fix_note_says_what_is_wrong_never_the_models_instruction() { + let blocking = vec![ + "`package.json` was changed and is no task of the plan. Put it back with `restore_file` \ + (omit `from_ref`), or, when the change truly needs it, say why in your Evidence on a \ + line `Outside the plan: package.json: `." + .to_string(), + "`src/search/card.tsx` is only reformatted: the fix changes nothing in it. Put it back \ + with `restore_file` (omit `from_ref`)." + .to_string(), + ]; + let note = crate::passes::habits_check::fixing_note(&blocking); + assert_eq!( + note, + "Tests and scope check found 2 items; CoderHelm is fixing them now. `package.json` was \ + changed and is no task of the plan. `src/search/card.tsx` is only reformatted: the fix \ + changes nothing in it." + ); + assert_eq!(person_text(¬e), None, "{note}"); + // The model still gets its instructions. + let fb = crate::passes::habits_check::fix_feedback(&blocking); + assert!(fb.contains("restore_file")); + // The old note is caught. + assert!(person_text(&format!("fixing: {}", blocking[0])).is_some()); +} + +#[test] +fn every_fix_round_can_have_the_description_rebuilt() { + // The fix round has the description tool, with the writer's guard. + assert!(IMPLEMENT.contains("tools.push(super::feedback::update_description_tool());")); + assert!(IMPLEMENT.contains("super::feedback::DescriptionRequests::for_round(false, false)")); + assert!(RESUME.contains("let rebuild_description = handed_off || r.description_rebuild;")); + assert!(common::description_handoff::ROUND_NOTE.contains("update_pr_description")); + assert!(!common::description_handoff::ROUND_NOTE.contains("You have no tool")); + // The live sentence is caught and the description rebuilt. + let live = "I've corrected the docs. I have no tool that edits the PR description, so \ + someone needs to paste in the replacement sections below."; + let (account, handed_off) = crate::passes::description::round_account(live); + assert!(handed_off); + assert!(!account.contains("paste"), "{account}"); + assert!(person_text(live).is_some()); +} + +#[test] +fn labels_are_coderhelms_and_one_way_is_named() { + use common::pr_steps::{State, Step}; + let labels = Step { + what: "Add PR labels e2e:checkout and CI:E2E, sending the existing labels too, so the \ + preview deploy runs the checkout spec" + .into(), + how: String::new(), + when: Default::default(), + owner: "a repository admin".into(), + state: State::Person { + why: "labels".into(), + unblock: String::new(), + }, + }; + assert!(!labels.needs_person(), "{}", labels.line()); + let start = Step { + what: "Start the staging deploy workflow".into(), + how: "gh workflow run deploy-staging.yml".into(), + when: Default::default(), + owner: "a repository admin".into(), + state: State::Person { + why: "the GitHub app may not start workflows".into(), + unblock: "give the app \"Actions: write\" (GitHub, Settings, Installed GitHub Apps, \ + CoderHelm, Permissions), or run the command yourself" + .into(), + }, + }; + let line = start.line(); + assert!(!line.contains("yourself"), "{line}"); + assert!(line.contains("Actions: write"), "{line}"); +} + +#[test] +fn the_updater_waits_out_aws_and_names_one_admin_action() { + assert!(!UPDATER.contains("press Update again once it has finished")); + assert!(UPDATER.contains("raise AwsBusy(stack_busy_why(st))")); + assert!(!PERMISSIONS.contains("delete the failed stack, then press Update again")); + let fix = common::live::permissions::stack_failed_fix( + "ROLLBACK_COMPLETE", + "CoderHelmLogReaderUpdate", + "111122223333", + "us-east-1", + ); + assert!( + fix.starts_with("An AWS admin in account 111122223333"), + "{fix}" + ); + assert_eq!(person_text(&fix), None, "{fix}"); + // The API's own example no longer hands the ready mark to a person. + assert!(!API.contains("Mark it ready once")); +} diff --git a/services/worker/src/passes/jira_comment.rs b/services/worker/src/passes/jira_comment.rs index 8990cb6d5..ab19cf80d 100644 --- a/services/worker/src/passes/jira_comment.rs +++ b/services/worker/src/passes/jira_comment.rs @@ -16,6 +16,11 @@ //! //! Every comment read is kept on the ticket's record, so the next plan sees //! what people wrote. +//! +//! A comment on a run that waits on a person is that person's answer +//! (`common::run_wake`): it resumes the run, whatever words it uses, unless +//! it only reports status or says the work is done elsewhere. A question +//! back is read by the resumed run, which asks again only if it must. use crate::agent::provider::ModelProvider; use crate::models::{JiraCommentMessage, TokenUsage, WorkerMessage}; @@ -54,26 +59,37 @@ fn action_kind(a: Option<&WorkerMessage>) -> ActionKind { } } +/// Whether the comment answers a run that waits for it: the gateway says so +/// for a run that waits on a person (`common::run_wake::wakes`); a message +/// that doesn't say takes a `needs_input` or `failed` run as waiting. +pub fn waits_for_answer(resumes: Option, run_status: &str) -> bool { + resumes.unwrap_or(matches!(run_status, "needs_input" | "failed")) +} + /// Whether a comment that starts a run is a person's direction for it: it -/// asks for the work, or it answers CoderHelm's own question on a waiting -/// run (whatever words it uses). -pub fn is_direction(intent: Option, run_status: &str) -> bool { - let waiting_for_answer = matches!( - run_status, - "needs_input" | "needs_outside_change" | "failed" - ); +/// asks for the work, or it answers a waiting run (whatever words it uses). +pub fn is_direction(intent: Option, waiting: bool, run_status: &str) -> bool { + let waiting_for_answer = waiting || run_status == "needs_outside_change"; match intent { Some(Intent::NewRequirement) => true, - None | Some(Intent::Other) => waiting_for_answer, + None | Some(Intent::Other | Intent::Question) => waiting_for_answer, _ => false, } } -/// The decision. `intent` is `None` when the model couldn't read the comment: -/// feedback on an open PR (which reads it again) and an answer to -/// CoderHelm's own question still go ahead; nothing else starts a run. +/// The decision for a run with `run_status` (see [`decide_waiting`]). +#[cfg(test)] pub fn decide(intent: Option, run_status: &str, action: ActionKind) -> Act { - let waiting_for_answer = matches!(run_status, "needs_input" | "failed"); + decide_waiting(intent, waits_for_answer(None, run_status), action) +} + +/// The decision. `intent` is `None` when the model couldn't read the comment: +/// feedback on an open PR (which reads it again) and an answer to a waiting +/// run still go ahead; nothing else starts a run. `waiting`: the run waits +/// for this person's answer, so any reply but a status report or "done +/// elsewhere" resumes it. +pub fn decide_waiting(intent: Option, waiting: bool, action: ActionKind) -> Act { + let waiting_for_answer = waiting; match (intent, action) { (_, ActionKind::None) => match intent { Some(Intent::FixElsewhereInfo) => Act::Elsewhere { @@ -85,6 +101,9 @@ pub fn decide(intent: Option, run_status: &str, action: ActionKind) -> A (None, ActionKind::Run) if waiting_for_answer => Act::Dispatch, (None, ActionKind::Run) => Act::Nothing, (Some(Intent::NewRequirement), _) => Act::Dispatch, + (Some(Intent::Question | Intent::Other), ActionKind::Run) if waiting_for_answer => { + Act::Dispatch + } (Some(Intent::Question), ActionKind::Feedback) => Act::Dispatch, (Some(Intent::Question), _) => Act::Nothing, (Some(Intent::FixElsewhereInfo), kind) => Act::Elsewhere { @@ -96,8 +115,9 @@ pub fn decide(intent: Option, run_status: &str, action: ActionKind) -> A pub const SYSTEM: &str = "You read one comment a person wrote on a ticket that an automated \ coding agent (CoderHelm) already worked on, and say what the comment is. \ - new_requirement: it asks for new or different work in the code, or answers the agent's \ - question with details it needs to do the work. \ + new_requirement: it asks for new or different work in the code, answers the agent's \ + question with details it needs to do the work, or says the person did what the agent was \ + waiting for (granted access, added a credential, restored a branch, made the decision). \ fix_elsewhere_info: it says the issue was fixed, or belongs, somewhere other than the code \ (a setting or data in another system, a manual change), or that it is resolved or no longer \ needed. \ @@ -120,7 +140,15 @@ pub fn schema() -> serde_json::Value { } pub fn prompt(msg: &JiraCommentMessage) -> String { + let waiting_for; let state = match msg.run_status.as_str() { + "needs_input" if !msg.waiting_for.trim().is_empty() => { + waiting_for = format!( + "CoderHelm's run is waiting on a person for this: {}", + common::truncate_str(msg.waiting_for.trim(), 600) + ); + waiting_for.as_str() + } "needs_input" => "CoderHelm asked a question on the ticket and is waiting for an answer.", "failed" => "CoderHelm's last run on the ticket failed.", "needs_outside_change" => { @@ -365,7 +393,8 @@ pub async fn run( let mut usage = TokenUsage::default(); let intent = classify(state, &provider, &msg, &mut usage).await; let kind = action_kind(msg.action.as_deref()); - let act = decide(intent, &msg.run_status, kind); + let waiting = waits_for_answer(msg.resumes, &msg.run_status); + let act = decide_waiting(intent, waiting, kind); info!( ticket_id = %msg.ticket_id, run_status = %msg.run_status, @@ -379,7 +408,7 @@ pub async fn run( intent: intent.unwrap_or(Intent::Other), at: chrono::Utc::now().to_rfc3339(), }; - let direction = is_direction(intent, &msg.run_status) + let direction = is_direction(intent, waiting, &msg.run_status) .then(|| format!("{}: {}", note.author, common::truncate_str(¬e.text, 600))); match act { Act::Dispatch => { @@ -488,8 +517,9 @@ mod tests { decide(Some(Intent::StatusOnly), "completed", kind), Act::Nothing ); + assert_eq!(decide(Some(Intent::Other), "completed", kind), Act::Nothing); assert_eq!( - decide(Some(Intent::Other), "needs_input", kind), + decide(Some(Intent::StatusOnly), "needs_input", kind), Act::Nothing ); } @@ -548,15 +578,59 @@ mod direction_tests { #[test] fn an_answer_to_a_waiting_run_is_a_direction() { - assert!(is_direction(Some(Intent::NewRequirement), "completed")); + assert!(is_direction( + Some(Intent::NewRequirement), + false, + "completed" + )); assert!( - is_direction(None, "needs_input"), + is_direction(None, true, "needs_input"), "unread answer to our question" ); - assert!(is_direction(Some(Intent::Other), "needs_outside_change")); - assert!(!is_direction(None, "completed")); - assert!(!is_direction(Some(Intent::Question), "needs_input")); - assert!(!is_direction(Some(Intent::StatusOnly), "needs_input")); - assert!(!is_direction(Some(Intent::FixElsewhereInfo), "needs_input")); + assert!(is_direction( + Some(Intent::Other), + false, + "needs_outside_change" + )); + assert!(!is_direction(None, false, "completed")); + assert!(is_direction(Some(Intent::Question), true, "needs_input")); + assert!(!is_direction(Some(Intent::StatusOnly), true, "needs_input")); + assert!(!is_direction( + Some(Intent::FixElsewhereInfo), + true, + "needs_input" + )); + } + + /// A run waiting on a person: the person's reply resumes it, whatever + /// its words ("done, access granted", "use the second reading", a + /// question back). A wait a comment can't answer (the usage limit, an + /// approval) isn't resumed by one. + #[test] + fn a_reply_to_a_waiting_run_resumes_it() { + for intent in [ + None, + Some(Intent::NewRequirement), + Some(Intent::Other), + Some(Intent::Question), + ] { + assert_eq!( + decide_waiting(intent, true, ActionKind::Run), + Act::Dispatch, + "{intent:?}" + ); + } + assert_eq!( + decide_waiting(Some(Intent::StatusOnly), true, ActionKind::Run), + Act::Nothing + ); + assert!(waits_for_answer(Some(true), "needs_input")); + assert!(!waits_for_answer(Some(false), "needs_input")); + assert!(waits_for_answer(None, "needs_input")); + assert!(!waits_for_answer(None, "completed")); + assert_eq!( + decide_waiting(Some(Intent::Other), false, ActionKind::Run), + Act::Nothing + ); } } diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 11c10e2c0..814675b88 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -4618,6 +4618,7 @@ false, outside_plan: Vec::new(), refused: Vec::new(), owed: Vec::new(), + description_rebuild: false, // The first attempt's lookups weren't kept; the proof check's // fix round can make them again. evidence: proof::RunEvidence { @@ -8424,6 +8425,7 @@ async fn run_repo_pipeline( outside_plan: Vec::new(), refused: Vec::new(), owed: Vec::new(), + description_rebuild: false, evidence: proof::RunEvidence { ci_gates: checks::kinds_from(&ci_commands), ci_commands, @@ -10369,7 +10371,7 @@ fn wait_on_ticket( questions, None, WaitingOn::fixed( - "Add the missing detail to the ticket, then press Retry", + "Add the missing detail to the ticket, or write it in a comment there; the run continues by itself when the ticket changes or the comment arrives", what, &ticket, ), @@ -10475,7 +10477,11 @@ pub(crate) async fn mark_run_stopped_by_guard( .expression_attribute_names("#s", "status") .needs_input( run_id, - &WaitingOn::fixed("Give CoderHelm what it needs, then press Retry", reason, ""), + &WaitingOn::fixed( + "Give CoderHelm what the reason below names, then say so in a comment on the ticket; the run continues by itself when the comment arrives", + reason, + "", + ), &hand_back, ) .expression_attribute_values(":em", attr_s(reason)) @@ -10539,7 +10545,7 @@ async fn stop_run_repo_not_enabled( } } let wait = WaitingOn::fixed( - "Turn the repository on for runs in CoderHelm, then press Retry", + "Turn the repository on for runs in CoderHelm's Repositories page; the run continues by itself once it is on", message, "", ); diff --git a/services/worker/src/passes/repo_pick.rs b/services/worker/src/passes/repo_pick.rs index 625ff6d15..07489c044 100644 --- a/services/worker/src/passes/repo_pick.rs +++ b/services/worker/src/passes/repo_pick.rs @@ -43,33 +43,57 @@ pub fn pin_state(pin: &str, repos: &[TeamRepo]) -> PinState { } } +/// The ticket names a repository that is connected but not on for runs: the +/// run waits, and goes on by itself once the repository is turned on +/// (`run_wake`, from the Repositories switch). pub fn not_enabled_message(repo: &str) -> String { format!( "This ticket is for {repo}, which isn't turned on for CoderHelm runs. \ - Turn it on in Repositories and re-run." + Turn it on in CoderHelm's Repositories page; the run continues by itself once it is on." ) } +/// The ticket names a repository CoderHelm's GitHub app can't reach: the run +/// waits, and goes on by itself once GitHub reports the access. pub fn not_connected_message(repo: &str) -> String { format!( - "This ticket is for {repo}, which isn't connected to CoderHelm. \ - Connect it in Repositories and re-run." + "This ticket is for {repo}, which isn't connected to CoderHelm. Give the CoderHelm \ + GitHub app access to it on GitHub (Settings, Installed GitHub Apps, CoderHelm, \ + Repository access); the run continues by itself once GitHub reports the access." ) } +/// The longest "why that repo" a note quotes. +pub const MAX_PICK_WHY_CHARS: usize = 300; + +/// What a ticket writes to name its repository: a line the repo pick reads +/// first ([`ticket_named_repo`]). +pub fn repo_line(repo: &str) -> String { + format!("`Repo: {repo}`") +} + /// Note appended when the plan finds nothing to change in a repo CoderHelm /// picked itself, so the reader can tell a wrong-repo pick from a done ticket. +/// It names the one place a person sets the repository: a `Repo:` line in +/// the ticket's description, which the pick reads first. Editing the ticket +/// starts a new run by itself (the ticket's content changed). pub fn no_changes_repo_note(repo: &str, why: &str) -> String { - let why = why.trim(); + let why = common::rendered::clip(why.trim(), MAX_PICK_WHY_CHARS); + let set = format!( + "If the work belongs in a different repository, add a line {} to the ticket's \ + description; CoderHelm starts a new run there by itself when the ticket changes.", + repo_line("owner/name") + ); if why.is_empty() { - format!( - "CoderHelm picked {repo} for this ticket and looked there. \ - If the work belongs in a different repo, set the repo and re-run." - ) + format!("CoderHelm picked {repo} for this ticket and looked there. {set}") } else { + let why = if why.ends_with(['.', '!', '?', '…']) { + why + } else { + format!("{why}.") + }; format!( - "CoderHelm picked {repo} for this ticket and looked there. Why that repo: {why} \ - If the work belongs in a different repo, set the repo and re-run." + "CoderHelm picked {repo} for this ticket and looked there. Why that repo: {why} {set}" ) } } @@ -420,7 +444,8 @@ mod tests { assert_eq!( not_enabled_message("Acme/handbook-docs"), "This ticket is for Acme/handbook-docs, which isn't turned on for CoderHelm runs. \ - Turn it on in Repositories and re-run." + Turn it on in CoderHelm's Repositories page; the run continues by itself once it is \ + on." ); } @@ -569,7 +594,49 @@ mod tests { let n = no_changes_repo_note("Acme/api", "the ticket is about the billing endpoint."); assert!(n.contains("Acme/api")); assert!(n.contains("billing endpoint")); - assert!(n.contains("re-run")); + assert!( + n.contains("add a line `Repo: owner/name` to the ticket's description"), + "{n}" + ); + assert!(n.contains("starts a new run there by itself"), "{n}"); + assert_eq!(common::rendered::person_text(&n), None, "{n}"); + // The line the note names is the one the pick reads. + let repos = vec![TeamRepo { + full_name: "Acme/web".into(), + enabled: true, + }]; + assert_eq!( + ticket_named_repo( + "Fix the footer", + "Repo: Acme/web\nThe footer is off.", + &repos + ), + Some("Acme/web".to_string()) + ); + } + + /// A long "why" is cut at a word, never mid-word, and the note still + /// ends with where to set the repository. + #[test] + fn a_long_pick_reason_is_cut_at_a_word() { + let why = "The ticket asks for a change to the storefront's search results page, which \ + lives in the web repository's search components and the shared product card \ + that renders each result with its price, cover image and the stock badge for \ + bookstore titles, so the web repository fits the Next.js components the ticket \ + names better than the api repository does"; + let n = no_changes_repo_note("Acme/web", why); + let quoted = n + .split("Why that repo: ") + .nth(1) + .and_then(|r| r.split(" If the work").next()) + .unwrap(); + assert!(quoted.ends_with('…'), "{quoted}"); + let kept = quoted.trim_end_matches('…'); + assert!( + why[kept.len()..].starts_with(' '), + "cut inside a word: {quoted}" + ); + assert!(quoted.chars().count() <= MAX_PICK_WHY_CHARS + 1, "{quoted}"); } fn run( diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 655f8faf8..3b17af86b 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -5169,6 +5169,9 @@ async fn run_fix_round( warn!(run_id = %msg.run_id, "A fix round handed the description to a person; rebuilding it from the branch"); r.evidence.notes = account; } + // The round asked for the description through its tool, or + // handed it to a person: either way it is rebuilt now. + let rebuild_description = handed_off || r.description_rebuild; *refused = std::mem::take(&mut r.refused); let outside_plan = std::mem::take(&mut r.outside_plan); // What this round was asked and looked up reaches the next one. @@ -5224,7 +5227,7 @@ async fn run_fix_round( ) .await; } - if files > 0 || handed_off { + if files > 0 || rebuild_description { let _ = super::description::head_moved( &super::description::Moved { state, @@ -5259,7 +5262,7 @@ async fn run_fix_round( } super::round::Landed::Nothing => { super::round::clear(state, &msg.team_id, &msg.run_id).await; - if handed_off { + if rebuild_description { let _ = super::description::head_moved( &super::description::Moved { state, diff --git a/services/worker/src/passes/review_eval.rs b/services/worker/src/passes/review_eval.rs index d8a5a5692..8b337987e 100644 --- a/services/worker/src/passes/review_eval.rs +++ b/services/worker/src/passes/review_eval.rs @@ -1663,6 +1663,7 @@ async fn review_eval_live_ticket_comments() { comment: case.comment.clone(), context_hash: String::new(), action: None, + ..Default::default() }; let v = crate::agent::anthropic::converse_json( &client, diff --git a/services/worker/src/passes/triage.rs b/services/worker/src/passes/triage.rs index 2314a7c83..b569eff0a 100644 --- a/services/worker/src/passes/triage.rs +++ b/services/worker/src/passes/triage.rs @@ -875,13 +875,8 @@ fn pick_reason(response: &str) -> String { .filter(|l| !l.is_empty()) .collect(); lines.pop(); - let joined = lines.join(" "); - let capped = common::truncate_str(&joined, 400); - if capped.len() < joined.len() { - format!("{capped}…") - } else { - capped.to_string() - } + // Cut at a word ("fits the Next.js compon…" was cut mid-word). + common::rendered::clip(&lines.join(" "), 400) } /// Scan the response from the LAST line upward for a line that names one of From 15b3318b5e272e89747de4086bed1b43b84571c7 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 30 Nov 2026 15:24:49 -0500 Subject: [PATCH 3/6] Usage-limit, reopened-change, approval and alert waits go on by themselves Runs waiting on the usage limit start again from the 15-minute sweep once the team's limit allows runs, so a new month resets them. A run whose change closed goes back to waiting when the change is reopened, and goes on when it merges. An answered approval resumes the same run with the work it kept. An alert run resumes when its alert fires again and closes when it clears; its wait says what to do first, then Retry on the run page. --- .../incidents/wz_waits_go_on_by_themselves.md | 2 +- services/common/src/change_wait.rs | 52 ++++ services/common/src/run_fail.rs | 18 +- services/common/src/run_recovery.rs | 2 +- services/common/src/run_wake.rs | 120 ++++++++- services/gateway/src/routes/agent_policy.rs | 15 +- services/gateway/src/routes/alerts.rs | 13 +- services/gateway/src/routes/run_wake.rs | 193 ++++++++++++++ services/worker/src/agent/policy.rs | 48 +++- services/worker/src/main.rs | 8 + services/worker/src/passes/change_wait.rs | 111 +++++++- .../incidents/wz_waits_go_on_by_themselves.rs | 69 +++++ services/worker/src/passes/mod.rs | 14 + services/worker/src/passes/recover.rs | 7 + services/worker/src/passes/run_guard.rs | 1 + services/worker/src/passes/run_wake.rs | 241 ++++++++++++++++++ 16 files changed, 896 insertions(+), 18 deletions(-) create mode 100644 services/worker/src/passes/run_wake.rs diff --git a/docs/incidents/wz_waits_go_on_by_themselves.md b/docs/incidents/wz_waits_go_on_by_themselves.md index 2e2cc98cc..feb2af3b4 100644 --- a/docs/incidents/wz_waits_go_on_by_themselves.md +++ b/docs/incidents/wz_waits_go_on_by_themselves.md @@ -2,4 +2,4 @@ **What happened:** A second pass over what CoderHelm showed people found texts that still handed people work CoderHelm does, or promised what didn't happen. A run stopped for a person said "Look at what stopped the run, put it right, then press Retry", and a comment on its ticket was only kept as context, so a person's answer left the run waiting. A merged-ticket stop told people to reply on the ticket as if the reply started a run. A wrong-repo note said "set the repo and re-run" without saying where, after a reason cut in the middle of a word. A tests-and-scope note quoted the coding model's instruction ("Put it back with `restore_file` (omit `from_ref`)"). A fix round wrote that it had no tool to edit the pull request's description and that someone had to paste in the new sections. An outside-change report asked a person to add pull request labels CoderHelm adds itself, and to "run the command yourself". The updater said "press Update again" when AWS was busy, and the access check said to delete a failed stack and press Update again. -**The guarantee:** A run that waits on a person goes on by itself when what it waits for arrives: a comment or reply on its ticket, access granted on GitHub or a repository turned on, or the usage limit raised. Its action names the one thing to do, where, and that the run goes on by itself; only a decision about the run itself (an approval, a person's own stop) waits for that decision. Notes a person reads never carry the coding model's instructions. Every fix round can have the description rebuilt. Pull request labels are CoderHelm's to add. The updater waits out a busy stack or AWS throttling and starts the update again by itself, and a failed stack in another account gets one action for an AWS admin. Tests hold each text to `common::rendered::person_text`. +**The guarantee:** A run that waits on a person goes on by itself when what it waits for arrives: a comment or reply on its ticket, access granted on GitHub or a repository turned on, or the usage limit raised or reset by a new month. A change it waited for that closed and is reopened takes the run back to waiting, and its merge lets it go on. An answered approval resumes the same run. An alert run resumes when its alert fires again and closes when it clears; its wait says what to do first, then Retry on the run page. Its action names the one thing to do, where, and that the run goes on by itself; only a decision about the run itself (an approval, a person's own stop) waits for that decision. Notes a person reads never carry the coding model's instructions. Every fix round can have the description rebuilt. Pull request labels are CoderHelm's to add. The updater waits out a busy stack or AWS throttling and starts the update again by itself, and a failed stack in another account gets one action for an AWS admin. Tests hold each text to `common::rendered::person_text`. diff --git a/services/common/src/change_wait.rs b/services/common/src/change_wait.rs index 45006682a..f5b2c40fb 100644 --- a/services/common/src/change_wait.rs +++ b/services/common/src/change_wait.rs @@ -252,6 +252,36 @@ pub fn settle(pr: Option<(&str, bool)>, dep_run_status: Option<&str>) -> Settled } } +/// What a run that stopped because its dependency closed does when the +/// dependency's pull request moves again: reopened, it waits for the merge +/// again; merged, it goes on as any merge does. `None` while it stays +/// closed (or can't be read). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AfterClose { + Reopened, + Merged, +} + +/// [`AfterClose`] for the dependency's pull request as GitHub gives it. +pub fn after_close(pr: Option<(&str, bool)>) -> Option { + match pr { + Some((_, true)) => Some(AfterClose::Merged), + Some(("open", false)) => Some(AfterClose::Reopened), + _ => None, + } +} + +/// What the stopped run asks of a person: reopen the change (the run then +/// waits for it again by itself) or change the ticket (a new run starts by +/// itself). +pub fn closed_action(dep: &Dependency) -> String { + format!( + "Reopen {} on GitHub, or change this ticket; the run goes back to waiting for its merge \ + by itself once it is reopened, and a change to the ticket starts a new run by itself", + dep.label() + ) +} + /// The reason a run stops when its dependency closed without merging. pub fn closed_reason(dep: &Dependency) -> String { format!( @@ -265,6 +295,28 @@ pub fn stuck_line(dep: &Dependency, why: &str) -> String { format!("Still waiting for {}: {why}.", dep.label()) } +#[cfg(test)] +mod after_close_tests { + use super::*; + + #[test] + fn a_reopened_or_merged_change_takes_the_run_back() { + assert_eq!( + after_close(Some(("open", false))), + Some(AfterClose::Reopened) + ); + assert_eq!( + after_close(Some(("closed", true))), + Some(AfterClose::Merged) + ); + assert_eq!(after_close(Some(("closed", false))), None); + assert_eq!(after_close(None), None); + let a = closed_action(&Dependency::default()); + assert!(!a.contains("press Retry"), "{a}"); + assert_eq!(crate::rendered::person_text(&a), None, "{a}"); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/common/src/run_fail.rs b/services/common/src/run_fail.rs index 63c02973c..2ab10aed0 100644 --- a/services/common/src/run_fail.rs +++ b/services/common/src/run_fail.rs @@ -100,6 +100,10 @@ pub struct RunFailure<'a> { /// Numbers added to fields in the same write (tokens, cost): what this /// invocation used, on top of what earlier ones recorded. pub add: Vec<(&'static str, AttributeValue)>, + /// The run is an alert's: it has no ticket thread, so a wait's action + /// says what to do first and then Retry on the run page + /// (`run_wake::for_alert`). + pub alert: bool, } /// The status-index sort key of a failed run. @@ -168,9 +172,17 @@ pub fn update(run_id: &str, f: &RunFailure<'_>, now: &str) -> Update { ("#detail".to_string(), rr::FIELD_ERROR_DETAIL.to_string()), ("#kind".to_string(), rr::FIELD_ERROR_KIND.to_string()), ]); + // What the person does: an alert run has no thread to comment on. + let action_of = |needs: &rr::NeedsYou| { + if f.alert { + crate::run_wake::for_alert(&needs.action) + } else { + needs.action.clone() + } + }; // A wait on a person, through the gate with what they do. let needs_you = |needs: &rr::NeedsYou| { - let wait = crate::run_wait::WaitingOn::action(&needs.action, &needs.detail, "") + let wait = crate::run_wait::WaitingOn::action(&action_of(needs), &needs.detail, "") .unwrap_or_else(|| { crate::run_wait::WaitingOn::fixed( "Put right what the error below names, then say so in a comment on the ticket; the run continues by itself when the comment arrives", @@ -208,7 +220,7 @@ pub fn update(run_id: &str, f: &RunFailure<'_>, now: &str) -> Update { } Ending::NeedsYou(c, needs) => { let (w, wo) = needs_you(&needs); - let said = format!("{} {}.", needs.detail, needs.action); + let said = format!("{} {}.", needs.detail, action_of(&needs)); ( w, needs.detail.clone(), @@ -222,7 +234,7 @@ pub fn update(run_id: &str, f: &RunFailure<'_>, now: &str) -> Update { Cause::NeedsYou { needs, .. } => { let kind = needs.kind; let (w, wo) = needs_you(needs); - let said = format!("{} {}.", needs.detail, needs.action); + let said = format!("{} {}.", needs.detail, action_of(needs)); ( w, needs.detail.clone(), diff --git a/services/common/src/run_recovery.rs b/services/common/src/run_recovery.rs index d18c04faa..9d840b99c 100644 --- a/services/common/src/run_recovery.rs +++ b/services/common/src/run_recovery.rs @@ -865,7 +865,7 @@ pub fn person_action(why: HumanOnly) -> String { HumanOnly::UsageLimit => "Raise or clear the team's usage limit in Settings; the run \ continues by itself once the new limit is saved and allows it" .to_string(), - HumanOnly::Approval => "Answer the approval the team's agent policy asks for".to_string(), + HumanOnly::Approval => crate::run_wake::APPROVAL_ACTION.to_string(), HumanOnly::PersonAction => "Decide whether the run goes on: press Retry on the run in \ CoderHelm to start it again, or leave it stopped" .to_string(), diff --git a/services/common/src/run_wake.rs b/services/common/src/run_wake.rs index 76b585e8a..9c3982eb4 100644 --- a/services/common/src/run_wake.rs +++ b/services/common/src/run_wake.rs @@ -12,7 +12,13 @@ //! (a repository added to its installation, a permission accepted, the //! app installed again); //! - [`Wake::Limit`]: the team's usage limit raised or cleared so runs may -//! start again. +//! start again, or a new month that resets it (the worker's 15-minute +//! sweep reads each waiting team's limit: `passes::run_wake`); +//! - [`Wake::Approval`]: the approval the run's agent policy asked for was +//! answered: the same run goes on, so the one-time grant (kept for that +//! run) applies ([`approval_resumes`]); +//! - an alert run (no ticket thread): the alert firing again resumes it, +//! and the alert clearing closes it ([`alert_wake`], [`for_alert`]). //! //! Every wait names one of these in its action ([`CONTINUES`]), so what a //! person reads is what happens. Only a decision a person makes about the @@ -40,10 +46,17 @@ pub enum Wake { Comment, /// Access granted to the CoderHelm GitHub app. Access, - /// The team's usage limit raised or cleared. + /// The team's usage limit raised or cleared, or reset by a new month. Limit, + /// The approval the run waited for was answered. + Approval, } +/// What a run waiting on its agent policy's approval asks. The answer +/// resumes the same run by itself (the grant is kept for that run). +pub const APPROVAL_ACTION: &str = "Answer the approval request this run is waiting on (Agents, \ + Approvals, or the link sent with it); the run goes on by itself once it is answered"; + /// The status of a run that waits on a person. pub const WAITING: &str = "needs_input"; @@ -57,9 +70,65 @@ pub fn wakes(why: Option, wake: Wake) -> bool { Wake::Comment => !matches!(why, Some(HumanOnly::UsageLimit | HumanOnly::Approval)), Wake::Access => matches!(why, Some(HumanOnly::MissingAccess | HumanOnly::Credential)), Wake::Limit => why == Some(HumanOnly::UsageLimit), + Wake::Approval => why == Some(HumanOnly::Approval), } } +/// Whether the answer to approval `approval_id` resumes the run with +/// `status` that waited on `handback` for `waited_for` (its +/// `policy_approval`): only that run, only while it still waits. +pub fn approval_resumes(status: &str, handback: &str, waited_for: &str, approval_id: &str) -> bool { + !approval_id.is_empty() + && waited_for == approval_id + && wakes_run(status, handback, Wake::Approval) +} + +/// What an alert's delivery does to its run that waits on a person. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AlertWake { + /// The alert fired again: the run goes on, as Retry would. + Resume, + /// The alert cleared by itself: nothing is left to fix, the run closes. + Close, +} + +/// [`AlertWake`] for a run with `status` waiting on `handback`, when its +/// alert fires again (`cleared` false) or clears. `None` for a run that +/// doesn't wait, or waits on the usage limit or an approval (only those +/// lift it; a clear still closes it). +pub fn alert_wake(status: &str, handback: &str, cleared: bool) -> Option { + if status != WAITING { + return None; + } + if cleared { + return Some(AlertWake::Close); + } + wakes(HumanOnly::from_code(handback), Wake::Comment).then_some(AlertWake::Resume) +} + +/// What an alert run's wait asks: an alert has no ticket thread, so a +/// comment can't answer it. The person does what `action` names, then +/// presses Retry on the run page; the run also goes on by itself when the +/// alert fires again, and closes by itself when it clears. +pub fn for_alert(action: &str) -> String { + let what = match action.find(", then say so in a comment on the ticket") { + Some(i) => &action[..i], + None => match action.find("; the run continues by itself") { + Some(i) => &action[..i], + None => action, + }, + }; + // No thread to comment on: the decision is the person's to act on. + let what = what + .replace("Say in a comment on the ticket ", "Decide ") + .replace(" in a comment on the ticket", ""); + let what = what.trim().trim_end_matches('.'); + format!( + "{what}. Once that is done, press Retry on the run page; the run also goes on by itself \ + when the alert fires again, and closes by itself when it clears" + ) +} + /// [`wakes`] for a run with `status` whose wait recorded `handback` (its /// code, `HumanOnly::code`): only a run that waits on a person is woken. pub fn wakes_run(status: &str, handback: &str, wake: Wake) -> bool { @@ -129,6 +198,53 @@ mod tests { assert!(access_reaches("acme/bookstore-api", "", &[])); } + #[test] + fn an_answer_resumes_only_the_run_that_waited_for_it() { + assert!(approval_resumes("needs_input", "approval", "ap1", "ap1")); + assert!(!approval_resumes("needs_input", "approval", "ap1", "ap2")); + assert!(!approval_resumes("completed", "approval", "ap1", "ap1")); + assert!(!approval_resumes( + "needs_input", + "product_decision", + "ap1", + "ap1" + )); + assert!(!approval_resumes("needs_input", "approval", "", "")); + } + + #[test] + fn an_alert_firing_again_resumes_and_clearing_closes() { + let w = "needs_input"; + assert_eq!( + alert_wake(w, "unrepaired_error", false), + Some(AlertWake::Resume) + ); + assert_eq!(alert_wake(w, "usage_limit", false), None); + assert_eq!(alert_wake(w, "usage_limit", true), Some(AlertWake::Close)); + assert_eq!(alert_wake("running", "", true), None); + let a = for_alert(&by_comment( + "Restore the branch `main` in acme/bookstore-ops", + )); + assert_eq!( + a, + "Restore the branch `main` in acme/bookstore-ops. Once that is done, press Retry on \ + the run page; the run also goes on by itself when the alert fires again, and closes \ + by itself when it clears" + ); + assert_eq!(crate::rendered::person_text(&a), None, "{a}"); + let c = for_alert("Say in a comment on the ticket which reading is meant; the run continues by itself when the comment arrives"); + assert!( + c.starts_with("Decide which reading is meant. Once that is done"), + "{c}" + ); + assert!(!c.contains("comment"), "{c}"); + let b = for_alert("Raise or clear the team's usage limit in Settings; the run continues by itself once the new limit is saved and allows it"); + assert!( + b.starts_with("Raise or clear the team's usage limit in Settings. Once"), + "{b}" + ); + } + #[test] fn the_action_says_the_run_goes_on_by_itself() { let a = by_comment("Restore the branch `main` in acme/bookstore-web."); diff --git a/services/gateway/src/routes/agent_policy.rs b/services/gateway/src/routes/agent_policy.rs index 261b2b67b..3e48ed9a4 100644 --- a/services/gateway/src/routes/agent_policy.rs +++ b/services/gateway/src/routes/agent_policy.rs @@ -931,6 +931,8 @@ pub async fn decide( ) .await .map_err(decide_error)?; + // The run that waited for this answer goes on by itself (`run_wake`). + super::run_wake::approval_answered(&state, &claims.team_id, &a.run_id, &a.id).await; Ok(Json(json!({ "approval": a }))) } @@ -1282,14 +1284,17 @@ pub async fn link_answer( ) .await { - Ok(_) => page( - StatusCode::OK, - "Approval recorded", - &format!( + Ok(a) => { + super::run_wake::approval_answered(&state, &c.team_id, &a.run_id, &a.id).await; + page( + StatusCode::OK, + "Approval recorded", + &format!( "

{}

The agent carries on with your answer. You can close this page.

", if approve { "Approved once." } else { "Denied." } ), - ), + ) + } Err(e) => page( StatusCode::CONFLICT, "Approval", diff --git a/services/gateway/src/routes/alerts.rs b/services/gateway/src/routes/alerts.rs index 260134662..08fceabfe 100644 --- a/services/gateway/src/routes/alerts.rs +++ b/services/gateway/src/routes/alerts.rs @@ -832,7 +832,16 @@ async fn handle_notification( episodes::post_cleared(&posting, &route.team_id, old).await; } let opens_episode = matches!(decision, Some(Decision::Opened | Decision::Reopened(_))); - let decided = decide(state, msg, route, rule, &alert, &tid).await; + // The alert fired again while its run waits on a person: that + // run goes on (`run_wake`), and no second run starts. + let decided = if route.enabled + && super::run_wake::alert_delivery(state, &route.team_id, &tid, false).await + { + info!(topic = %msg.topic_arn, ticket = %tid, "Alert fired again: its waiting run goes on"); + Ok(Outcome::RunStarted) + } else { + decide(state, msg, route, rule, &alert, &tid).await + }; if decided.is_err() && opens_episode { // SNS retries this delivery: let it open the episode again. forget_episode( @@ -848,6 +857,8 @@ async fn handle_notification( } Plan::Recover => { let fp = alert.recovers.as_deref().unwrap_or_default(); + // Its run waiting on a person has nothing left to fix. + super::run_wake::alert_delivery(state, &route.team_id, &ticket_id(fp), true).await; let opened = alert_notify::close_open_alert( &state.dynamo, &state.config.settings_table_name, diff --git a/services/gateway/src/routes/run_wake.rs b/services/gateway/src/routes/run_wake.rs index 8e89ade2f..20bd780b1 100644 --- a/services/gateway/src/routes/run_wake.rs +++ b/services/gateway/src/routes/run_wake.rs @@ -11,6 +11,12 @@ //! - The team's usage limit raised or cleared: [`wake_team`] with //! `Wake::Limit`. //! +//! - The approval an agent policy asked for answered: the same run goes on +//! with the work it kept ([`approval_answered`]), so the one-time grant +//! applies. +//! - An alert run (no ticket thread): the alert firing again resumes its +//! waiting run, and the alert clearing closes it ([`alert_delivery`]). +//! //! A woken run is the same start as a person's Retry: the ticket again, //! with the waiting run's plan and branch when its plan wasn't what stopped //! it, and the waiting run marked as superseded by the new one. Only a run @@ -230,6 +236,193 @@ async fn wake_one(state: &AppState, team_id: &str, item: &Item, what: &str) -> b } } +/// A run of the team by id. +async fn run_item(state: &AppState, team_id: &str, run_id: &str) -> Option { + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .consistent_read(true) + .send() + .await + .ok()? + .item +} + +/// The newest run of `ticket_id`, whatever its status. +async fn newest_of_ticket(state: &AppState, team_id: &str, ticket_id: &str) -> Option { + let out = state + .dynamo + .query() + .table_name(&state.config.runs_table_name) + .index_name("ticket-index") + .key_condition_expression("team_id = :tid AND ticket_id = :ticket") + .expression_attribute_values(":tid", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":ticket", AttributeValue::S(ticket_id.to_string())) + .send() + .await + .ok()?; + out.items() + .iter() + .max_by(|a, b| text(a, "run_id").cmp(text(b, "run_id"))) + .cloned() +} + +/// The answer to approval `approval_id` sends the run that waited for it +/// on: the work it kept, as the same run, after the run is marked working +/// again (only while it still waits for this approval). A run that kept no +/// work starts again as Retry would. `true` when the run went on. +pub async fn approval_answered( + state: &AppState, + team_id: &str, + run_id: &str, + approval_id: &str, +) -> bool { + if run_id.is_empty() { + return false; + } + let Some(item) = run_item(state, team_id, run_id).await else { + return false; + }; + let wait = WaitingOn::of_item(&item).unwrap_or_default(); + if !run_wake::approval_resumes( + text(&item, "status"), + &wait.handback, + text(&item, "policy_approval"), + approval_id, + ) { + return false; + } + let kept = text(&item, common::run_recovery::FIELD_RESUME_MESSAGE).to_string(); + if kept.is_empty() { + return wake_one( + state, + team_id, + &item, + "the approval it waited for was answered", + ) + .await; + } + let back = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .update_expression( + "SET #status = :s, status_run_id = :sri, updated_at = :t REMOVE waiting_on", + ) + .condition_expression("#status = :waiting AND policy_approval = :a") + .expression_attribute_names("#status", "status") + .run_status( + ":s", + &common::run_ending::working(common::run_ending::Working::Queued, run_id), + ) + .expression_attribute_values(":waiting", AttributeValue::S(run_wake::WAITING.into())) + .expression_attribute_values(":a", AttributeValue::S(approval_id.to_string())) + .expression_attribute_values(":t", AttributeValue::S(chrono::Utc::now().to_rfc3339())) + .send() + .await; + if back.is_err() { + return false; + } + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(kept) + .send() + .await + { + Ok(_) => { + info!(run_id, approval_id, "Approval answered: the run goes on"); + true + } + Err(e) => { + warn!(run_id, error = %e, "Could not send the approved run on"); + false + } + } +} + +/// An alert delivery for the alert whose run's ticket is `ticket_id`: +/// firing again (`cleared` false) resumes its waiting run as Retry would; +/// clearing closes it, since nothing is left to fix. `true` when the run +/// moved (a firing then starts no second run). +pub async fn alert_delivery( + state: &AppState, + team_id: &str, + ticket_id: &str, + cleared: bool, +) -> bool { + let Some(item) = newest_of_ticket(state, team_id, ticket_id).await else { + return false; + }; + let wait = WaitingOn::of_item(&item).unwrap_or_default(); + match run_wake::alert_wake(text(&item, "status"), &wait.handback, cleared) { + Some(run_wake::AlertWake::Resume) => { + wake_one(state, team_id, &item, "its alert fired again").await + } + Some(run_wake::AlertWake::Close) => close_cleared(state, team_id, &item).await, + None => false, + } +} + +/// Closes a waiting alert run whose alert cleared by itself. +async fn close_cleared(state: &AppState, team_id: &str, item: &Item) -> bool { + let run_id = text(item, "run_id").to_string(); + let why = "the alert cleared by itself, so nothing is left to fix"; + let closed = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("run_id", AttributeValue::S(run_id.clone())) + .update_expression( + "SET #status = :s, status_run_id = :sri, updated_at = :t, \ + progress_notes = list_append(if_not_exists(progress_notes, :empty), :n)", + ) + .condition_expression("#status = :waiting") + .expression_attribute_names("#status", "status") + .run_status( + ":s", + &common::run_ending::gate( + &run_id, + &common::run_ending::RunEnd::Stopped(common::run_ending::Stopped { + reason: common::run_ending::Stop::ClosedBy { + who: "CoderHelm".into(), + why: why.into(), + }, + tried: Default::default(), + }), + ), + ) + .expression_attribute_values(":waiting", AttributeValue::S(run_wake::WAITING.into())) + .expression_attribute_values(":empty", AttributeValue::L(vec![])) + .expression_attribute_values( + ":n", + AttributeValue::L(vec![AttributeValue::M(HashMap::from([ + ( + "message".to_string(), + AttributeValue::S(format!("Closed: {why}.")), + ), + ( + "timestamp".to_string(), + AttributeValue::S(chrono::Utc::now().to_rfc3339()), + ), + ]))]), + ) + .expression_attribute_values(":t", AttributeValue::S(chrono::Utc::now().to_rfc3339())) + .send() + .await; + if closed.is_ok() { + info!(run_id, "Alert cleared: its waiting run closed"); + } + closed.is_ok() +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/worker/src/agent/policy.rs b/services/worker/src/agent/policy.rs index d2f4394bb..ba1cd4322 100644 --- a/services/worker/src/agent/policy.rs +++ b/services/worker/src/agent/policy.rs @@ -605,6 +605,52 @@ pub fn claim_stop(run_id: &str) -> Option { .flatten() } +/// Keeps the work a loop stopped for an unanswered approval on its run +/// (`run_recovery::FIELD_RESUME_MESSAGE`), as the same run: the answer +/// sends it again (`gateway::routes::run_wake::approval_answered`), and the +/// one-time grant, kept for that run, lets the call through. +pub async fn keep_for_answer( + state: &WorkerState, + team_id: &str, + run_id: &str, + raw: &serde_json::Value, +) { + if run_id.is_empty() { + return; + } + let again = resume_as_same_run(raw, run_id); + let Ok(body) = serde_json::to_string(&again) else { + return; + }; + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key( + "team_id", + aws_sdk_dynamodb::types::AttributeValue::S(team_id.to_string()), + ) + .key( + "run_id", + aws_sdk_dynamodb::types::AttributeValue::S(run_id.to_string()), + ) + .update_expression("SET #m = :m") + .condition_expression("attribute_exists(run_id)") + .expression_attribute_names("#m", common::run_recovery::FIELD_RESUME_MESSAGE) + .expression_attribute_values(":m", aws_sdk_dynamodb::types::AttributeValue::S(body)) + .send() + .await; +} + +/// `raw` sent again as the same run: a ticket message continues `run_id`. +pub fn resume_as_same_run(raw: &serde_json::Value, run_id: &str) -> serde_json::Value { + let mut again = raw.clone(); + if again.get("type").and_then(|t| t.as_str()) == Some("ticket") { + again["continuation_run_id"] = serde_json::json!(run_id); + } + again +} + /// Ends a run a loop stopped: queued (agents paused; it resumes when the /// pause ends) or waiting for input (an approval nobody answered), with the /// note on the run. Never overwrites a run a person cancelled or closed. @@ -668,7 +714,7 @@ async fn write_run_stop( .needs_input( run_id, &WaitingOn::fixed( - "Answer the approval request this run is waiting on, then press Retry", + common::run_wake::APPROVAL_ACTION, &stop.note(), "", ), diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 3d3cbe014..2f2600a80 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -295,6 +295,14 @@ async fn handle_sqs(state: Arc, event: LambdaEvent) -> Re if let Some(step) = &admitted.step { passes::github_admission::release(&state, step).await; } + // A loop stopped for an approval nobody answered yet: keep the work + // on the run (as the same run, so the one-time grant applies) for + // the answer to send again (`gateway::routes::run_wake`). + if let (Some((common::agent_policy::Stop::TimedOut { .. }, run_id)), Some((team, _, _))) = + (&stopped, &work) + { + agent::policy::keep_for_answer(&state, team, run_id, &raw).await; + } // A loop stopped because agents were paused mid-run: keep the work // (as the same run) to pick up again when the pause ends. if let (Some((common::agent_policy::Stop::Paused { .. }, run_id)), Some((team, label, _))) = diff --git a/services/worker/src/passes/change_wait.rs b/services/worker/src/passes/change_wait.rs index 1e7c94395..42471ba60 100644 --- a/services/worker/src/passes/change_wait.rs +++ b/services/worker/src/passes/change_wait.rs @@ -262,6 +262,11 @@ pub async fn check_all(state: &WorkerState, team: Option<&str>) -> Checked { None => {} } } + // Runs that stopped because their change closed: reopened, they wait + // for it again; merged, they go on (the 15-minute sweep reads them). + if team.is_none() { + out.resumed += check_closed(state).await; + } info!( waiting = out.waiting, resumed = out.resumed, @@ -271,6 +276,107 @@ pub async fn check_all(state: &WorkerState, team: Option<&str>) -> Checked { out } +/// Every run that stopped because the change it waited for closed: when +/// that change is reopened the run waits for it again, and when it merged +/// the run goes on. Returns how many went back. +async fn check_closed(state: &WorkerState) -> usize { + let filter = super::team_runs::Filter { + expr: "#s = :n AND attribute_exists(#w)", + names: vec![("#s", "status"), ("#w", cw::FIELD)], + values: vec![(":n", attr_s(common::run_wake::WAITING))], + projection: None, + }; + let items = super::team_runs::matching(state, "Runs whose change closed", &filter).await; + let mut back = 0; + for item in items { + if s(&item, "status") != common::run_status::NEEDS_INPUT { + continue; + } + let Some(dep) = Dependency::from_json(s(&item, cw::FIELD)) else { + continue; + }; + let Some((o, r)) = dep.repo.split_once('/') else { + continue; + }; + if dep.pr == 0 { + continue; + } + let Ok(gh) = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + n(&item, "installation_id"), + &state.http, + ) else { + continue; + }; + let pr = gh.get_pull_request(o, r, dep.pr).await.ok(); + let moved = cw::after_close(pr.as_ref().map(|p| { + ( + p["state"].as_str().unwrap_or("closed"), + p["merged"].as_bool().unwrap_or(false), + ) + })); + let Some(moved) = moved else { + continue; + }; + let team_id = s(&item, "team_id"); + let run_id = s(&item, "run_id"); + let line = cw::note(&dep); + // Back to waiting, only while it still waits on a person. + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET #s = :s, status_run_id = :sri, error_message = :em, current_pass = :cp, \ + updated_at = :t REMOVE waiting_on", + ) + .condition_expression("#s = :n") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":s", attr_s(AWAITING_CHANGE)) + .expression_attribute_values( + ":sri", + common::run_ending::working(common::run_ending::Working::AwaitingChange, run_id) + .sri_attr(), + ) + .expression_attribute_values(":n", attr_s(common::run_wake::WAITING)) + .expression_attribute_values(":em", attr_s(&line)) + .expression_attribute_values(":cp", attr_s("waiting")) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await; + if res.is_err() { + continue; + } + add_progress_note( + state, + team_id, + run_id, + &match moved { + cw::AfterClose::Reopened => { + format!( + "{} was reopened: the run waits for it to merge again", + dep.label() + ) + } + cw::AfterClose::Merged => { + format!("{} merged after all: the run goes on", dep.label()) + } + }, + ) + .await; + back += 1; + if moved == cw::AfterClose::Merged { + if let Some(now) = record(state, team_id, run_id).await { + check_one(state, &now).await; + } + } + } + back +} + /// `Some(true)`: resumed; `Some(false)`: stopped for a person; `None`: /// still waiting. async fn check_one(state: &WorkerState, item: &HashMap) -> Option { @@ -344,10 +450,7 @@ async fn check_one(state: &WorkerState, item: &HashMap) let needs = common::run_recovery::NeedsYou { kind: common::run_recovery::Kind::NeedsPerson, why: common::handback::HumanOnly::ProductDecision, - action: format!( - "Reopen and merge {}, or change this ticket, then press Retry", - dep.label() - ), + action: cw::closed_action(&dep), detail: reason, }; super::recover::stop_for_person( diff --git a/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs b/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs index 157fa61ce..e419c12c3 100644 --- a/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs +++ b/services/worker/src/passes/incidents/wz_waits_go_on_by_themselves.rs @@ -38,6 +38,13 @@ const IMPLEMENT: &str = include_str!("../implement.rs"); const RESUME: &str = include_str!("../resume.rs"); const PERMISSIONS: &str = include_str!("../../../../common/src/live/permissions.rs"); const UPDATER: &str = include_str!("../../../../../lambda/updater/handler.py"); +const RECOVER: &str = include_str!("../recover.rs"); +const PASSES_MOD: &str = include_str!("../mod.rs"); +const CHANGE_WAIT: &str = include_str!("../change_wait.rs"); +const POLICY: &str = include_str!("../../agent/policy.rs"); +const MAIN: &str = include_str!("../../main.rs"); +const AGENT_POLICY_ROUTES: &str = include_str!("../../../../gateway/src/routes/agent_policy.rs"); +const ALERTS: &str = include_str!("../../../../gateway/src/routes/alerts.rs"); #[test] fn a_wait_says_the_run_goes_on_by_itself() { @@ -238,3 +245,65 @@ fn the_updater_waits_out_aws_and_names_one_admin_action() { // The API's own example no longer hands the ready mark to a person. assert!(!API.contains("Mark it ready once")); } + +/// The month resets the usage limit: the 15-minute sweep reads each waiting +/// team's limit and starts its waiting runs once it allows runs. +#[test] +fn a_limit_wait_wakes_when_the_limit_allows_runs_again() { + assert!(RECOVER.contains("report.woken = super::run_wake::wake_limit_waits(state).await;")); + let src = include_str!("../run_wake.rs"); + assert!(src.contains("super::check_budget_exceeded(state, &team).await.is_some()")); +} + +/// A change that closed: reopened, the run waits for it again; merged, it +/// goes on; a changed ticket starts a new run. Never "press Retry". +#[test] +fn a_reopened_change_takes_its_run_back() { + assert!(!CHANGE_WAIT.contains("then press Retry")); + assert!(CHANGE_WAIT.contains("action: cw::closed_action(&dep),")); + assert!(CHANGE_WAIT.contains("out.resumed += check_closed(state).await;")); + assert_eq!( + common::change_wait::after_close(Some(("open", false))), + Some(common::change_wait::AfterClose::Reopened) + ); +} + +/// An answer to the approval resumes the same run with the work it kept. +#[test] +fn an_answered_approval_resumes_the_run_that_waited() { + assert!(!POLICY.contains("then press Retry")); + assert!(POLICY.contains("common::run_wake::APPROVAL_ACTION")); + assert!(MAIN.contains("agent::policy::keep_for_answer(&state, team, run_id, &raw).await;")); + assert_eq!( + AGENT_POLICY_ROUTES + .matches("super::run_wake::approval_answered(") + .count(), + 2, + "both ways of answering (the dashboard and the signed link)" + ); + let again = crate::agent::policy::resume_as_same_run( + &serde_json::json!({"type": "ticket", "ticket_id": "WEB-7"}), + "01RUN", + ); + assert_eq!(again["continuation_run_id"], "01RUN"); + assert_eq!(person_text(common::run_wake::APPROVAL_ACTION), None); +} + +/// An alert run has no thread: firing again resumes it, clearing closes +/// it, and its wait says what to do first. +#[test] +fn an_alert_run_resumes_or_closes_with_its_alert() { + assert!(ALERTS.contains("super::run_wake::alert_delivery(state, &route.team_id, &tid, false)")); + assert!(ALERTS + .contains("super::run_wake::alert_delivery(state, &route.team_id, &ticket_id(fp), true)")); + assert!(PASSES_MOD.contains("common::run_wake::for_alert(&wait.action)")); + assert!(PASSES_MOD.contains("alert: matches!(msg.source, TicketSource::Alert),")); + assert!(RECOVER.contains("alert: matches!(msg.source, crate::models::TicketSource::Alert),")); + let a = common::run_wake::for_alert(&person_action(HumanOnly::Unrepaired)); + assert!( + a.contains("Once that is done, press Retry on the run page"), + "{a}" + ); + assert!(!a.contains("comment"), "{a}"); + assert_eq!(person_text(&a), None, "{a}"); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 814675b88..96dfbf8c2 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1477,6 +1477,7 @@ pub(crate) mod run_files; pub mod run_guard; pub(crate) mod run_lists; pub mod run_map; +pub mod run_wake; pub(crate) mod scope_ledger; mod security; pub mod security_fixes; @@ -10396,6 +10397,18 @@ async fn mark_run_needs_input( // question or blocker when it names one, else what this stop asks for // (a question about the ticket, a decision, access, a pull request // someone else holds). + // An alert run has no ticket thread: its wait says what to do first, + // then Retry on the run page (`run_wake::for_alert`). + let alerted; + let wait = if matches!(msg.source, TicketSource::Alert) { + alerted = WaitingOn { + action: common::run_wake::for_alert(&wait.action), + ..wait.clone() + }; + &alerted + } else { + wait + }; let hand_back = supervisor::HandBack::of_judged(judged).unwrap_or_else(|| { supervisor::HandBack::new(asked_for, &wait.line()) .unwrap_or(supervisor::HandBack::of(asked_for)) @@ -11146,6 +11159,7 @@ async fn end_with( only_from: None, extra, add: usage_adds(&delta), + alert: matches!(msg.source, TicketSource::Alert), }; // The ending is decided once (`common::run_fail::update`): only an // error the self-heal sweep resumes is parked as `failed` with its diff --git a/services/worker/src/passes/recover.rs b/services/worker/src/passes/recover.rs index f7ad99c8d..d4587ea3d 100644 --- a/services/worker/src/passes/recover.rs +++ b/services/worker/src/passes/recover.rs @@ -590,6 +590,7 @@ pub async fn stop_for_person( only_from: None, extra: vec![("duration_s", attr_n(duration))], add: super::usage_adds(&delta), + alert: matches!(msg.source, crate::models::TicketSource::Alert), }; match common::run_fail::fail_run( &state.dynamo, @@ -660,6 +661,8 @@ pub struct SweepReport { pub skipped: usize, /// Runs waiting on CI with nothing set to look again, picked back up. pub redriven: usize, + /// Runs waiting on the usage limit started again once it allowed runs. + pub woken: usize, } /// The first start of each release (its code version) sends one self-heal @@ -851,6 +854,9 @@ pub async fn self_heal_sweep(state: &WorkerState) -> SweepReport { super::change_wait::check_all(state, None).await; // Runs waiting on CI with no check left to look at them again. report.redriven = super::resume::redrive_parked_waits(state).await; + // Runs waiting on the usage limit: started again once it allows runs + // (raised, cleared, or a new month). + report.woken = super::run_wake::wake_limit_waits(state).await; info!( failed = report.failed, waiting = report.waiting, @@ -858,6 +864,7 @@ pub async fn self_heal_sweep(state: &WorkerState) -> SweepReport { handed = report.handed, skipped = report.skipped, redriven = report.redriven, + woken = report.woken, "Self-heal sweep done" ); report diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index 951602a28..ddebb088f 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -1114,6 +1114,7 @@ async fn finish_open_pr(state: &WorkerState, team_id: &str, run_id: &str, reason only_from: None, extra: Vec::new(), add: Vec::new(), + alert: false, }; match common::run_fail::fail_run( &state.dynamo, diff --git a/services/worker/src/passes/run_wake.rs b/services/worker/src/passes/run_wake.rs new file mode 100644 index 000000000..d94867973 --- /dev/null +++ b/services/worker/src/passes/run_wake.rs @@ -0,0 +1,241 @@ +//! The worker's side of `common::run_wake`: runs waiting on the team's +//! usage limit go on by themselves once the limit allows runs again, +//! whether a person raised it or a new month reset it. +//! +//! The 15-minute sweep (`recover::self_heal_sweep`) reads every run waiting +//! on the usage limit, asks each team's limit once, and starts every such +//! run of a team whose limit allows runs again, the way Retry does: the +//! ticket again, taking up the waiting run's plan and branch, with the +//! waiting run marked superseded by one conditional write (only while it +//! still waits), so two sweeps never start two runs. + +use std::collections::{HashMap, HashSet}; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::run_ending::EndWrite; +use common::run_wait::WaitingOn; +use common::run_wake::{self, Wake}; +use tracing::{info, warn}; + +use super::attr_s; +use crate::models::{TicketMessage, TicketSource, WorkerMessage}; +use crate::WorkerState; + +type Item = HashMap; + +fn s<'a>(item: &'a Item, k: &str) -> &'a str { + item.get(k) + .and_then(|v| v.as_s().ok()) + .map(|x| x.as_str()) + .unwrap_or("") +} + +fn n(item: &Item, k: &str) -> u64 { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|x| x.parse().ok()) + .unwrap_or(0) +} + +/// Most waiting runs one sweep starts again. +const MAX_WOKEN: usize = 50; + +/// The runs in `items` that wait on the usage limit, by team. +pub fn limit_waits(items: &[Item]) -> HashMap> { + let mut out: HashMap> = HashMap::new(); + for i in items { + let wait = WaitingOn::of_item(i).unwrap_or_default(); + if run_wake::wakes_run(s(i, "status"), &wait.handback, Wake::Limit) { + out.entry(s(i, "team_id").to_string()).or_default().push(i); + } + } + out +} + +/// The ticket a waiting run starts again with, from its record, as a +/// person's Retry builds it: the same ticket, the waiting run's plan and +/// branch taken up unless the plan was what stopped it, and the repository +/// picked again for a Jira ticket. +pub fn retry_ticket(item: &Item) -> Option { + let run_id = s(item, "run_id"); + let (owner, name) = s(item, "repo").split_once('/')?; + let source = match s(item, "ticket_source") { + "jira" => TicketSource::Jira, + "alert" => TicketSource::Alert, + _ => TicketSource::Github, + }; + let (owner, name) = if matches!(source, TicketSource::Jira) { + (String::new(), String::new()) + } else { + (owner.to_string(), name.to_string()) + }; + let error = format!("{} {}", s(item, "error_message"), s(item, "error")); + Some(TicketMessage { + team_id: s(item, "team_id").to_string(), + installation_id: n(item, "installation_id"), + ticket_id: s(item, "ticket_id").to_string(), + title: s(item, "title").to_string(), + body: if matches!(source, TicketSource::Github) { + String::new() + } else { + s(item, "ticket_body").to_string() + }, + source, + repo_owner: owner, + repo_name: name, + issue_number: n(item, "issue_number"), + sender: "CoderHelm".to_string(), + resume_from: common::run_status::retry_resumes(s(item, "current_pass"), &error) + .then(|| run_id.to_string()), + ..Default::default() + }) +} + +/// Starts the waiting run `item` again (see [`retry_ticket`]), after it is +/// marked superseded while it still waits. `what`: what arrived. +pub async fn wake_item(state: &WorkerState, item: &Item, what: &str) -> bool { + let team_id = s(item, "team_id"); + let run_id = s(item, "run_id"); + let Some(ticket) = retry_ticket(item) else { + return false; + }; + let ended = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #s = :s, status_run_id = :sri, updated_at = :t") + .condition_expression("#s = :waiting") + .expression_attribute_names("#s", "status") + .run_status( + ":s", + &common::run_ending::gate( + run_id, + &common::run_ending::superseded(&format!( + "the run CoderHelm started by itself when {what}" + )), + ), + ) + .expression_attribute_values(":waiting", attr_s(run_wake::WAITING)) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await; + if ended.is_err() { + return false; + } + super::release_ticket_lock(state, team_id, &ticket.ticket_id).await; + let Ok(body) = serde_json::to_string(&WorkerMessage::Ticket(ticket)) else { + return false; + }; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .send() + .await + { + Ok(_) => { + info!(run_id, what, "Waiting run started again by itself"); + true + } + Err(e) => { + warn!(run_id, error = %e, "Could not queue the woken run"); + false + } + } +} + +/// Every run waiting on the usage limit whose team's limit now allows runs +/// (raised, cleared, or reset by a new month) starts again. Returns how +/// many started. +pub async fn wake_limit_waits(state: &WorkerState) -> usize { + let filter = super::team_runs::Filter { + expr: "#s = :w", + names: vec![("#s", "status")], + values: vec![(":w", attr_s(run_wake::WAITING))], + projection: None, + }; + let items = super::team_runs::matching(state, "Runs waiting on the usage limit", &filter).await; + let mut started = 0; + let mut full: HashSet = HashSet::new(); + for (team, runs) in limit_waits(&items) { + if super::check_budget_exceeded(state, &team).await.is_some() { + full.insert(team); + continue; + } + for item in runs { + if started >= MAX_WOKEN { + break; + } + if wake_item(state, item, "the team's usage limit allowed runs again").await { + started += 1; + } + } + } + if started > 0 || !full.is_empty() { + info!( + started, + still_over = full.len(), + "Runs waiting on the usage limit read" + ); + } + started +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(team: &str, id: &str, status: &str, handback: &str, source: &str) -> Item { + let wait = WaitingOn { + action: "Raise or clear the team's usage limit in Settings".into(), + handback: handback.into(), + ..Default::default() + }; + HashMap::from([ + ("team_id".into(), attr_s(team)), + ("run_id".into(), attr_s(id)), + ("status".into(), attr_s(status)), + ("repo".into(), attr_s("acme/bookstore-web")), + ("ticket_id".into(), attr_s("WEB-7")), + ("ticket_source".into(), attr_s(source)), + ("ticket_body".into(), attr_s("Show the cover image")), + ("current_pass".into(), attr_s("implement")), + (common::run_wait::FIELD_WAITING_ON.into(), wait.to_attr()), + ]) + } + + #[test] + fn only_runs_waiting_on_the_limit_are_read_by_team() { + let items = vec![ + run("T1", "01A", "needs_input", "usage_limit", "jira"), + run("T1", "01B", "needs_input", "product_decision", "jira"), + run("T2", "01C", "needs_input", "usage_limit", "github"), + run("T2", "01D", "completed", "usage_limit", "github"), + ]; + let by_team = limit_waits(&items); + let ids = |t: &str| -> Vec<&str> { by_team[t].iter().map(|i| s(i, "run_id")).collect() }; + assert_eq!(ids("T1"), vec!["01A"]); + assert_eq!(ids("T2"), vec!["01C"]); + } + + #[test] + fn a_woken_run_starts_as_retry_would() { + let t = retry_ticket(&run("T1", "01A", "needs_input", "usage_limit", "jira")).unwrap(); + assert_eq!(t.ticket_id, "WEB-7"); + assert_eq!(t.resume_from.as_deref(), Some("01A")); + assert!( + t.repo_owner.is_empty(), + "a Jira ticket picks its repo again" + ); + assert_eq!(t.body, "Show the cover image"); + let g = retry_ticket(&run("T1", "01B", "needs_input", "usage_limit", "github")).unwrap(); + assert_eq!( + (g.repo_owner.as_str(), g.repo_name.as_str()), + ("acme", "bookstore-web") + ); + assert!(g.body.is_empty(), "GitHub reads the issue again"); + } +} From c3c13cbbe6a990f23ac5bcd9abdc6d9d31a8b371 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 30 Nov 2026 21:12:49 -0500 Subject: [PATCH 4/6] A woken run that couldn't be queued waits again, and only a closed change's stop is read as one - A wake (gateway event or the worker's limit sweep) that marked the waiting run superseded but couldn't queue its new run puts it back to waiting, with the status key and ending it had, only while it still holds that wake's write (common::run_wake::put_back). The ticket is serialized before the write, so only the send can fail after it. - A woken security fix run starts as Retry starts it: a new request for its unit's findings (security::retry_event), not its ticket again. - The change-wait sweep reads a run as "its change closed" only when its wait is that stop (change_wait::waits_on_close). A run keeps the change it waited on after it went on, so a later question, approval or person's stop is never overridden. - A comment no longer restarts a run a person stopped or put back to draft (HumanOnly::PersonAction); only that person's Retry or ready does. - A label item that names production, a release or a publish in any word (deploy-prod, release, CI:DEPLOY_PRODUCTION) stays the team's call. - An update stack still rolling back (_IN_PROGRESS) is told to wait, never to update again or delete. - one_way finds its cut in an ASCII-lowercased copy, so the offset is always a char boundary of the text it cuts. --- services/common/src/change_wait.rs | 41 +++++- services/common/src/live/permissions.rs | 24 +++- services/common/src/person_gate.rs | 37 ++++- services/common/src/pr_steps.rs | 3 +- services/common/src/run_wake.rs | 164 +++++++++++++++++++++- services/gateway/src/routes/run_wake.rs | 133 +++++++++++------- services/worker/src/passes/change_wait.rs | 7 + services/worker/src/passes/run_wake.rs | 41 ++++-- 8 files changed, 375 insertions(+), 75 deletions(-) diff --git a/services/common/src/change_wait.rs b/services/common/src/change_wait.rs index f5b2c40fb..4b18ced3e 100644 --- a/services/common/src/change_wait.rs +++ b/services/common/src/change_wait.rs @@ -276,12 +276,24 @@ pub fn after_close(pr: Option<(&str, bool)>) -> Option { /// itself). pub fn closed_action(dep: &Dependency) -> String { format!( - "Reopen {} on GitHub, or change this ticket; the run goes back to waiting for its merge \ - by itself once it is reopened, and a change to the ticket starts a new run by itself", + "Reopen {} {CLOSED_ASK} the run goes back to waiting for its merge by itself once it is \ + reopened, and a change to the ticket starts a new run by itself", dep.label() ) } +/// The words of [`closed_action`] after the change's label. +const CLOSED_ASK: &str = "on GitHub, or change this ticket;"; + +/// Whether a run's wait, by its action, is the stop [`closed_action`] +/// wrote: its change closed without merging. A run keeps the change it +/// waited on after it went on, so a later wait of another kind (a question, +/// an approval, a person's own stop) is never read as the change closing. +pub fn waits_on_close(action: &str) -> bool { + let a = action.split_whitespace().collect::>().join(" "); + a.starts_with("Reopen ") && a.contains(CLOSED_ASK) +} + /// The reason a run stops when its dependency closed without merging. pub fn closed_reason(dep: &Dependency) -> String { format!( @@ -315,6 +327,31 @@ mod after_close_tests { assert!(!a.contains("press Retry"), "{a}"); assert_eq!(crate::rendered::person_text(&a), None, "{a}"); } + + #[test] + fn only_the_closed_change_stop_is_read_as_its_change_closing() { + let dep = Dependency { + ticket: "WEB-7".into(), + repo: "acme/bookstore-web".into(), + pr: 12, + ..Default::default() + }; + assert!(waits_on_close(&closed_action(&dep))); + assert!(waits_on_close(&closed_action(&Dependency::default()))); + // As the wait stores it: one line, cut to its limit. + let stored: String = closed_action(&dep).chars().take(200).collect(); + assert!(waits_on_close(&stored), "{stored}"); + for other in [ + "Write the product decision in a comment on the ticket; the run continues by itself \ + when the comment arrives", + crate::run_wake::APPROVAL_ACTION, + "Decide whether the run goes on: press Retry on the run in CoderHelm to start it \ + again, or leave it stopped", + "", + ] { + assert!(!waits_on_close(other), "{other}"); + } + } } #[cfg(test)] diff --git a/services/common/src/live/permissions.rs b/services/common/src/live/permissions.rs index d29385c45..6f4a3423c 100644 --- a/services/common/src/live/permissions.rs +++ b/services/common/src/live/permissions.rs @@ -424,7 +424,13 @@ pub fn stack_failed_fix(status: &str, stack: &str, account: &str, region: &str) } else { format!("account {account} ({region})") }; - if status == "UPDATE_ROLLBACK_FAILED" { + if status.ends_with("_IN_PROGRESS") { + // A rollback still running takes no update or delete yet. + format!( + "AWS is still rolling back the stack {stack} in {at} ({status}); nothing to do until \ + it finishes. This page checks again by itself." + ) + } else if status == "UPDATE_ROLLBACK_FAILED" { format!( "An AWS admin in {at} continues the rollback of the stack {stack} (CloudFormation, \ Stack actions, Continue update rollback). This page checks again by itself once the \ @@ -1026,6 +1032,22 @@ mod tests { assert!(!f.contains("deletes"), "{f}"); assert_eq!(crate::rendered::person_text(&f), None, "{f}"); } + // A rollback still running: no update, no delete, only a wait. + for status in [ + "UPDATE_ROLLBACK_IN_PROGRESS", + "ROLLBACK_IN_PROGRESS", + "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", + ] { + let f = stack_failed_fix( + status, + "CoderHelmLogReaderUpdate", + "111122223333", + "us-east-1", + ); + assert!(!f.contains("deletes") && !f.contains("update again"), "{f}"); + assert!(f.contains("checks again by itself"), "{f}"); + assert_eq!(crate::rendered::person_text(&f), None, "{f}"); + } c.update_stack = UpdateStack::NotFound; assert!(c.problem(false).is_none()); let p = c.problem(true).unwrap(); diff --git a/services/common/src/person_gate.rs b/services/common/src/person_gate.rs index dcb6f0ba5..765979934 100644 --- a/services/common/src/person_gate.rs +++ b/services/common/src/person_gate.rs @@ -514,7 +514,8 @@ fn asks_testing(a: &Ask) -> bool { /// CoderHelm adds labels itself through the issues API, whatever workflow a /// label starts (a preview deploy, an end-to-end run): a label that starts /// a deploy needs no deploy permission. Only a label that releases to -/// production stays the team's call. +/// production stays the team's call: one whose item names production, a +/// release or a publish in any word (`deploy-prod`, `release`, `prod`). pub fn adds_labels(a: &Ask) -> bool { let t = one_line(&a.text).to_lowercase(); let t = t @@ -533,7 +534,15 @@ pub fn adds_labels(a: &Ask) -> bool { ] .iter() .any(|p| t.starts_with(p)) - && !t.contains("production") + && !releases(t) +} + +/// Whether a label item's words name a release to production: a word (split +/// on anything but letters and digits) that is or starts with `prod`, or +/// one that names a release or a publish. +fn releases(t: &str) -> bool { + t.split(|c: char| !c.is_ascii_alphanumeric()) + .any(|w| w.starts_with("prod") || w.starts_with("release") || w.starts_with("publish")) } /// Whether the item's action is a deploy: its words start with one, or the @@ -1912,4 +1921,28 @@ mod tests { assert!(!paid_action(t), "{t}"); } } + + #[test] + fn a_label_that_releases_to_production_stays_the_teams_call() { + let ask = |t: &str| Ask { + text: t.into(), + ..Default::default() + }; + for t in [ + "Add the label `deploy-preview` to start the preview", + "Add label e2e-run", + "Before merging: add the PR label `needs-qa`", + ] { + assert!(adds_labels(&ask(t)), "{t}"); + } + for t in [ + "Add label deploy-prod", + "Add the `release` label", + "Add the label CI:DEPLOY_PRODUCTION", + "After merging: apply the label publish-npm", + "Add the label to ship to production", + ] { + assert!(!adds_labels(&ask(t)), "{t}"); + } + } } diff --git a/services/common/src/pr_steps.rs b/services/common/src/pr_steps.rs index f84293059..3b87ff85b 100644 --- a/services/common/src/pr_steps.rs +++ b/services/common/src/pr_steps.rs @@ -177,7 +177,8 @@ pub fn is_command(how: &str) -> bool { /// what to run; the unblock is what lets CoderHelm run it. pub fn one_way(unblock: &str) -> String { let t = one_line(unblock); - let low = t.to_lowercase(); + // ASCII-only, so an offset found here is a char boundary in `t`. + let low = t.to_ascii_lowercase(); let cut = [ ", or run the command yourself", " or run the command yourself", diff --git a/services/common/src/run_wake.rs b/services/common/src/run_wake.rs index 9c3982eb4..a1f9e948f 100644 --- a/services/common/src/run_wake.rs +++ b/services/common/src/run_wake.rs @@ -22,8 +22,18 @@ //! //! Every wait names one of these in its action ([`CONTINUES`]), so what a //! person reads is what happens. Only a decision a person makes about the -//! run itself (an approval its policy asks for) waits for that decision, -//! where it is made. +//! run itself (an approval its policy asks for, or a person's own stop or +//! draft of it) waits for that decision, where it is made: a comment never +//! restarts a run a person stopped. +//! +//! A wake marks the waiting run superseded before it queues the new run. If +//! the queue refuses, [`put_back`] writes the run back to waiting (only +//! while it still holds that wake's write), so the next event, sweep or +//! Retry finds it again instead of a superseded run with no successor. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; use crate::handback::HumanOnly; @@ -62,12 +72,16 @@ pub const WAITING: &str = "needs_input"; /// Whether `wake` starts a run that waits on a person for `why` (the wait's /// `handback`; `None` when the wait names none). A comment answers every -/// wait but the two a comment can't settle: the usage limit (only the -/// setting lifts it) and an approval the team's policy asks for (answered -/// where the policy asks). +/// wait but the three a comment can't settle: the usage limit (only the +/// setting lifts it), an approval the team's policy asks for (answered +/// where the policy asks), and a person's own action on the run (a stop, a +/// PR put back to draft: only that person's Retry or ready undoes it). pub fn wakes(why: Option, wake: Wake) -> bool { match wake { - Wake::Comment => !matches!(why, Some(HumanOnly::UsageLimit | HumanOnly::Approval)), + Wake::Comment => !matches!( + why, + Some(HumanOnly::UsageLimit | HumanOnly::Approval | HumanOnly::PersonAction) + ), Wake::Access => matches!(why, Some(HumanOnly::MissingAccess | HumanOnly::Credential)), Wake::Limit => why == Some(HumanOnly::UsageLimit), Wake::Approval => why == Some(HumanOnly::Approval), @@ -151,6 +165,91 @@ pub fn access_reaches(repo: &str, wait_text: &str, added: &[String]) -> bool { }) } +/// The write that undoes a wake whose new run couldn't be queued: the run +/// `item` (as read before the wake) goes back to waiting with the status +/// key ([`crate::run_ending::restored_sri`]) and ending it had, only while it still holds the wake's own write +/// (`woken_sri`, the status key it set, and `woken_at`, its `updated_at`). +#[derive(Debug, Clone, PartialEq)] +pub struct PutBack { + pub update: String, + pub condition: &'static str, + pub values: Vec<(&'static str, AttributeValue)>, +} + +/// [`PutBack`] for `item` after a wake that wrote `woken_sri` at `woken_at`. +pub fn put_back_write( + item: &HashMap, + woken_sri: AttributeValue, + woken_at: &str, +) -> PutBack { + let run_id = item + .get("run_id") + .and_then(|v| v.as_s().ok()) + .map(String::as_str) + .unwrap_or(""); + // Only a waiting run is woken, so its key was the waiting one. + let mut values = vec![ + (":waiting", AttributeValue::S(WAITING.into())), + (":sri", crate::run_ending::restored_sri(WAITING, run_id)), + (":woken_sri", woken_sri), + (":woken_at", AttributeValue::S(woken_at.into())), + (":now", AttributeValue::S(chrono::Utc::now().to_rfc3339())), + ]; + let ending = crate::run_ending::FIELD_ENDING; + let update = match item.get(ending) { + Some(e) => { + values.push((":ending", e.clone())); + format!( + "SET #s = :waiting, status_run_id = :sri, updated_at = :now, {ending} = :ending" + ) + } + None => { + format!("SET #s = :waiting, status_run_id = :sri, updated_at = :now REMOVE {ending}") + } + }; + PutBack { + update, + condition: "status_run_id = :woken_sri AND updated_at = :woken_at", + values, + } +} + +/// Puts the woken run `item` back to waiting after its new run couldn't be +/// queued ([`put_back_write`]). Returns whether it was put back; `false` +/// when something else moved it meanwhile (a Retry, another wake). +pub async fn put_back( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + item: &HashMap, + woken_sri: AttributeValue, + woken_at: &str, +) -> bool { + let key = |k: &str| { + item.get(k) + .cloned() + .unwrap_or_else(|| AttributeValue::S(String::new())) + }; + let w = put_back_write(item, woken_sri, woken_at); + let mut req = dynamo + .update_item() + .table_name(table) + .key("team_id", key("team_id")) + .key("run_id", key("run_id")) + .update_expression(w.update) + .condition_expression(w.condition) + .expression_attribute_names("#s", "status"); + for (k, v) in w.values { + req = req.expression_attribute_values(k, v); + } + match req.send().await { + Ok(_) => true, + Err(e) => { + tracing::warn!(error = %e, "A woken run couldn't be put back to waiting"); + false + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -163,7 +262,6 @@ mod tests { HumanOnly::Credential, HumanOnly::MissingAccess, HumanOnly::HeldByAnother, - HumanOnly::PersonAction, HumanOnly::Unrepaired, ] { assert!(wakes(Some(why), Wake::Comment), "{why:?}"); @@ -173,6 +271,58 @@ mod tests { assert!(!wakes(Some(HumanOnly::Approval), Wake::Comment)); } + #[test] + fn a_comment_never_restarts_a_run_a_person_stopped_or_drafted() { + assert!(!wakes(Some(HumanOnly::PersonAction), Wake::Comment)); + assert!(!wakes_run("needs_input", "person_action", Wake::Comment)); + assert_eq!(alert_wake("needs_input", "person_action", false), None); + assert_eq!( + alert_wake("needs_input", "person_action", true), + Some(AlertWake::Close) + ); + } + + #[test] + fn a_wake_whose_run_was_not_queued_goes_back_to_waiting() { + let s = |v: &str| AttributeValue::S(v.into()); + let ending = AttributeValue::M(HashMap::from([("kind".to_string(), s("waiting"))])); + let item = HashMap::from([ + ("team_id".to_string(), s("T1")), + ("run_id".to_string(), s("01A")), + ("status".to_string(), s("needs_input")), + ("status_run_id".to_string(), s("needs_input#01A")), + (crate::run_ending::FIELD_ENDING.to_string(), ending.clone()), + ]); + let w = put_back_write(&item, s("superseded#01A"), "2026-03-02T10:00:00Z"); + let val = |k: &str| { + w.values + .iter() + .find(|(n, _)| *n == k) + .map(|(_, v)| v.clone()) + }; + assert_eq!(val(":waiting"), Some(s(WAITING))); + assert_eq!(val(":sri"), Some(s("needs_input#01A")), "the key it had"); + assert_eq!(val(":ending"), Some(ending), "the ending it had"); + assert_eq!(val(":woken_sri"), Some(s("superseded#01A"))); + assert!(w + .update + .starts_with("SET #s = :waiting, status_run_id = :sri")); + // Only the wake's own write is undone: a Retry or another wake that + // moved the run meanwhile wrote another key or time. + assert!(w.condition.contains("status_run_id = :woken_sri")); + assert!(w.condition.contains("updated_at = :woken_at")); + + let mut bare = item.clone(); + bare.remove(crate::run_ending::FIELD_ENDING); + bare.remove("status_run_id"); + let w = put_back_write(&bare, s("superseded#01A"), "t"); + assert!(w.update.ends_with("REMOVE run_ending"), "{}", w.update); + assert!(w + .values + .iter() + .any(|(n, v)| *n == ":sri" && *v == s("needs_input#01A"))); + } + #[test] fn access_and_the_limit_wake_only_their_own_waits() { assert!(wakes(Some(HumanOnly::MissingAccess), Wake::Access)); diff --git a/services/gateway/src/routes/run_wake.rs b/services/gateway/src/routes/run_wake.rs index 20bd780b1..291bb6d1c 100644 --- a/services/gateway/src/routes/run_wake.rs +++ b/services/gateway/src/routes/run_wake.rs @@ -21,7 +21,8 @@ //! with the waiting run's plan and branch when its plan wasn't what stopped //! it, and the waiting run marked as superseded by the new one. Only a run //! still waiting is woken (a conditional write), so two events never start -//! two runs. +//! two runs. A run whose new run couldn't be queued is put back to waiting +//! (`common::run_wake::put_back`), so a later event or a Retry starts it. use std::collections::HashMap; @@ -163,24 +164,53 @@ pub async fn wake_team( started } -/// Starts the waiting run `item` again: its ticket, as a person's Retry -/// would, after the run is marked superseded (only while it still waits). +/// Starts the waiting run `item` again as a person's Retry would, after the +/// run is marked superseded (only while it still waits): a security fix +/// run as a new request for its unit's findings as they stand now (the +/// Retry's own decision, `security::retry_event`), any other run as its +/// ticket again. When the new run can't be queued, the waiting run is put +/// back to waiting (`common::run_wake::put_back`). async fn wake_one(state: &AppState, team_id: &str, item: &Item, what: &str) -> bool { let run_id = text(item, "run_id").to_string(); - let mut ticket = - match super::api::retry_message_as(state, team_id, "CoderHelm".to_string(), None, item) + let ticket_id = text(item, "ticket_id").to_string(); + let start = match super::security::retry_event(state, team_id, &ticket_id, "CoderHelm").await { + Some(event) => Start::Security(event), + None => { + let mut ticket = match super::api::retry_message_as( + state, + team_id, + "CoderHelm".to_string(), + None, + item, + ) .await - { - Ok(t) => t, - Err(_) => { - warn!( - run_id, - "A waiting run's ticket couldn't be read to start it again" - ); - return false; + { + Ok(t) => t, + Err(_) => { + warn!( + run_id, + "A waiting run's ticket couldn't be read to start it again" + ); + return false; + } + }; + ticket.resume_from = resumed_from(item); + match serde_json::to_string(&WorkerMessage::Ticket(ticket)) { + Ok(b) => Start::Ticket(b), + Err(e) => { + warn!(run_id, error = %e, "Could not serialize the woken run's ticket"); + return false; + } } - }; - ticket.resume_from = resumed_from(item); + } + }; + let woken = common::run_ending::gate( + &run_id, + &common::run_ending::superseded(&format!( + "the run CoderHelm started by itself when {what}" + )), + ); + let woken_at = chrono::Utc::now().to_rfc3339(); // Only a run still waiting: a second event, or a person's Retry // meanwhile, already started it. let ended = state @@ -192,48 +222,57 @@ async fn wake_one(state: &AppState, team_id: &str, item: &Item, what: &str) -> b .update_expression("SET #status = :s, status_run_id = :sri, updated_at = :t") .condition_expression("#status = :waiting") .expression_attribute_names("#status", "status") - .run_status( - ":s", - &common::run_ending::gate( - &run_id, - &common::run_ending::superseded(&format!( - "the run CoderHelm started by itself when {what}" - )), - ), - ) + .run_status(":s", &woken) .expression_attribute_values(":waiting", AttributeValue::S(run_wake::WAITING.into())) - .expression_attribute_values(":t", AttributeValue::S(chrono::Utc::now().to_rfc3339())) + .expression_attribute_values(":t", AttributeValue::S(woken_at.clone())) .send() .await; if ended.is_err() { info!(run_id, "Waiting run already moved on — not started again"); return false; } - super::api::delete_ticket_lock(state, team_id, &ticket.ticket_id).await; - let body = match serde_json::to_string(&WorkerMessage::Ticket(ticket)) { - Ok(b) => b, - Err(e) => { - warn!(run_id, error = %e, "Could not serialize the woken run's ticket"); - return false; + let queued = match start { + Start::Security(event) => super::security::queue_retry(state, event).await.is_ok(), + Start::Ticket(body) => { + super::api::delete_ticket_lock(state, team_id, &ticket_id).await; + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .send() + .await + { + Ok(_) => true, + Err(e) => { + warn!(run_id, error = %e, "Could not queue the woken run's ticket"); + false + } + } } }; - match state - .sqs - .send_message() - .queue_url(&state.config.ticket_queue_url) - .message_body(body) - .send() - .await - { - Ok(_) => { - info!(run_id, what, "Waiting run started again by itself"); - true - } - Err(e) => { - warn!(run_id, error = %e, "Could not queue the woken run's ticket"); - false - } + if queued { + info!(run_id, what, "Waiting run started again by itself"); + return true; } + // Back to waiting, so the next event or a Retry starts it. + run_wake::put_back( + &state.dynamo, + &state.config.runs_table_name, + item, + woken.sri_attr(), + &woken_at, + ) + .await; + false +} + +/// What a woken run is started again with. +enum Start { + /// A security fix run's new request for its unit's findings. + Security(crate::models::SecurityEventMessage), + /// The ticket message, serialized for the queue. + Ticket(String), } /// A run of the team by id. diff --git a/services/worker/src/passes/change_wait.rs b/services/worker/src/passes/change_wait.rs index 42471ba60..ce7f13ff6 100644 --- a/services/worker/src/passes/change_wait.rs +++ b/services/worker/src/passes/change_wait.rs @@ -292,6 +292,13 @@ async fn check_closed(state: &WorkerState) -> usize { if s(&item, "status") != common::run_status::NEEDS_INPUT { continue; } + // Only a run whose wait is the closed change's stop: a run that went + // on after its change merged keeps the field, and a later wait of + // another kind is that wait's to end. + let wait = common::run_wait::WaitingOn::of_item(&item).unwrap_or_default(); + if !cw::waits_on_close(&wait.action) { + continue; + } let Some(dep) = Dependency::from_json(s(&item, cw::FIELD)) else { continue; }; diff --git a/services/worker/src/passes/run_wake.rs b/services/worker/src/passes/run_wake.rs index d94867973..9e0c57560 100644 --- a/services/worker/src/passes/run_wake.rs +++ b/services/worker/src/passes/run_wake.rs @@ -7,7 +7,9 @@ //! run of a team whose limit allows runs again, the way Retry does: the //! ticket again, taking up the waiting run's plan and branch, with the //! waiting run marked superseded by one conditional write (only while it -//! still waits), so two sweeps never start two runs. +//! still waits), so two sweeps never start two runs. A run whose new run +//! couldn't be queued is put back to waiting (`run_wake::put_back`), so the +//! next sweep starts it. use std::collections::{HashMap, HashSet}; @@ -99,6 +101,17 @@ pub async fn wake_item(state: &WorkerState, item: &Item, what: &str) -> bool { let Some(ticket) = retry_ticket(item) else { return false; }; + let ticket_id = ticket.ticket_id.clone(); + let Ok(body) = serde_json::to_string(&WorkerMessage::Ticket(ticket)) else { + return false; + }; + let woken = common::run_ending::gate( + run_id, + &common::run_ending::superseded(&format!( + "the run CoderHelm started by itself when {what}" + )), + ); + let woken_at = chrono::Utc::now().to_rfc3339(); let ended = state .dynamo .update_item() @@ -108,26 +121,15 @@ pub async fn wake_item(state: &WorkerState, item: &Item, what: &str) -> bool { .update_expression("SET #s = :s, status_run_id = :sri, updated_at = :t") .condition_expression("#s = :waiting") .expression_attribute_names("#s", "status") - .run_status( - ":s", - &common::run_ending::gate( - run_id, - &common::run_ending::superseded(&format!( - "the run CoderHelm started by itself when {what}" - )), - ), - ) + .run_status(":s", &woken) .expression_attribute_values(":waiting", attr_s(run_wake::WAITING)) - .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .expression_attribute_values(":t", attr_s(&woken_at)) .send() .await; if ended.is_err() { return false; } - super::release_ticket_lock(state, team_id, &ticket.ticket_id).await; - let Ok(body) = serde_json::to_string(&WorkerMessage::Ticket(ticket)) else { - return false; - }; + super::release_ticket_lock(state, team_id, &ticket_id).await; match state .sqs .send_message() @@ -142,6 +144,15 @@ pub async fn wake_item(state: &WorkerState, item: &Item, what: &str) -> bool { } Err(e) => { warn!(run_id, error = %e, "Could not queue the woken run"); + // Back to waiting, so the next sweep starts it. + run_wake::put_back( + &state.dynamo, + &state.config.runs_table_name, + item, + woken.sri_attr(), + &woken_at, + ) + .await; false } } From 4ed73a4327f3eb62378216f5357e19a0041f19d4 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 30 Nov 2026 22:59:17 -0500 Subject: [PATCH 5/6] A run the token limit refuses pauses and goes on by itself, and no error reads as one a person must repair A model call refused by the team's monthly token limit ("limit reached") was read as an error nobody knew, so the run stopped as "an error it doesn't know how to repair ... put it right, then press Retry" and waited on a person past the month's turn. - The refusal is a typed pause (common::token_room, Kind::TokenLimit): the run keeps its continuation and resumes in place, from the step that was refused, when the month turns or the limit is raised. #924's wake_limit_waits hands these waits to token_room::wake_team. - New runs wait for token room when what is left is less than a run of their kind takes; a run under way waits before building; runs in progress come first on what is left. - Warnings at 80% and 95%, once each a month, with the day the limit runs out at this pace; /api/usage gives warn_level and projected_at. - A schedule at 00:00 and 00:01 UTC on the 1st sends the sweep; a saved limit sends it at once; a paused run gets no reminder. - A teammate's branch is left as it is: the run works on -N and says so once. - An error nobody classified is CoderHelm's own problem: retried with longer waits, then parked with an internal alert (#930's own_problems); the generic frame is gone and person_text refuses it. - Runs an older release stopped this way are found by their stored words and resumed after the deploy. - Incident case xg_token_limit_pauses_and_resumes. --- docs/api/openapi.json | 121 ++- .../vo_pass_errors_recover_not_fail.md | 2 +- .../xg_token_limit_pauses_and_resumes.md | 5 + docs/self-host/email.md | 2 +- infra/lib/api-stack.ts | 17 + infra/lib/email-stack.ts | 11 +- lambda/stuck-run-cleanup/handler.py | 8 +- lambda/tests/test_stuck_run_cleanup.py | 16 + services/common/src/lib.rs | 3 + .../src/mail/golden/token_limit_reached.html | 2 +- .../src/mail/golden/token_limit_reached.txt | 2 +- .../common/src/mail/golden/token_warning.html | 2 +- .../common/src/mail/golden/token_warning.txt | 4 +- services/common/src/mail/golden_tests.rs | 2 +- services/common/src/mail/templates.rs | 6 +- services/common/src/rendered.rs | 8 + services/common/src/run_fail.rs | 105 +- services/common/src/run_recovery.rs | 217 +++-- services/common/src/run_wait.rs | 7 + services/common/src/token_limits.rs | 8 +- services/common/src/token_room.rs | 914 ++++++++++++++++++ services/gateway/src/routes/api.rs | 105 +- services/gateway/src/routes/github_webhook.rs | 24 +- services/gateway/src/routes/jira_webhook.rs | 24 +- services/gateway/src/routes/run_wake.rs | 8 +- services/worker/src/clients/email.rs | 8 +- services/worker/src/clients/github.rs | 107 ++ services/worker/src/passes/change_wait.rs | 1 + .../vo_pass_errors_recover_not_fail.rs | 45 +- .../incidents/wz_waits_go_on_by_themselves.rs | 13 +- .../xg_token_limit_pauses_and_resumes.rs | 664 +++++++++++++ services/worker/src/passes/mod.rs | 223 ++++- services/worker/src/passes/recover.rs | 45 +- services/worker/src/passes/run_wake.rs | 20 +- services/worker/src/passes/token_room.rs | 422 ++++++++ 35 files changed, 2949 insertions(+), 222 deletions(-) create mode 100644 docs/incidents/xg_token_limit_pauses_and_resumes.md create mode 100644 services/common/src/token_room.rs create mode 100644 services/worker/src/passes/incidents/xg_token_limit_pauses_and_resumes.rs create mode 100644 services/worker/src/passes/token_room.rs diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 2c0ad4268..fbb0270a8 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -5553,6 +5553,94 @@ }, "type": "object" }, + "RunPause": { + "description": "A run paused on the team's monthly token limit. It resumes by itself\nwhen the month turns (`resumes_at`) or as soon as an admin raises the\nlimit.", + "properties": { + "kind": { + "description": "`token_limit`: a model call was refused, the run keeps its work and\ngoes on from where it stopped. `token_room`: a new run waits because\nwhat is left is less than a run like it takes.", + "examples": [ + "token_limit" + ], + "type": "string" + }, + "limit": { + "description": "The limit's name.", + "examples": [ + "new tokens" + ], + "type": "string" + }, + "line": { + "description": "The one line, with the time in UTC.", + "examples": [ + "Paused: this month's token limit is used up (40.3M of 40M). Resumes by itself on Dec 1, 00:00 UTC when the month turns, or as soon as an admin raises the limit." + ], + "type": "string" + }, + "max": { + "description": "The limit.", + "examples": [ + 40000000 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "need": { + "description": "For `token_room`: what a run like this takes.", + "examples": [ + 0 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "resumes_at": { + "description": "When the month turns and it resumes by itself (RFC 3339, UTC).", + "examples": [ + "2026-12-01T00:00:00+00:00" + ], + "type": "string" + }, + "room": { + "description": "For `token_room`: what is left for new runs.", + "examples": [ + 0 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "settings_path": { + "description": "Where an admin raises the limit.", + "examples": [ + "/settings/budget" + ], + "type": "string" + }, + "used": { + "description": "This month's count of that limit.", + "examples": [ + 40300000 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "kind", + "limit", + "used", + "max", + "room", + "need", + "resumes_at", + "line", + "settings_path" + ], + "type": "object" + }, "RunPrReview": { "description": "CoderHelm's latest review verdict on the run's pull request.", "properties": { @@ -6290,6 +6378,17 @@ ], "type": "string" }, + "pause": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunPause", + "description": "The run waits on the team's monthly token limit and resumes by\nitself: shown as paused, never as a person's step. Null for every\nother wait." + } + ] + }, "since": { "description": "When the wait started (RFC 3339).", "examples": [ @@ -7257,6 +7356,16 @@ "minimum": 0, "type": "integer" }, + "projected_at": { + "description": "When it runs out at this month's pace (RFC 3339), when that falls\nbefore the month turns. Null otherwise.", + "examples": [ + "2026-11-26T14:00:00+00:00" + ], + "type": [ + "string", + "null" + ] + }, "used": { "description": "What it counts so far this month.", "examples": [ @@ -7265,12 +7374,22 @@ "format": "int64", "minimum": 0, "type": "integer" + }, + "warn_level": { + "description": "The warning level it has crossed: 0, 80, 95 or 100 (percent). The\ndashboard warns admins at 80 and 95, once each a month.", + "examples": [ + 80 + ], + "format": "int32", + "minimum": 0, + "type": "integer" } }, "required": [ "kind", "max", - "used" + "used", + "warn_level" ], "type": "object" }, diff --git a/docs/incidents/vo_pass_errors_recover_not_fail.md b/docs/incidents/vo_pass_errors_recover_not_fail.md index 76574b0c5..1bf51410f 100644 --- a/docs/incidents/vo_pass_errors_recover_not_fail.md +++ b/docs/incidents/vo_pass_errors_recover_not_fail.md @@ -2,4 +2,4 @@ **What happened:** Any error a pass returned that the run had no special case for ended the run as failed, usually with the raw HTTP error as its reason. Some were passing (a 5xx in the middle of the coder's work), some were states CoderHelm could put right itself (a branch that wasn't there, a base branch someone deleted), and the run tried the same thing again in a fresh step without changing anything until its ceilings ran out. -**The guarantee:** Every pass error takes one recovery path before anything is marked failed. It is classified as transient (tried again after a backoff), a state CoderHelm repairs (repaired, then the same pass resumes from its checkpoint, with no second plan and no repeated ticket or pull request), or something only a person has. The same error again with no progress takes the next repair strategy, never the same one. Only a person's step stops a run, as "needs you" with what to do in plain words. An error nobody classified is tried once more and then stops as "needs you", never as failed. Runs left failed on an error CoderHelm now gets past are resumed by the self-heal sweep, on deploy and every 15 minutes, once per run per deploy. +**The guarantee:** Every pass error takes one recovery path before anything is marked failed. It is classified as transient (tried again after a backoff), a state CoderHelm repairs (repaired, then the same pass resumes from its checkpoint, with no second plan and no repeated ticket or pull request), or something only a person has. The same error again with no progress takes the next repair strategy, never the same one. Only a person's step stops a run, as "needs you" with what to do in plain words. An error nobody classified is CoderHelm's own problem: tried again with longer waits, then parked for the self-heal sweep with an internal alert for its maintainers, never a person's step (see `xg`). Runs left failed on an error CoderHelm now gets past are resumed by the self-heal sweep, on deploy and every 15 minutes, once per run per deploy. diff --git a/docs/incidents/xg_token_limit_pauses_and_resumes.md b/docs/incidents/xg_token_limit_pauses_and_resumes.md new file mode 100644 index 000000000..04770641a --- /dev/null +++ b/docs/incidents/xg_token_limit_pauses_and_resumes.md @@ -0,0 +1,5 @@ +# xg. `xg_token_limit_pauses_and_resumes` + +**What happened:** Several runs on one install planned, then stopped at the start of building. Their page said "CoderHelm met an error it doesn't know how to repair, and stopped without trying again: Monthly new tokens limit reached", headed "Look at what stopped the run, put it right, then press Retry" and "Needs a person". The limit is counted per UTC month, but when the month turned nothing resumed them; they waited for hours until a person pressed Retry. The error classifier knew only the older wording of the limit ("limit exceeded"), so the refusal every model call now gives ("limit reached") read as an error nobody knew. No warning came before the limit, and new runs kept starting into it. The same night another run stopped with the same frame because the ticket's branch held a teammate's commits and had no pull request. + +**The guarantee:** A model call the team's token limit refuses is a typed pause, never an unknown error and never a person's step. The run keeps its plan, branch and finished steps; its continuation is kept, and it resumes in place from the step that was refused when the month turns (a schedule at 00:00 UTC on the 1st) or as soon as an admin raises the limit. The page says it in one line, with when it resumes. A new run whose kind takes more than the room left waits for token room instead of starting, and runs already in progress come first on what is left. Admins are warned at 80% and 95%, once each a month, with the day the limit runs out at this month's pace. A teammate's branch is left as it is: the run works on the next free `-N` and says so once. "An error it doesn't know how to repair ... put it right, then press Retry" can't be produced: an error nobody classified is CoderHelm's own problem, with an internal alert, one plain line and retries with longer waits. Runs an older release stopped this way are found by their stored words and go on by themselves after the deploy. diff --git a/docs/self-host/email.md b/docs/self-host/email.md index 119af7920..6405836b3 100644 --- a/docs/self-host/email.md +++ b/docs/self-host/email.md @@ -16,7 +16,7 @@ A self-hosted install sends the emails it needs, and nothing else until you turn | Team invites | Essential | The only way an invited person learns how to join. | | Plugin approval requests | Essential | A named approver must approve a plugin draft before it publishes. | | Knowledge source sign-in alerts | Essential | Tells admins a knowledge source stopped syncing. | -| Token limit warnings | Essential | Tells the team before work stops at the monthly limit. Each person can turn these off. | +| Token limit warnings | Essential | Tells the team at 80% and 95% of a monthly limit, once each a month, with the day it runs out at this pace, and when it is reached. Runs that reach it pause and go on by themselves. Each person can turn these off. | | Support ticket updates | Essential | Replies and status changes on tickets someone filed. | | Webhook endpoint turned off | Essential | Tells a team's admins when CoderHelm stopped sending to an endpoint that failed for days. | | Two-factor lockout alerts | Essential | Tells admins and owners when someone's two-factor sign-in was paused after too many wrong codes. | diff --git a/infra/lib/api-stack.ts b/infra/lib/api-stack.ts index c28bf9bfc..febd52836 100644 --- a/infra/lib/api-stack.ts +++ b/infra/lib/api-stack.ts @@ -439,6 +439,23 @@ export class ApiStack extends cdk.Stack { ], }); + // The month's turn: the token limit's counters start again at 00:00 UTC + // on the 1st, and runs paused on the limit (or waiting for room) go on + // then, not at the next 15-minute tick. Sent at 00:00 and again at 00:01 + // in case the first lands before the new month's counters are read. + new events.Rule(this, "TokenMonthTurnSchedule", { + ruleName: `${prefix}-token-month-turn`, + description: "Resume runs paused on the token limit when the month turns", + schedule: events.Schedule.cron({ minute: "0,1", hour: "0", day: "1" }), + targets: [ + new targets.SqsQueue(this.ticketQueue, { + message: events.RuleTargetInput.fromObject({ + type: "self_heal_sweep", + }), + }), + ], + }); + // Paused agent work: every 5 min, send again the work kept while a // team's agents were paused once the pause has ended (an until-time // passing needs nobody to click anything). Does nothing when no team is diff --git a/infra/lib/email-stack.ts b/infra/lib/email-stack.ts index 4923edccd..ac81011cf 100644 --- a/infra/lib/email-stack.ts +++ b/infra/lib/email-stack.ts @@ -201,7 +201,8 @@ export class EmailStack extends cdk.Stack { }); // Token limit emails: one per limit (new tokens, cache read, cache write) - // at 80% and at 100%. {{limit_name}} names the limit. + // at 80%, 95% and 100%, each once a month. {{limit_name}} names the + // limit; {{pace}} says when it runs out at this month's pace. new ses.CfnTemplate(this, "TokenWarningTemplate", { template: { templateName: `${prefix}-token-warning`, @@ -388,7 +389,7 @@ const TOKEN_WARNING_HTML = EMAIL_WRAPPER(`

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

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

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

Monthly {{limit_name}} limit reached

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

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

Monthly token limit reached, new work waits

 
-

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

Used10.0M
Limit10M
MonthOctober 2026

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

See usage
+

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

Used10.0M
Limit10M
MonthOctober 2026

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

See usage

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

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

81% of the monthly token limit used

 
-

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

Used8.1M
Limit10M
MonthOctober 2026

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

See usage
+

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

Used8.1M
Limit10M
MonthOctober 2026

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

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

See usage

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

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