diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 9ae5557c3..f0a533f47 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -3171,6 +3171,23 @@ "null" ] }, + "prs": { + "description": "Every pull request the run opened, each with its own repository\n(`repo`, `pr_number`, `branch`, `url`, and `outcome` once it ended).\nBuild links and labels from these: in a run across several\nrepositories, `repo` and `pr_numbers` don't pair up.", + "examples": [ + [ + { + "branch": "coderhelm/web-42-login-rate-limit", + "pr_number": 318, + "repo": "acme/web", + "url": "https://github.com/acme/web/pull/318" + } + ] + ], + "items": { + "type": "object" + }, + "type": "array" + }, "questions": { "description": "What the run asked when it stopped as `needs_input`, one question\neach. Answer them with `POST /api/runs/{run_id}/answer`. Empty when\nit asked nothing it can take answers for here.", "items": { @@ -3301,6 +3318,7 @@ }, "required": [ "run_id", + "prs", "tokens_in", "tokens_out", "cache_read_tokens", diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index 29e390ca7..0b652e4ce 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -55,6 +55,7 @@ "ci_fix": "CI fix round", "review_fix": "review fix round", "feedback": "feedback round", + "security_fix": "security fix round", } _dynamodb = None @@ -142,6 +143,8 @@ def round_kind(run, pass_name): return "ci_fix" if p == "feedback": return "feedback" + if p == "security_fix": + return "security_fix" return "review_fix" diff --git a/lambda/tests/test_stuck_run_cleanup.py b/lambda/tests/test_stuck_run_cleanup.py index b6fd0557a..5da177f96 100644 --- a/lambda/tests/test_stuck_run_cleanup.py +++ b/lambda/tests/test_stuck_run_cleanup.py @@ -109,6 +109,7 @@ def test_the_round_kind_falls_back_to_the_pass(self): self.assertEqual(sweep.round_kind({}, "ci_fix:2"), "ci_fix") self.assertEqual(sweep.round_kind({}, "feedback"), "feedback") self.assertEqual(sweep.round_kind({}, "implement"), "review_fix") + self.assertEqual(sweep.round_kind({}, "security_fix:1"), "security_fix") def test_no_pr_means_no_pr(self): self.assertFalse(sweep.has_pull_request({})) diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 0703474fa..b69fd68c4 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -83,6 +83,7 @@ mod model_call_sites; pub mod paged; /// What happened to a PR Coderhelm opened, read from GitHub. pub mod pr_outcome; +pub mod run_prs; // review_stats: time-ordered review records for analytics pub mod jira_text; /// Anthropic API or Amazon Bedrock, and Bedrock's model ids. diff --git a/services/common/src/run_fail.rs b/services/common/src/run_fail.rs index 503451256..bac3e60d2 100644 --- a/services/common/src/run_fail.rs +++ b/services/common/src/run_fail.rs @@ -41,8 +41,11 @@ pub struct RunFailure<'a> { /// Fail the run only while it is still in this status: a sweep that finds /// a stuck run must not overwrite one that finished meanwhile. pub only_from: Option<&'a str>, - /// More fields to set in the same write (tokens, cost, duration). + /// More fields to set in the same write (duration). pub extra: Vec<(&'static str, AttributeValue)>, + /// 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 status-index sort key of a failed run. @@ -117,6 +120,15 @@ pub fn update(run_id: &str, f: &RunFailure<'_>, now: &str) -> Update { names.insert(n, (*field).to_string()); values.insert(v, value.clone()); } + if !f.add.is_empty() { + values.insert(":zero".into(), AttributeValue::N("0".into())); + } + for (i, (field, value)) in f.add.iter().enumerate() { + let (n, v) = (format!("#a{i}"), format!(":a{i}")); + expression.push_str(&format!(", {n} = if_not_exists({n}, :zero) + {v}")); + names.insert(n, (*field).to_string()); + values.insert(v, value.clone()); + } expression.push_str(" REMOVE #legacy"); let condition = match f.only_from { Some(from) => { @@ -298,6 +310,27 @@ mod tests { } } + /// Tokens and cost are added to what the record holds, never set: a + /// later invocation's failure must not wipe the earlier cost. + #[test] + fn a_failure_adds_its_usage_to_the_record() { + let u = update( + "R1", + &RunFailure { + reason: "x", + add: vec![("cost_usd", AttributeValue::N("0.25".into()))], + ..Default::default() + }, + "now", + ); + assert!(u + .expression + .contains("#a0 = if_not_exists(#a0, :zero) + :a0")); + assert_eq!(u.names["#a0"], "cost_usd"); + assert_eq!(u.values[":a0"], AttributeValue::N("0.25".into())); + assert_eq!(u.values[":zero"], AttributeValue::N("0".into())); + } + #[test] fn error_text_names_the_cause_not_just_service_error() { assert_eq!( diff --git a/services/common/src/run_prs.rs b/services/common/src/run_prs.rs new file mode 100644 index 000000000..5964f5cb0 --- /dev/null +++ b/services/common/src/run_prs.rs @@ -0,0 +1,291 @@ +//! The pull requests a run opened, each with its own repository. +//! +//! A run that spans several repositories opens one pull request in each. Its +//! record used to keep `repo` (the run's) next to `pr_number` and `branch` +//! from the first pull request, which could be in another repository, and +//! lists of numbers and branches with no repository at all: a lookup by +//! number matched a pull request of the same number in an unrelated +//! repository, and a link built from `repo` and `pr_number` pointed at the +//! wrong pull request. Each pull request is now kept whole ([`RunPr`], the +//! record's `prs`), `repo`/`pr_number`/`branch`/`pr_url` always come from +//! one of them ([`primary`]), and lookups use keys that name the repository +//! ([`pr_key`], [`branch_key`]). + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; + +/// The run record field with every pull request ([`RunPr`]). +pub const FIELD: &str = "prs"; +/// The run record field with each pull request's [`pr_key`]. +pub const KEYS_FIELD: &str = "pr_keys"; +/// The run record field with each pull request's [`branch_key`]. +pub const BRANCH_KEYS_FIELD: &str = "branch_keys"; + +/// One pull request a run opened. +#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +pub struct RunPr { + /// The repository, `owner/name`. + pub repo: String, + pub pr_number: u64, + pub branch: String, + pub url: String, + /// `merged` or `closed` once the pull request ended; empty while open. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub outcome: String, +} + +/// The key that finds a run by one of its pull requests: `owner/name#123`. +pub fn pr_key(repo: &str, pr_number: u64) -> String { + format!("{}#{pr_number}", repo.to_ascii_lowercase()) +} + +/// The key that finds a run by one of its branches: `owner/name:branch`. +pub fn branch_key(repo: &str, branch: &str) -> String { + format!("{}:{branch}", repo.to_ascii_lowercase()) +} + +/// The pull request the record's `repo`, `pr_number`, `branch` and `pr_url` +/// describe: the one in the run's own repository when there is one, else the +/// first. `None` when there are none. +pub fn primary<'a>(prs: &'a [RunPr], run_repo: &str) -> Option<&'a RunPr> { + prs.iter() + .find(|p| p.repo.eq_ignore_ascii_case(run_repo)) + .or_else(|| prs.first()) +} + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +impl RunPr { + pub fn to_attr(&self) -> AttributeValue { + let mut m = HashMap::from([ + ("repo".to_string(), s(&self.repo)), + ( + "pr_number".to_string(), + AttributeValue::N(self.pr_number.to_string()), + ), + ("branch".to_string(), s(&self.branch)), + ("url".to_string(), s(&self.url)), + ]); + if !self.outcome.is_empty() { + m.insert("outcome".to_string(), s(&self.outcome)); + } + AttributeValue::M(m) + } + + fn from_attr(v: &AttributeValue) -> Option { + let m = v.as_m().ok()?; + let st = |k: &str| { + m.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let pr_number = m + .get("pr_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0); + let repo = st("repo"); + (pr_number > 0 && !repo.is_empty()).then(|| RunPr { + repo, + pr_number, + branch: st("branch"), + url: st("url"), + outcome: st("outcome"), + }) + } +} + +/// The values a run record write sets for its pull requests: `prs`, +/// `pr_keys`, `branch_keys`, and the lists older readers use. +pub fn attrs(prs: &[RunPr]) -> Vec<(&'static str, AttributeValue)> { + let list = + |f: &dyn Fn(&RunPr) -> AttributeValue| AttributeValue::L(prs.iter().map(f).collect()); + vec![ + (FIELD, list(&|p| p.to_attr())), + (KEYS_FIELD, list(&|p| s(&pr_key(&p.repo, p.pr_number)))), + ( + BRANCH_KEYS_FIELD, + list(&|p| s(&branch_key(&p.repo, &p.branch))), + ), + ("pr_urls", list(&|p| s(&p.url))), + ( + "pr_numbers", + list(&|p| AttributeValue::N(p.pr_number.to_string())), + ), + ("branches", list(&|p| s(&p.branch))), + ] +} + +/// The same values as an update's SET clause (`prs = :rp0, ...`) and the +/// values it names. +pub fn set_clause(prs: &[RunPr]) -> (String, Vec<(String, AttributeValue)>) { + let mut clause = Vec::new(); + let mut values = Vec::new(); + for (i, (field, value)) in attrs(prs).into_iter().enumerate() { + clause.push(format!("{field} = :rp{i}")); + values.push((format!(":rp{i}"), value)); + } + (clause.join(", "), values) +} + +/// Every pull request on a run record. Older records have no `prs`: their +/// pull requests are read from `pr_urls` (each URL names its repository), +/// paired with `branches` by position, else the one `pr_url`. +pub fn from_item(item: &HashMap) -> Vec { + if let Some(list) = item.get(FIELD).and_then(|v| v.as_l().ok()) { + let prs: Vec = list.iter().filter_map(RunPr::from_attr).collect(); + if !prs.is_empty() { + return prs; + } + } + let st = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let strings = |k: &str| -> Vec { + item.get(k) + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()) + .unwrap_or_default() + }; + let urls = strings("pr_urls"); + let branches = strings("branches"); + let from_urls: Vec = urls + .iter() + .enumerate() + .filter_map(|(i, url)| { + let (owner, name, n) = crate::pr_outcome::parse_pr_url(url)?; + Some(RunPr { + repo: format!("{owner}/{name}"), + pr_number: n, + branch: branches.get(i).cloned().unwrap_or_default(), + url: url.clone(), + outcome: String::new(), + }) + }) + .collect(); + if !from_urls.is_empty() { + return from_urls; + } + let url = st("pr_url"); + match crate::pr_outcome::parse_pr_url(&url) { + Some((owner, name, n)) => vec![RunPr { + repo: format!("{owner}/{name}"), + pr_number: n, + branch: st("branch"), + url, + outcome: String::new(), + }], + None => Vec::new(), + } +} + +/// Where in the record's `prs` the pull request `repo#pr_number` is. +pub fn position(prs: &[RunPr], repo: &str, pr_number: u64) -> Option { + prs.iter() + .position(|p| p.pr_number == pr_number && p.repo.eq_ignore_ascii_case(repo)) +} + +/// Whether `repo#pr_number` is the pull request the record's own `repo` and +/// `pr_number` describe. +pub fn is_primary(item: &HashMap, repo: &str, pr_number: u64) -> bool { + let rec_repo = item + .get("repo") + .and_then(|v| v.as_s().ok()) + .map(String::as_str) + .unwrap_or(""); + let rec_pr = item + .get("pr_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + rec_pr == pr_number && rec_repo.eq_ignore_ascii_case(repo) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pr(repo: &str, n: u64, branch: &str) -> RunPr { + RunPr { + repo: repo.into(), + pr_number: n, + branch: branch.into(), + url: format!("https://github.com/{repo}/pull/{n}"), + outcome: String::new(), + } + } + + /// The record's repo and number always name the same pull request. + #[test] + fn the_primary_pull_request_is_in_the_runs_repo_when_there_is_one() { + let prs = vec![pr("acme/api", 7, "a"), pr("acme/web", 12, "b")]; + assert_eq!(primary(&prs, "acme/web").unwrap().pr_number, 12); + assert_eq!(primary(&prs, "ACME/Web").unwrap().repo, "acme/web"); + // The run's repo opened none: the first, whole. + let p = primary(&prs, "acme/docs").unwrap(); + assert_eq!((p.repo.as_str(), p.pr_number), ("acme/api", 7)); + assert!(primary(&[], "acme/web").is_none()); + } + + /// The same number in two repositories is two different pull requests. + #[test] + fn keys_name_the_repository() { + assert_ne!(pr_key("acme/api", 12), pr_key("acme/web", 12)); + assert_eq!(pr_key("Acme/Web", 12), "acme/web#12"); + assert_eq!( + branch_key("acme/web", "coderhelm/x"), + "acme/web:coderhelm/x" + ); + } + + #[test] + fn prs_round_trip_and_older_records_are_read_from_their_urls() { + let prs = vec![pr("acme/api", 7, "a"), pr("acme/web", 12, "b")]; + let item: HashMap = attrs(&prs) + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(); + assert_eq!(from_item(&item), prs); + let (clause, values) = set_clause(&prs); + assert!(clause.starts_with("prs = :rp0, pr_keys = :rp1, branch_keys = :rp2")); + assert_eq!(values.len(), 6); + let keys = item[KEYS_FIELD].as_l().unwrap(); + assert_eq!(keys[1].as_s().unwrap(), "acme/web#12"); + + // Before `prs`: the URLs carry each repository, branches by position. + let mut old = item.clone(); + old.remove(FIELD); + assert_eq!(from_item(&old), prs); + + // A single-PR run. + let single: HashMap = HashMap::from([ + ( + "pr_url".to_string(), + s("https://github.com/acme/web/pull/3"), + ), + ("branch".to_string(), s("c")), + ]); + assert_eq!(from_item(&single), vec![pr("acme/web", 3, "c")]); + assert!(from_item(&HashMap::new()).is_empty()); + } + + #[test] + fn a_pull_request_is_found_by_repo_and_number() { + let prs = vec![pr("acme/api", 12, "a"), pr("acme/web", 12, "b")]; + assert_eq!(position(&prs, "acme/web", 12), Some(1)); + assert_eq!(position(&prs, "acme/docs", 12), None); + let item = HashMap::from([ + ("repo".to_string(), s("acme/web")), + ("pr_number".to_string(), AttributeValue::N("12".into())), + ]); + assert!(is_primary(&item, "acme/web", 12)); + assert!(!is_primary(&item, "acme/api", 12)); + } +} diff --git a/services/common/src/run_round.rs b/services/common/src/run_round.rs index 3c2250a51..4421e4dde 100644 --- a/services/common/src/run_round.rs +++ b/services/common/src/run_round.rs @@ -73,6 +73,11 @@ pub enum Kind { ReviewFix, /// A person's review or comments. Feedback, + /// The security check found issues before the pull request opened, with + /// too little of that invocation left to fix them: the fix runs on the + /// pull request in a fresh invocation, and the pull request stays a + /// draft until the issues are gone. + SecurityFix, } impl Kind { @@ -81,6 +86,7 @@ impl Kind { Kind::CiFix => "ci_fix", Kind::ReviewFix => "review_fix", Kind::Feedback => "feedback", + Kind::SecurityFix => "security_fix", } } @@ -89,6 +95,7 @@ impl Kind { "ci_fix" => Some(Kind::CiFix), "review_fix" => Some(Kind::ReviewFix), "feedback" => Some(Kind::Feedback), + "security_fix" => Some(Kind::SecurityFix), _ => None, } } @@ -99,6 +106,7 @@ impl Kind { match pass.split(':').next().unwrap_or("").trim() { "ci_fix" | "test" => Kind::CiFix, "feedback" => Kind::Feedback, + "security_fix" => Kind::SecurityFix, _ => Kind::ReviewFix, } } @@ -109,6 +117,7 @@ impl Kind { Kind::CiFix => "CI fix round", Kind::ReviewFix => "review fix round", Kind::Feedback => "feedback round", + Kind::SecurityFix => "security fix round", } } } @@ -660,6 +669,15 @@ mod tests { assert_eq!(Kind::of_pass("ci_fix:2"), Kind::CiFix); assert_eq!(Kind::of_pass("feedback"), Kind::Feedback); assert_eq!(Kind::of_pass("implement"), Kind::ReviewFix); + assert_eq!(Kind::of_pass("security_fix:1"), Kind::SecurityFix); + for k in [ + Kind::CiFix, + Kind::ReviewFix, + Kind::Feedback, + Kind::SecurityFix, + ] { + assert_eq!(Kind::parse(k.as_str()), Some(k)); + } for k in [Kind::CiFix, Kind::ReviewFix, Kind::Feedback] { assert_eq!(Kind::parse(k.as_str()), Some(k)); } diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 13b4e32d7..0e1c84b4d 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -1018,6 +1018,12 @@ pub struct Run { /// Their branches, in the same order. #[schema(example = json!(["coderhelm/web-42-login-rate-limit"]))] pub branches: Option>, + /// Every pull request the run opened, each with its own repository + /// (`repo`, `pr_number`, `branch`, `url`, and `outcome` once it ended). + /// Build links and labels from these: in a run across several + /// repositories, `repo` and `pr_numbers` don't pair up. + #[schema(value_type = Vec, example = json!([{"repo": "acme/web", "pr_number": 318, "branch": "coderhelm/web-42-login-rate-limit", "url": "https://github.com/acme/web/pull/318"}]))] + pub prs: Vec, /// The step the run is on or ended on. #[schema(example = "pr")] pub current_pass: Option, @@ -1432,6 +1438,7 @@ fn run_of( .collect() }), branches: strings("branches"), + prs: common::run_prs::from_item(item), current_pass: st("current_pass"), tokens_in, tokens_out, diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index dc04110d7..ee1d667d8 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -1285,30 +1285,18 @@ async fn handle_pull_request( let repo = &payload["repository"]; let owner = repo["owner"]["login"].as_str().unwrap_or(""); let name = repo["name"].as_str().unwrap_or(""); - let team_repo = format!("{team_id}#{owner}/{name}"); - // Query repo-index GSI to find the run with this PR number - let result = state - .dynamo - .query() - .table_name(&state.config.runs_table_name) - .index_name("repo-index") - .key_condition_expression("team_repo = :tr") - .filter_expression("pr_number = :pn") - .expression_attribute_values(":tr", attr_s(&team_repo)) - .expression_attribute_values(":pn", attr_n(pr_number)) - .scan_index_forward(false) - // Limit applies BEFORE the filter — limit(1) only ever examined the - // repo's newest run, dropping feedback/merge events for older PRs. - .limit(50) - .send() - .await - .map_err(|e| { - error!("Failed to query run for merged PR: {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - - if let Some(item) = result.items().first() { + // The run that opened this PR: its own PR, or one of a multi-repo run's. + let found = lookup_run_item_by_pr(state, team_id, owner, name, pr_number).await; + // A multi-repo run's other PR: its own outcome goes on its entry in + // `prs`; the run's status and outcome follow the PR its record names. + let is_primary = found + .as_ref() + .is_some_and(|i| common::run_prs::is_primary(i, &format!("{owner}/{name}"), pr_number)); + if let Some(item) = found.as_ref().filter(|_| !is_primary) { + record_secondary_pr_outcome(state, team_id, item, owner, name, pr_number, merged).await; + } + if let Some(item) = found.as_ref() { let run_id = item .get("run_id") .and_then(|v| v.as_s().ok()) @@ -1319,7 +1307,8 @@ async fn handle_pull_request( // Closed without merging: the run keeps its status; analytics // record the outcome so merge rate counts it honestly. let pr = &payload["pull_request"]; - let _ = state + if is_primary { + let _ = state .dynamo .update_item() .table_name(&state.config.runs_table_name) @@ -1332,6 +1321,7 @@ async fn handle_pull_request( .send() .await .map_err(|e| error!(team_id, run_id, pr_number, error = %e, "Could not record the closed PR on the run")); + } info!( team_id, run_id, pr_number, "PR closed without merging — outcome recorded" @@ -1364,7 +1354,20 @@ async fn handle_pull_request( .await; return Ok(StatusCode::OK); } - if !run_id.is_empty() { + if !run_id.is_empty() && !is_primary { + // A multi-repo run's other PR merged: scored like any other; the + // run's status follows the PR its record names. + queue_reward_outcome( + state, + team_id, + installation_id, + &run_id, + owner, + name, + pr_number, + ) + .await; + } else if !run_id.is_empty() { let now = chrono::Utc::now().to_rfc3339(); let pr = &payload["pull_request"]; // Commits people pushed on top of Coderhelm's: none means it @@ -1452,6 +1455,48 @@ async fn handle_pull_request( Ok(StatusCode::OK) } +/// A multi-repo run's PR that isn't the one its record names closed: its +/// entry in `prs` gets the outcome, and it is scored and learned from like +/// any other (with its own repository and number). +#[allow(clippy::too_many_arguments)] +async fn record_secondary_pr_outcome( + state: &AppState, + team_id: &str, + item: &common::paged::Item, + owner: &str, + name: &str, + pr_number: u64, + merged: bool, +) { + let Some(run_id) = common::paged::run_id_of(item) else { + return; + }; + let prs = common::run_prs::from_item(item); + if let Some(i) = common::run_prs::position(&prs, &format!("{owner}/{name}"), pr_number) { + if item.contains_key(common::run_prs::FIELD) { + let outcome = if merged { "merged" } else { "closed" }; + if let Err(e) = 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(format!("SET prs[{i}].outcome = :o, updated_at = :t")) + .expression_attribute_values(":o", attr_s(outcome)) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await + { + warn!(team_id, run_id, pr_number, error = %e, "Could not record the PR's outcome on its run"); + } + } + } + info!( + team_id, + run_id, pr_number, merged, "A multi-repo run's other PR closed" + ); +} + /// Hands a closed CoderHelm pull request to the worker to score (merged as /// written or edited, closed, time to merge, CI rounds, comments left open). async fn queue_reward_outcome( @@ -2558,16 +2603,26 @@ async fn find_run_by_branch( return Some(run_id); } - // Fallback: multi-repo runs store secondary branches in `branches` list. - // Query team partition and check if this branch is in the list. + // Fallback: a multi-repo run's other branches, by repository and branch + // (`branch_keys`); records from before them by branch name alone. let fallback = state .dynamo .query() .table_name(&state.config.runs_table_name) .key_condition_expression("team_id = :tid") - .filter_expression("contains(branches, :b) AND (#s = :s1 OR #s = :s2)") + .filter_expression( + "(contains(branch_keys, :bk) OR (attribute_not_exists(branch_keys) AND contains(branches, :b))) \ + AND (#s = :s1 OR #s = :s2)", + ) .expression_attribute_names("#s", "status") .expression_attribute_values(":tid", attr_s(team_id)) + .expression_attribute_values( + ":bk", + attr_s(&common::run_prs::branch_key( + &format!("{repo_owner}/{repo_name}"), + branch, + )), + ) .expression_attribute_values(":b", attr_s(branch)) .expression_attribute_values(":s1", attr_s("awaiting_ci")) .expression_attribute_values(":s2", attr_s("running")) @@ -3463,7 +3518,24 @@ async fn lookup_run_by_pr( name: &str, pr_number: u64, ) -> String { - // First try the repo-index GSI (fast path — works for primary repo) + lookup_run_item_by_pr(state, team_id, owner, name, pr_number) + .await + .as_ref() + .and_then(common::paged::run_id_of) + .unwrap_or_default() +} + +/// The run that opened `owner/name#pr_number`: its record's own PR (the +/// repo-index GSI), else one of a multi-repo run's PRs, matched by +/// repository AND number (`pr_keys`). A number alone matched a PR of the +/// same number in an unrelated repository. +async fn lookup_run_item_by_pr( + state: &AppState, + team_id: &str, + owner: &str, + name: &str, + pr_number: u64, +) -> Option { let team_repo = format!("{team_id}#{owner}/{name}"); // Limit applies BEFORE the filter, so a single page only examined the // repo's newest 50 runs and dropped events for older PRs. Follow @@ -3479,29 +3551,36 @@ async fn lookup_run_by_pr( .expression_attribute_values(":pn", attr_n(pr_number)) .scan_index_forward(false) .limit(50); - match common::paged::query_first_match(primary, common::paged::run_id_of).await { - Ok(Some(run_id)) => return run_id, + match common::paged::query_first_match(primary, |i| Some(i.clone())).await { + Ok(Some(item)) => return Some(item), Ok(None) => {} Err(e) => error!("Failed to query run by PR number: {e}"), } - // Fallback: multi-repo runs store secondary PRs in pr_numbers list. - // Query the team partition and check the list attribute, every page. + // Fallback: a multi-repo run's other PRs, by repository and number. + // Records from before `pr_keys` are matched by the PR's URL. + let repo = format!("{owner}/{name}"); let fallback = state .dynamo .query() .table_name(&state.config.runs_table_name) .key_condition_expression("team_id = :tid") - .filter_expression("contains(pr_numbers, :pn)") + .filter_expression( + "contains(pr_keys, :k) OR (attribute_not_exists(pr_keys) AND contains(pr_urls, :u))", + ) .expression_attribute_values(":tid", attr_s(team_id)) - .expression_attribute_values(":pn", attr_n(pr_number)) + .expression_attribute_values(":k", attr_s(&common::run_prs::pr_key(&repo, pr_number))) + .expression_attribute_values( + ":u", + attr_s(&format!("https://github.com/{repo}/pull/{pr_number}")), + ) .scan_index_forward(false) .limit(100); - match common::paged::query_first_match(fallback, common::paged::run_id_of).await { - Ok(found) => found.unwrap_or_default(), + match common::paged::query_first_match(fallback, |i| Some(i.clone())).await { + Ok(found) => found, Err(e) => { error!("Failed to query run by PR number (fallback): {e}"); - String::new() + None } } } diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 514a45596..6c3327097 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -289,6 +289,8 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) models::WorkerMessage::Ticket(msg) => { info!(team_id = %msg.team_id, ticket_id = %msg.ticket_id, "Starting ticket run"); if let Err(e) = passes::orchestrate_ticket(&state, msg).await { + // Already handled there: the run is failed with this reason + // and the ticket told (a test holds orchestrate_ticket to it). error!(error = %common::run_fail::error_text(&*e), "Ticket run failed"); } } diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index f50b2e898..d3564d452 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -171,8 +171,24 @@ pub struct TokenUsage { pub cost_usd: f64, pub tool_calls: u64, pub tool_names: Vec, + /// How much of this usage is already on the run record. Shared by + /// clones: a clone is a snapshot of the same run's usage. + pub(crate) recorded: Recorded, } +/// Tokens and cost one run write adds to the run record. +#[derive(Debug, Default, Clone, Copy, PartialEq)] +pub struct UsageDelta { + pub input_tokens: u64, + pub output_tokens: u64, + pub cache_read_tokens: u64, + pub cache_write_tokens: u64, + pub cost_usd: f64, +} + +#[derive(Debug, Default, Clone)] +pub(crate) struct Recorded(std::sync::Arc>); + impl TokenUsage { /// Add one model call's usage, priced at `model_id`'s rates. pub fn add_call(&mut self, model_id: &str, call: &common::usage::CallUsage) { @@ -212,29 +228,35 @@ impl TokenUsage { self.cost_usd } - /// Rebuild a saved usage. Old checkpoints carry no cost: their tokens are - /// priced at `model_id`'s rates. - pub fn restored( - model_id: &str, - input: u64, - output: u64, - cache_read: u64, - cache_write: u64, - cost_usd: Option, - ) -> Self { - let call = common::usage::CallUsage { - uncached_input: input, - cache_read, - cache_write_5m: cache_write, - cache_write_1h: 0, - output, - }; - let mut u = TokenUsage::default(); - u.add_call(model_id, &call); - if let Some(c) = cost_usd { - u.cost_usd = c; + /// What this usage adds to the run record now: everything since the + /// last write from this invocation ([`TokenUsage::mark_recorded`]). + /// Every run write ADDs this instead of SETting a total, so a fresh + /// invocation (a continuation, a resume, a CI fix) never overwrites the + /// cost earlier invocations recorded. + pub fn unrecorded(&self) -> UsageDelta { + let done = *self.recorded.0.lock().unwrap_or_else(|e| e.into_inner()); + UsageDelta { + input_tokens: self.input_tokens.saturating_sub(done.input_tokens), + output_tokens: self.output_tokens.saturating_sub(done.output_tokens), + cache_read_tokens: self + .cache_read_tokens + .saturating_sub(done.cache_read_tokens), + cache_write_tokens: self + .cache_write_tokens + .saturating_sub(done.cache_write_tokens), + cost_usd: (self.cost_usd - done.cost_usd).max(0.0), } - u + } + + /// `delta` is on the run record: the next write adds only what follows. + /// Called after the write succeeded; a refused write leaves it pending. + pub fn mark_recorded(&self, delta: &UsageDelta) { + let mut done = self.recorded.0.lock().unwrap_or_else(|e| e.into_inner()); + done.input_tokens += delta.input_tokens; + done.output_tokens += delta.output_tokens; + done.cache_read_tokens += delta.cache_read_tokens; + done.cache_write_tokens += delta.cache_write_tokens; + done.cost_usd += delta.cost_usd; } } @@ -379,13 +401,45 @@ mod tests { assert!((merged.cost_usd - usage.cost_usd).abs() < 1e-12); } + /// Each write adds only what came after the last one, so the run's + /// total is the sum of every invocation's calls, however many there were. #[test] - fn restored_usage_keeps_a_saved_cost_or_prices_the_tokens() { - let r = TokenUsage::restored("claude-opus-5-5", 10, 20, 30, 40, Some(1.5)); - assert_eq!(r.total_tokens(), 100); - assert_eq!(r.cost_usd, 1.5); - let r = TokenUsage::restored("claude-opus-5-5", 1_000_000, 0, 0, 0, None); - assert!((r.cost_usd - 4.0).abs() < 1e-9); + fn run_writes_add_only_what_is_not_yet_recorded() { + let call = common::usage::CallUsage { + uncached_input: 100, + cache_read: 10, + cache_write_5m: 5, + cache_write_1h: 0, + output: 50, + }; + let mut usage = TokenUsage::default(); + usage.add_call("claude-opus-5-5", &call); + let first = usage.unrecorded(); + assert_eq!(first.input_tokens, 100); + assert_eq!(first.cache_write_tokens, 5); + assert!(first.cost_usd > 0.0); + usage.mark_recorded(&first); + assert_eq!(usage.unrecorded(), UsageDelta::default()); + + usage.add_call("claude-opus-5-5", &call); + let second = usage.unrecorded(); + assert_eq!(second.input_tokens, 100); + assert_eq!(second.output_tokens, 50); + // A write that failed is not marked: the next one carries it. + usage.add_call("claude-opus-5-5", &call); + assert_eq!(usage.unrecorded().input_tokens, 200); + + // A snapshot shares what is recorded and never goes negative. + let before = usage.clone(); + let all = usage.unrecorded(); + usage.mark_recorded(&all); + assert_eq!(before.unrecorded(), UsageDelta::default()); + + // A new invocation starts at zero: it adds its own calls only, + // never a near-zero total over the earlier cost. + let mut next = TokenUsage::default(); + next.add_call("claude-opus-5-5", &call); + assert_eq!(next.unrecorded().input_tokens, 100); } #[test] diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index f27e89e31..d68de37d1 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -838,22 +838,42 @@ pub async fn orchestrate_ticket( ); return Ok(()); } - } else if let Err(e) = create_run_record(state, &msg, &run_id).await { - // The record may already be written: left alone it would sit in - // "running" with no pass until the stuck-run sweep called it a timeout. - // Say why now; with no record, nothing is written. - let reason = format!( - "Could not start the run: {}", - common::run_fail::error_text(&*e) - ); + } else if let Err(e) = create_run_record(state, &msg, &run_id, RecordDetail::Full).await { + // Left alone, a record that was written would sit in "running" with + // no pass until the stuck-run sweep called it a timeout "during + // unknown pass", and a record that wasn't would leave the ticket with + // no answer at all. Fail it now, plainly, with the cause. + let reason = start_failure_reason(&common::run_fail::error_text(&*e)); error!(run_id, error = %reason, "Run record write failed"); - fail_run(state, &msg, &run_id, &reason, &usage, 0).await; + if !run_record_exists(state, &msg.team_id, &run_id).await { + // The full record was refused (too large a ticket, a bad + // value): keep a small one so the run page can say why. + if let Err(e2) = create_run_record(state, &msg, &run_id, RecordDetail::Minimal).await { + warn!(run_id, error = %common::run_fail::error_text(&*e2), "Minimal run record write failed too"); + } + } + if run_record_exists(state, &msg.team_id, &run_id).await { + fail_run(state, &msg, &run_id, &reason, &usage, 0).await; + } else { + // No record to fail: the ticket still hears why. + notify_ticket_failed(state, &msg, &run_id, &reason).await; + } + release_ticket_lock(state, &msg.team_id, &msg.ticket_id).await; return Err(reason.into()); } match tokio::time::timeout( std::time::Duration::from_secs(LAMBDA_TIMEOUT_SECS - 30), // 30s buffer for cleanup - run_passes(state, &mut msg, &run_id, &mut usage, &start), + // A panic must fail the run with a reason like any other error: left + // to the runtime, SQS delivered the ticket again, the duplicate check + // dropped it, and the run sat "running" until the stuck-run sweep. + async { + use futures::FutureExt; + std::panic::AssertUnwindSafe(run_passes(state, &mut msg, &run_id, &mut usage, &start)) + .catch_unwind() + .await + .unwrap_or_else(|p| Err(panic_reason(p.as_ref()).into())) + }, ) .await { @@ -867,23 +887,24 @@ pub async fn orchestrate_ticket( if err_msg.contains("cancelled by user") { info!(run_id, duration, "Run cancelled — preserving tokens"); // Update token counts but keep status as cancelled - let cost = usage.estimated_cost(); - let _ = state + let delta = usage.unrecorded(); + let res = state .dynamo .update_item() .table_name(&state.config.runs_table_name) .key("team_id", attr_s(&msg.team_id)) .key("run_id", attr_s(&run_id)) - .update_expression("SET tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, cache_write_tokens = :cwt, cost_usd = :c, duration_s = :d, updated_at = :t") - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{cost:.4}"))) + .update_expression("SET tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t") + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) .send() .await; + if res.is_ok() { + usage.mark_recorded(&delta); + } // The team's counters already have these tokens: each model // call is counted as it happens (common::usage). } else { @@ -2184,26 +2205,24 @@ async fn run_passes( // Complete the run with no PR let duration = start.elapsed().as_secs(); - let cost = usage.estimated_cost(); + let delta = usage.unrecorded(); let now = chrono::Utc::now().to_rfc3339(); - let _ = state + let usage_res = state .dynamo .update_item() .table_name(&state.config.runs_table_name) .key("team_id", attr_s(&msg.team_id)) .key("run_id", attr_s(run_id)) .update_expression( - "SET #status = :s, tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, cache_write_tokens = :cwt, cost_usd = :c, \ + "SET #status = :s, tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, \ duration_s = :d, updated_at = :t, current_pass = :cp, \ status_run_id = :sri, mcp_servers = :mcp", ) .expression_attribute_names("#status", "status") .expression_attribute_values(":s", attr_s("completed")) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{:.4}", cost))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) @@ -2214,6 +2233,9 @@ async fn run_passes( ) .send() .await; + if usage_res.is_ok() { + usage.mark_recorded(&delta); + } self::webhooks::emit_run(state, &msg.team_id, run_id, "completed").await; // Update analytics counters @@ -2724,9 +2746,9 @@ async fn run_passes( // Store PR info on run record and go to awaiting_ci let now = chrono::Utc::now().to_rfc3339(); - let cost = usage.estimated_cost(); + let delta = usage.unrecorded(); let duration = start.elapsed().as_secs(); - let _ = state.dynamo.update_item() + let usage_res = state.dynamo.update_item() .table_name(&state.config.runs_table_name) .key("team_id", attr_s(&msg.team_id)) .key("run_id", attr_s(run_id)) @@ -2734,8 +2756,9 @@ async fn run_passes( "SET #s = :s, status_run_id = :sri, current_pass = :cp, \ pr_number = :pn, pr_url = :pu, branch = :b, \ repo = :repo, team_repo = :tr, \ - tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, cache_write_tokens = :cwt, \ - cost_usd = :cost, duration_s = :d, updated_at = :t" + tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t" ) .expression_attribute_names("#s", "status") // Never resurrect a cancelled run: if the user cancelled @@ -2754,14 +2777,13 @@ async fn run_passes( .expression_attribute_values(":repo", attr_s(&format!("{}/{}", msg.repo_owner, msg.repo_name))) .expression_attribute_values(":tr", attr_s(&format!("{}#{}/{}", msg.team_id, msg.repo_owner, msg.repo_name))) .expression_attribute_values(":t", attr_s(&now)) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":cost", attr_n(format!("{:.4}", cost))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .send() .await; + if usage_res.is_ok() { + usage.mark_recorded(&delta); + } save_checkpoint(state, &msg.team_id, run_id, "pr", &branch_name, 1, usage) .await; @@ -3432,49 +3454,52 @@ async fn run_passes( let duration = start.elapsed().as_secs(); let now = chrono::Utc::now().to_rfc3339(); - let cost = usage.estimated_cost(); - - // Build PR list attributes - let pr_urls: Vec = - pr_results.iter().map(|p| attr_s(&p.pr_url)).collect(); - let pr_numbers: Vec = - pr_results.iter().map(|p| attr_n(p.pr_number)).collect(); - let branches: Vec = - pr_results.iter().map(|p| attr_s(&p.branch)).collect(); - - // Store first PR as primary for backward compat, plus full lists - let multi_res = state + let delta = usage.unrecorded(); + + // Each pull request with its own repository; the record's repo, + // number, branch and URL all come from one of them (the one in + // the run's repo when there is one), never mixed across repos. + let run_prs: Vec = pr_results + .iter() + .map(|p| common::run_prs::RunPr { + repo: format!("{}/{}", p.repo.0, p.repo.1), + pr_number: p.pr_number, + branch: p.branch.clone(), + url: p.pr_url.clone(), + outcome: String::new(), + }) + .collect(); + let run_repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + let primary = common::run_prs::primary(&run_prs, &run_repo) + .cloned() + .unwrap_or_default(); + + let (prs_clause, prs_values) = common::run_prs::set_clause(&run_prs); + let mut multi = state .dynamo .update_item() .table_name(&state.config.runs_table_name) .key("team_id", attr_s(&msg.team_id)) .key("run_id", attr_s(run_id)) - .update_expression( - "SET #status = :s, pr_url = :pr, pr_number = :pn, branch = :b, \ - pr_urls = :prs, pr_numbers = :pns, branches = :bs, \ + .update_expression(format!( + "SET #status = :s, pr_url = :pr, pr_number = :pn, branch = :b, {prs_clause}, \ repo = :repo, team_repo = :tr, \ - tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, cache_write_tokens = :cwt, \ - cost_usd = :c, duration_s = :d, updated_at = :t, current_pass = :cp, \ + tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, current_pass = :cp, \ status_run_id = :sri, mcp_servers = :mcp", - ) + )) .expression_attribute_names("#status", "status") // Never resurrect a cancelled run (mirrors the single-repo guard). .condition_expression(common::run_status::not_ended("#status")) .ended_values() .expression_attribute_values(":s", attr_s("awaiting_ci")) - .expression_attribute_values(":pr", attr_s(&pr_results[0].pr_url)) - .expression_attribute_values(":pn", attr_n(pr_results[0].pr_number)) - .expression_attribute_values(":b", attr_s(&pr_results[0].branch)) - .expression_attribute_values(":prs", AttributeValue::L(pr_urls)) - .expression_attribute_values(":pns", AttributeValue::L(pr_numbers)) - .expression_attribute_values(":bs", AttributeValue::L(branches)) - .expression_attribute_values(":repo", attr_s(&format!("{}/{}", msg.repo_owner, msg.repo_name))) - .expression_attribute_values(":tr", attr_s(&format!("{}#{}/{}", msg.team_id, msg.repo_owner, msg.repo_name))) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{:.4}", cost))) + .expression_attribute_values(":pr", attr_s(&primary.url)) + .expression_attribute_values(":pn", attr_n(primary.pr_number)) + .expression_attribute_values(":b", attr_s(&primary.branch)) + .expression_attribute_values(":repo", attr_s(&primary.repo)) + .expression_attribute_values(":tr", attr_s(&format!("{}#{}", msg.team_id, primary.repo))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("awaiting_ci")) @@ -3482,9 +3507,11 @@ async fn run_passes( .expression_attribute_values( ":mcp", AttributeValue::L(used_mcp_ids.iter().map(|id| attr_s(id)).collect()), - ) - .send() - .await; + ); + for (name, value) in prs_values { + multi = multi.expression_attribute_values(name, value); + } + let multi_res = multi.send().await; if let Err(e) = multi_res { if format!("{e:?}").contains("ConditionalCheckFailed") { info!( @@ -3495,6 +3522,7 @@ async fn run_passes( } return Err(e.into()); } + usage.mark_recorded(&delta); info!( run_id, @@ -3659,7 +3687,7 @@ async fn run_passes( .unwrap_or("") .to_string(); let duration = start.elapsed().as_secs(); - let cost = usage.estimated_cost(); + let delta = usage.unrecorded(); let now = chrono::Utc::now().to_rfc3339(); let wrote = state .dynamo @@ -3669,8 +3697,9 @@ async fn run_passes( .key("run_id", attr_s(run_id)) .update_expression( "SET #status = :s, status_run_id = :sri, pr_number = :pn, pr_url = :pu, \ - branch = :b, tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, \ - cache_write_tokens = :cwt, cost_usd = :c, duration_s = :d, updated_at = :t, \ + branch = :b, tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, \ current_pass = :cp", ) .expression_attribute_names("#status", "status") @@ -3681,11 +3710,7 @@ async fn run_passes( .expression_attribute_values(":pn", attr_n(pr_number)) .expression_attribute_values(":pu", attr_s(&pr_url)) .expression_attribute_values(":b", attr_s(&branch_name)) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{:.4}", cost))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) @@ -3693,6 +3718,7 @@ async fn run_passes( .await .is_ok(); if wrote { + usage.mark_recorded(&delta); self::webhooks::emit_run(state, &msg.team_id, run_id, "completed").await; } close_memory(state, agent_memory.take()).await; @@ -3746,9 +3772,9 @@ async fn run_passes( .await; let duration = start.elapsed().as_secs(); - let cost = usage.estimated_cost(); + let delta = usage.unrecorded(); let now = chrono::Utc::now().to_rfc3339(); - let _ = state + let usage_res = state .dynamo .update_item() .table_name(&state.config.runs_table_name) @@ -3756,23 +3782,23 @@ async fn run_passes( .key("run_id", attr_s(run_id)) .update_expression( "SET #status = :s, status_run_id = :sri, error_message = :em, \ - tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, cache_write_tokens = :cwt, \ - cost_usd = :c, duration_s = :d, updated_at = :t, current_pass = :cp", + tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, current_pass = :cp", ) .expression_attribute_names("#status", "status") .expression_attribute_values(":s", attr_s("needs_input")) .expression_attribute_values(":sri", attr_s(&format!("needs_input#{run_id}"))) .expression_attribute_values(":em", attr_s(raw_clarification)) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{:.4}", cost))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) .send() .await; + if usage_res.is_ok() { + usage.mark_recorded(&delta); + } self::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; close_memory(state, agent_memory.take()).await; return Ok(()); @@ -3960,29 +3986,24 @@ async fn run_passes( update_pass(state, &msg.team_id, run_id, "security").await?; let pass_start = std::time::Instant::now(); let usage_before = usage.clone(); - let security_result = match security::run( - state, - msg, - &github, - &plan_result, - &branch_name, - &repo_instructions, - &provider, - usage, - &file_cache, - Some(run_id), - ) - .await - { - Ok(r) => r, - Err(e) => { - warn!(run_id, error = %e, "Security pass errored, proceeding"); - security::SecurityResult { - passed: true, - summary: format!("Security error: {e}"), - } - } - }; + let mut security_verdict = security::Verdict::of( + security::run( + state, + msg, + &github, + &plan_result, + &branch_name, + &repo_instructions, + &provider, + usage, + &file_cache, + Some(run_id), + ) + .await, + ); + if let security::Verdict::NotChecked(e) = &security_verdict { + warn!(run_id, error = %e, "Security pass errored: the PR opens as a draft with it under Open items"); + } write_pass_trace( state, &msg.team_id, @@ -4006,35 +4027,48 @@ async fn run_passes( .await; info!( run_id, - passed = security_result.passed, + passed = security_verdict.passed(), "Security audit complete" ); add_progress_note( state, &msg.team_id, run_id, - if security_result.passed { - "Security audit passed" - } else { - "Security issues found, fixing" + match &security_verdict { + security::Verdict::Passed => "Security audit passed", + security::Verdict::Findings(_) => "Security issues found, fixing", + security::Verdict::NotChecked(_) => { + "The security check couldn't run; the pull request stays a draft with that under Open items" + } }, ) .await; - if !security_result.passed { + // What a security round on the PR is told, when the fix (or the check) + // continues in a fresh invocation after the PR opens. + let mut security_round: Option = None; + if let security::Verdict::NotChecked(why) = &security_verdict { + security_round = Some(security::recheck_feedback(why)); + } + if let security::Verdict::Findings(summary) = security_verdict.clone() { if !has_time_for_remediation(start) { + // Too little of this invocation is left to fix them here: the fix + // is a round of its own on the pull request, with its own budget, + // and the PR stays a draft with the issues under Open items until + // it's done. Never skipped. warn!( run_id, remaining_secs = remaining_secs(start), - "Skipping security remediation — not enough time remaining" + "Security issues found with little time left: the fix continues in a fresh step" ); add_progress_note( state, &msg.team_id, run_id, - "Security issues found but skipping remediation (low time remaining)", + "Security issues found with too little time left in this step: the fix continues in a fresh step on the pull request, which stays a draft until they're fixed", ) .await; + security_round = Some(security::fix_feedback(&summary)); } else { info!(run_id, "Security issues found, running remediation cycle"); check_cancelled(state, &msg.team_id, run_id).await?; @@ -4047,10 +4081,7 @@ async fn run_passes( &branch_name, &rules, &repo_instructions, - Some(&format!( - "Security audit found vulnerabilities. Fix ALL of the following:\n\n{}", - security_result.summary - )), + Some(&security::fix_feedback(&summary)), &effective_complexity, &provider, usage, @@ -4071,40 +4102,40 @@ async fn run_passes( check_cancelled(state, &msg.team_id, run_id).await?; update_pass(state, &msg.team_id, run_id, "security").await?; - let retry = match security::run( - state, - msg, - &github, - &plan_result, - &branch_name, - &repo_instructions, - &provider, - usage, - &file_cache, - Some(run_id), - ) - .await - { - Ok(r) => r, - Err(e) => { - warn!(run_id, error = %e, "Security retry errored, proceeding"); - security::SecurityResult { - passed: true, - summary: format!("Security error: {e}"), - } - } - }; - if !retry.passed { + security_verdict = security::Verdict::of( + security::run( + state, + msg, + &github, + &plan_result, + &branch_name, + &repo_instructions, + &provider, + usage, + &file_cache, + Some(run_id), + ) + .await, + ); + if !security_verdict.passed() { warn!( run_id, - "Security issues remain after remediation, proceeding with PR" + "Security issues remain after remediation (or the re-check didn't run): they go under Open items and the PR stays a draft" ); } + // A re-check that didn't run runs again on the PR. + if let security::Verdict::NotChecked(why) = &security_verdict { + security_round = Some(security::recheck_feedback(why)); + } } } + // What is still open goes under Open items, marked: the PR stays a draft + // while any is listed. + let security_items = security::open_items(&security_verdict, security_round.is_some()); - // Security findings are already posted as PR review comments and stored in the - // run record — no need to duplicate the full audit text into long-term memory. + // Security issues not fixed (or a check that didn't run) are the PR's + // Open items, marked so it stays a draft; the full audit text is not + // copied into long-term memory. // --- Proof check (before PR — what the change rests on is proven) --- check_cancelled(state, &msg.team_id, run_id).await?; @@ -4171,6 +4202,8 @@ async fn run_passes( } // Tasks the plan marks optional and the change left out, named. gaps.extend(plan_optional); + // Security issues not fixed yet, or a check that didn't run. + gaps.extend(security_items); // Every redirect and link the change adds or changes, checked live; a // failure that survives its fix round stops the run before the PR. let links = link_checks::gate(&work, &mut evidence, usage, || { @@ -4261,6 +4294,21 @@ async fn run_passes( ) .await; + // The security fix there wasn't time for: a round of its own on the PR, + // parked for the resume that follows (a fresh invocation, its own budget). + if let Some(feedback) = &security_round { + let round = common::run_round::Round::start( + common::run_round::Kind::SecurityFix, + 1, + "", + feedback, + true, + chrono::Utc::now(), + ) + .parked(false); + round::record(state, &msg.team_id, run_id, &round).await; + } + // Save checkpoint and set awaiting_ci — Lambda returns here. // The webhook-driven resume flow handles CI results and review. save_checkpoint(state, &msg.team_id, run_id, "pr", &branch_name, 0, usage).await; @@ -4268,7 +4316,7 @@ async fn run_passes( // Update run record with PR info + awaiting_ci status let duration = start.elapsed().as_secs(); let now = chrono::Utc::now().to_rfc3339(); - let cost = usage.estimated_cost(); + let delta = usage.unrecorded(); let awaiting_res = state .dynamo @@ -4278,7 +4326,9 @@ async fn run_passes( .key("run_id", attr_s(run_id)) .update_expression( "SET #status = :s, pr_url = :pr, pr_number = :pn, branch = :b, \ - tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, cache_write_tokens = :cwt, cost_usd = :c, \ + tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, \ duration_s = :d, updated_at = :t, current_pass = :cp, \ status_run_id = :sri, \ repo = :repo, team_repo = :tr, mcp_servers = :mcp", @@ -4302,11 +4352,7 @@ async fn run_passes( )), ) .expression_attribute_values(":b", attr_s(&branch_name)) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{:.4}", cost))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("awaiting_ci")) @@ -4332,6 +4378,7 @@ async fn run_passes( } return Err(e.into()); } + usage.mark_recorded(&delta); info!( run_id, @@ -4352,7 +4399,8 @@ async fn run_passes( .send_message() .queue_url(&state.config.ci_fix_queue_url) .message_body(resume_body.to_string()) - .delay_seconds(120) + // A parked security fix starts as soon as this invocation ends. + .delay_seconds(if security_round.is_some() { 5 } else { 120 }) .send() .await; } @@ -4699,29 +4747,24 @@ async fn run_repo_pipeline( update_pass(state, &msg.team_id, run_id, "security").await?; let pass_start = std::time::Instant::now(); let usage_before = usage.clone(); - let security_result = match security::run( - state, - msg, - github, - &repo_plan, - branch_name, - repo_instructions, - provider, - usage, - file_cache, - Some(run_id), - ) - .await - { - Ok(r) => r, - Err(e) => { - warn!(run_id, error = %e, "Security pass errored, proceeding"); - security::SecurityResult { - passed: true, - summary: format!("Security error: {e}"), - } - } - }; + let mut security_verdict = security::Verdict::of( + security::run( + state, + msg, + github, + &repo_plan, + branch_name, + repo_instructions, + provider, + usage, + file_cache, + Some(run_id), + ) + .await, + ); + if let security::Verdict::NotChecked(e) = &security_verdict { + warn!(run_id, error = %e, "Security pass errored: the PR opens as a draft with it under Open items"); + } write_pass_trace( state, &msg.team_id, @@ -4744,21 +4787,25 @@ async fn run_repo_pipeline( ) .await; - info!(run_id, repo = %format!("{repo_owner}/{repo_name}"), passed = security_result.passed, "Security audit complete"); + info!(run_id, repo = %format!("{repo_owner}/{repo_name}"), passed = security_verdict.passed(), "Security audit complete"); add_progress_note( state, &msg.team_id, run_id, - if security_result.passed { - "Security audit passed" - } else { - "Security issues found, fixing" + match &security_verdict { + security::Verdict::Passed => "Security audit passed", + security::Verdict::Findings(_) => "Security issues found, fixing", + security::Verdict::NotChecked(_) => { + "The security check couldn't run; the pull request stays a draft with that under Open items" + } }, ) .await; - // Security remediation - if !security_result.passed { + // Security remediation. A multi-repo run's pull requests have no fix + // rounds of their own, so findings there wasn't time to fix stay under + // the PR's Open items and hold it a draft. + if let security::Verdict::Findings(summary) = security_verdict.clone() { if has_time_for_remediation(start) { info!(run_id, "Running security remediation"); check_cancelled(state, &msg.team_id, run_id).await?; @@ -4770,10 +4817,7 @@ async fn run_repo_pipeline( branch_name, rules, repo_instructions, - Some(&format!( - "Security audit found vulnerabilities. Fix ALL of the following:\n\n{}", - security_result.summary - )), + Some(&security::fix_feedback(&summary)), complexity, provider, usage, @@ -4791,13 +4835,31 @@ async fn run_repo_pipeline( &sec_fix.conversation_log, ) .await; + check_cancelled(state, &msg.team_id, run_id).await?; + security_verdict = security::Verdict::of( + security::run( + state, + msg, + github, + &repo_plan, + branch_name, + repo_instructions, + provider, + usage, + file_cache, + Some(run_id), + ) + .await, + ); } else { - warn!(run_id, "Skipping security remediation — not enough time"); + warn!(run_id, "No time for security remediation: the findings go under Open items and the PR stays a draft"); } } + let security_items = security::open_items(&security_verdict, false); - // Security findings are already posted as PR review comments and stored in the - // run record — no need to duplicate the full audit text into long-term memory. + // Security issues not fixed (or a check that didn't run) are the PR's + // Open items, marked so it stays a draft; the full audit text is not + // copied into long-term memory. // --- Proof check --- check_cancelled(state, &msg.team_id, run_id).await?; @@ -4858,6 +4920,7 @@ async fn run_repo_pipeline( .into()); } gaps.extend(plan_optional); + gaps.extend(security_items); let links = link_checks::gate(&work, &mut evidence, usage, || { has_time_for_remediation(start) }) @@ -4988,11 +5051,62 @@ async fn resume_run_to_running(state: &WorkerState, team_id: &str, run_id: &str) .is_ok() } +/// The reason a run that panicked gives. +fn panic_reason(p: &(dyn std::any::Any + Send)) -> String { + let what = p + .downcast_ref::<&str>() + .map(|s| s.to_string()) + .or_else(|| p.downcast_ref::().cloned()) + .unwrap_or_default(); + if what.trim().is_empty() { + "CoderHelm stopped on an internal error.".to_string() + } else { + format!("CoderHelm stopped on an internal error: {}", what.trim()) + } +} + +/// How much of the ticket a new run record carries. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum RecordDetail { + Full, + /// No ticket body or images: written when the full record was refused, + /// so a run that can't start still has a record that says why. + Minimal, +} + +/// The reason a run that could not start gives, in plain words, with the +/// cause underneath (the SDK's own text is only "service error"). +fn start_failure_reason(cause: &str) -> String { + let cause = cause.trim(); + if cause.is_empty() { + "CoderHelm could not start this run: saving the run failed.".to_string() + } else { + format!("CoderHelm could not start this run: saving the run failed ({cause}).") + } +} + +async fn run_record_exists(state: &WorkerState, team_id: &str, run_id: &str) -> bool { + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("run_id") + .consistent_read(true) + .send() + .await + .map(|o| o.item().is_some()) + .unwrap_or(false) +} + async fn create_run_record( state: &WorkerState, msg: &TicketMessage, run_id: &str, + detail: RecordDetail, ) -> Result<(), Box> { + let full = detail == RecordDetail::Full; let now = chrono::Utc::now().to_rfc3339(); let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); let mut put = state @@ -5027,7 +5141,7 @@ async fn create_run_record( .item( "ticket_body", attr_s( - if matches!(msg.source, TicketSource::Jira | TicketSource::Alert) { + if full && matches!(msg.source, TicketSource::Jira | TicketSource::Alert) { &msg.body } else { "" @@ -5036,7 +5150,11 @@ async fn create_run_record( ) .item( "image_attachments", - AttributeValue::S(serde_json::to_string(&msg.image_attachments).unwrap_or_default()), + AttributeValue::S(if full { + serde_json::to_string(&msg.image_attachments).unwrap_or_default() + } else { + "[]".to_string() + }), ) .item("tokens_in", attr_n(0)) .item("tokens_out", attr_n(0)) @@ -5363,25 +5481,24 @@ async fn finish_without_code( let duration = start.elapsed().as_secs(); let now = chrono::Utc::now().to_rfc3339(); let decision_json = serde_json::to_string(decision).unwrap_or_default(); - let _ = state + // After mark_run_needs_input: only what it didn't already add. + let delta = usage.unrecorded(); + let usage_res = state .dynamo .update_item() .table_name(&state.config.runs_table_name) .key("team_id", attr_s(&msg.team_id)) .key("run_id", attr_s(run_id)) .update_expression( - "SET #status = :s, tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, \ - cache_write_tokens = :cwt, cost_usd = :c, duration_s = :d, updated_at = :t, \ + "SET #status = :s, tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, \ current_pass = :cp, status_run_id = :sri, mcp_servers = :mcp, \ fix_location = :fl, fix_decision = :fd, outside_change_report = :rep", ) .expression_attribute_names("#status", "status") .expression_attribute_values(":s", attr_s(status)) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{:.4}", usage.estimated_cost()))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) @@ -5395,6 +5512,9 @@ async fn finish_without_code( .expression_attribute_values(":rep", attr_s(&format!("{heading}{report}"))) .send() .await; + if usage_res.is_ok() { + usage.mark_recorded(&delta); + } if outside { let analytics_month = chrono::Utc::now().format("%Y-%m").to_string(); @@ -5533,26 +5653,24 @@ async fn mark_run_needs_input( mcp_ids: &[String], ) { let duration = start.elapsed().as_secs(); - let cost = usage.estimated_cost(); + let delta = usage.unrecorded(); let now = chrono::Utc::now().to_rfc3339(); - let _ = state + let usage_res = state .dynamo .update_item() .table_name(&state.config.runs_table_name) .key("team_id", attr_s(&msg.team_id)) .key("run_id", attr_s(run_id)) .update_expression( - "SET #status = :s, tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, cache_write_tokens = :cwt, cost_usd = :c, \ + "SET #status = :s, tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, \ duration_s = :d, updated_at = :t, current_pass = :cp, \ status_run_id = :sri, mcp_servers = :mcp", ) .expression_attribute_names("#status", "status") .expression_attribute_values(":s", attr_s("needs_input")) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{:.4}", cost))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) @@ -5563,6 +5681,9 @@ async fn mark_run_needs_input( ) .send() .await; + if usage_res.is_ok() { + usage.mark_recorded(&delta); + } self::webhooks::emit_run(state, &msg.team_id, run_id, "needs_input").await; // Update analytics counters @@ -5722,7 +5843,7 @@ async fn complete_run( duration: u64, ) -> Result<(), Box> { let now = chrono::Utc::now().to_rfc3339(); - let cost = usage.estimated_cost(); + let delta = usage.unrecorded(); // Update run record in runs table state @@ -5733,7 +5854,9 @@ async fn complete_run( .key("run_id", attr_s(run_id)) .update_expression( "SET #status = :s, pr_url = :pr, pr_number = :pn, branch = :b, \ - tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, cache_write_tokens = :cwt, cost_usd = :c, \ + tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, \ duration_s = :d, updated_at = :t, current_pass = :cp, \ status_run_id = :sri, files_modified = :fm, \ repo = :repo, team_repo = :tr, mcp_servers = :mcp \ @@ -5756,11 +5879,7 @@ async fn complete_run( )), ) .expression_attribute_values(":b", attr_s(&pr.branch)) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{:.4}", cost))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) @@ -5781,6 +5900,7 @@ async fn complete_run( ) .send() .await?; + usage.mark_recorded(&delta); // Update analytics counters (current month + all-time) let month = chrono::Utc::now().format("%Y-%m").to_string(); @@ -5871,21 +5991,15 @@ async fn fail_run( crate::agent::policy::end_run_for_stop(state, &msg.team_id, run_id, &stop).await; return; } - let cost = usage.estimated_cost(); + let delta = usage.unrecorded(); // The one failed-status write: reason, and the pass the record names. let failure = common::run_fail::RunFailure { reason: error_msg, pass: None, only_from: None, - extra: vec![ - ("tokens_in", attr_n(usage.input_tokens)), - ("tokens_out", attr_n(usage.output_tokens)), - ("cache_read_tokens", attr_n(usage.cache_read_tokens)), - ("cache_write_tokens", attr_n(usage.cache_write_tokens)), - ("cost_usd", attr_n(format!("{:.4}", cost))), - ("duration_s", attr_n(duration)), - ], + extra: vec![("duration_s", attr_n(duration))], + add: usage_adds(&delta), }; match common::run_fail::fail_run( &state.dynamo, @@ -5896,7 +6010,10 @@ async fn fail_run( ) .await { - Ok(true) => self::webhooks::emit_run(state, &msg.team_id, run_id, "failed").await, + Ok(true) => { + usage.mark_recorded(&delta); + self::webhooks::emit_run(state, &msg.team_id, run_id, "failed").await + } // Cancelled or merged meanwhile: nothing failed, so nothing to tell. Ok(false) => return, Err(e) => warn!(run_id, error = %e, "Could not mark the run failed"), @@ -5920,6 +6037,17 @@ async fn fail_run( // Check token usage against limit and send warning if needed check_token_usage_warning(state, &msg.team_id, usage).await; + notify_ticket_failed(state, msg, run_id, error_msg).await; +} + +/// Tells the ticket the run failed and why: a GitHub issue comment or a Jira +/// comment, with a link to the run. +async fn notify_ticket_failed( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + error_msg: &str, +) { // Comment on the GitHub issue so the user knows the run failed if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { if let Ok(gh) = GitHubClient::new( @@ -5996,6 +6124,42 @@ pub(crate) fn attr_n(val: impl std::fmt::Display) -> aws_sdk_dynamodb::types::At aws_sdk_dynamodb::types::AttributeValue::N(val.to_string()) } +/// Adds the values a run write's token and cost fields name (`:ti`, `:to`, +/// `:crt`, `:cwt`, `:c`, `:uzero`). Those fields are always ADDed +/// (`tokens_in = if_not_exists(tokens_in, :uzero) + :ti`): an invocation +/// knows only its own calls, so a SET wiped what earlier ones recorded once +/// the checkpoint holding the running total expired. Mark the delta with +/// [`TokenUsage::mark_recorded`] once the write succeeds. +pub(crate) trait RunUsageValues { + fn usage_values(self, d: &crate::models::UsageDelta) -> Self; +} + +impl RunUsageValues + for aws_sdk_dynamodb::operation::update_item::builders::UpdateItemFluentBuilder +{ + fn usage_values(self, d: &crate::models::UsageDelta) -> Self { + self.expression_attribute_values(":ti", attr_n(d.input_tokens)) + .expression_attribute_values(":to", attr_n(d.output_tokens)) + .expression_attribute_values(":crt", attr_n(d.cache_read_tokens)) + .expression_attribute_values(":cwt", attr_n(d.cache_write_tokens)) + .expression_attribute_values(":c", attr_n(format!("{:.6}", d.cost_usd))) + .expression_attribute_values(":uzero", attr_n(0)) + } +} + +/// The run record's token and cost fields for a failure: added, never set. +pub(crate) fn usage_adds( + d: &crate::models::UsageDelta, +) -> Vec<(&'static str, aws_sdk_dynamodb::types::AttributeValue)> { + vec![ + ("tokens_in", attr_n(d.input_tokens)), + ("tokens_out", attr_n(d.output_tokens)), + ("cache_read_tokens", attr_n(d.cache_read_tokens)), + ("cache_write_tokens", attr_n(d.cache_write_tokens)), + ("cost_usd", attr_n(format!("{:.6}", d.cost_usd))), + ] +} + /// Release a ticket-level lock after a run completes (any terminal state). /// Takes the ticket lock the gateway takes before it starts a run (same /// record), so a run started from the worker can't run twice. Fails open on @@ -8396,8 +8560,8 @@ async fn salvage_timeout_pr( // Mark run as completed (not failed) — it produced a PR let now = chrono::Utc::now().to_rfc3339(); - let cost = usage.estimated_cost(); - let _ = state + let delta = usage.unrecorded(); + let usage_res = state .dynamo .update_item() .table_name(&state.config.runs_table_name) @@ -8405,9 +8569,9 @@ async fn salvage_timeout_pr( .key("run_id", attr_s(run_id)) .update_expression( "SET #s = :s, status_run_id = :sri, pr_url = :pu, pr_number = :pn, \ - branch = :b, tokens_in = :ti, tokens_out = :to, \ - cache_read_tokens = :crt, cache_write_tokens = :cwt, \ - cost_usd = :c, duration_s = :d, updated_at = :t, \ + branch = :b, tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, \ error_message = :err", ) .expression_attribute_names("#s", "status") @@ -8416,16 +8580,15 @@ async fn salvage_timeout_pr( .expression_attribute_values(":pu", attr_s(&pr_url)) .expression_attribute_values(":pn", attr_n(pr_number)) .expression_attribute_values(":b", attr_s(branch)) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{cost:.4}"))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":err", attr_s("Partial implementation — agent timed out")) .send() .await; + if usage_res.is_ok() { + usage.mark_recorded(&delta); + } self::webhooks::emit_run(state, &msg.team_id, run_id, "completed").await; Ok(pr_url) @@ -9538,3 +9701,106 @@ mod asking_tests { assert_eq!(jira_comment_link(None, "ABC-7", Some("1")), None); } } + +#[cfg(test)] +mod run_usage_tests { + /// A run's tokens and cost are only ever added to. An invocation knows its + /// own calls; a SET of its total over the record wiped what earlier + /// invocations recorded (a resume after the checkpoint expired wrote a + /// near-zero cost over the run). This reads the worker's sources for a SET + /// of those fields. The review record (REVIEW#, one write per review) is + /// not a run record. + #[test] + fn run_records_never_set_tokens_or_cost() { + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut offenders = Vec::new(); + let mut stack = vec![src]; + while let Some(dir) = stack.pop() { + for entry in std::fs::read_dir(&dir).unwrap().flatten() { + let p = entry.path(); + if p.is_dir() { + stack.push(p); + continue; + } + if p.extension().and_then(|e| e.to_str()) != Some("rs") + || p.ends_with("passes/review_pr.rs") + { + continue; + } + let text = std::fs::read_to_string(&p).unwrap_or_default(); + for (i, line) in text.lines().enumerate() { + for field in [ + "tokens_in", + "tokens_out", + "cache_read_tokens", + "cache_write_tokens", + "cost_usd", + ] { + if line.contains(&format!("{field} = :")) { + offenders.push(format!("{}:{}", p.display(), i + 1)); + } + } + } + } + } + assert!( + offenders.is_empty(), + "add run usage with if_not_exists(field, :uzero) + :v: {offenders:?}" + ); + } +} + +#[cfg(test)] +mod start_failure_tests { + use super::{panic_reason, start_failure_reason}; + + /// A run that can't start says so plainly and keeps the cause the SDK + /// hides behind "service error". + #[test] + fn a_start_failure_is_plain_and_keeps_the_cause() { + let r = start_failure_reason( + "service error: ValidationException: Item size has exceeded the maximum allowed size", + ); + assert!(r.starts_with("CoderHelm could not start this run")); + assert!(r.contains("ValidationException: Item size has exceeded")); + assert_eq!( + start_failure_reason(" "), + "CoderHelm could not start this run: saving the run failed." + ); + } + + #[test] + fn a_panic_becomes_a_reason() { + let p: Box = Box::new("index out of bounds"); + assert_eq!( + panic_reason(p.as_ref()), + "CoderHelm stopped on an internal error: index out of bounds" + ); + let p: Box = Box::new(String::from("boom")); + assert!(panic_reason(p.as_ref()).ends_with("boom")); + let p: Box = Box::new(7u8); + assert_eq!( + panic_reason(p.as_ref()), + "CoderHelm stopped on an internal error." + ); + } + + /// Every way a ticket run ends in error fails the run itself: the worker + /// only logs what orchestrate_ticket returns, so each `return Err` in it + /// must come after a failed-status write or a ticket notice. + #[test] + fn orchestrate_ticket_fails_the_run_before_returning_an_error() { + let src = include_str!("mod.rs"); + let start = src.find("pub async fn orchestrate_ticket(").unwrap(); + let end = start + src[start..].find("\n}\n").unwrap(); + let body = &src[start..end]; + let returns = body.matches("return Err(").count(); + assert_eq!(returns, 1, "a new error return must fail the run first"); + let before = &body[..body.find("return Err(").unwrap()]; + assert!(before.contains("fail_run(") && before.contains("notify_ticket_failed(")); + assert!( + !body.contains(".await?"), + "a `?` in orchestrate_ticket skips the failure" + ); + } +} diff --git a/services/worker/src/passes/proof.rs b/services/worker/src/passes/proof.rs index 287396a19..278401f5a 100644 --- a/services/worker/src/passes/proof.rs +++ b/services/worker/src/passes/proof.rs @@ -423,6 +423,8 @@ impl Finding { "near_match_unresolved" => "Close match not followed up", "history_used" => "Earlier pull requests not built on", "planned_work" => "Planned work not done", + "security" => "Security issue not fixed yet", + "security_unchecked" => "Security check did not run", "optional_task" => "Optional task left out", other => other, } @@ -1215,6 +1217,79 @@ pub fn fix_feedback(findings: &[Finding]) -> String { pub const UNVERIFIED_START: &str = ""; pub const UNVERIFIED_END: &str = ""; const CI_MARK: &str = ""; +/// The mark on each security item: while one is in the description the pull +/// request stays a draft (see `resume::mark_pr_ready`). +pub const SECURITY_MARK: &str = ""; + +/// Whether a finding is a security issue or a security check that didn't run. +fn is_security(f: &Finding) -> bool { + matches!(f.point.trim(), "security" | "security_unchecked") +} + +/// One Open items line, with the mark its settler needs. +fn item_line(f: &Finding) -> String { + if is_security(f) { + format!("{} {SECURITY_MARK}", f.line()) + } else { + f.line() + } +} + +/// Whether the description still holds a security item: the pull request +/// stays a draft until none is left. +pub fn holds_security_items(body: &str) -> bool { + body.contains(SECURITY_MARK) +} + +/// The description with its security items replaced by `items` (all of them +/// gone when `items` is empty), other Open items kept as they are. `None` +/// when there is nothing to change. +pub fn with_security_items(body: &str, items: &[Finding]) -> Option { + let (mut owned, rest) = super::completeness::take_owned(body); + let new: Vec = items.iter().map(item_line).collect(); + if new.is_empty() && !owned.open_items.contains(SECURITY_MARK) { + return None; + } + let kept: Vec<&str> = owned + .open_items + .lines() + .filter(|l| !l.contains(SECURITY_MARK)) + .collect(); + let others: Vec<&str> = kept + .iter() + .copied() + .filter(|l| { + let l = l.trim_start_matches('>').trim_start(); + l.starts_with("- ") || l.starts_with("* ") + }) + .collect(); + let section = if others.is_empty() && new.is_empty() { + String::new() + } else if kept.iter().any(|l| l.trim() == UNVERIFIED_END) { + // Into the section that is there, before its end marker. + let mut out: Vec = Vec::new(); + for l in kept { + if l.trim() == UNVERIFIED_END { + out.extend(new.iter().cloned()); + } + out.push(l.to_string()); + } + out.join("\n") + } else { + format!( + "{UNVERIFIED_START}\n## Open items\n{}\n{UNVERIFIED_END}", + others + .iter() + .map(|l| l.to_string()) + .chain(new) + .collect::>() + .join("\n") + ) + }; + owned.set(super::completeness::Section::OpenItems, section); + let out = super::completeness::assemble(&rest, &owned); + (out != body).then_some(out) +} /// The Open items section, put at the bottom of the PR description: one /// bullet per proof gap, per step the plan left without an owner, and per @@ -1225,7 +1300,7 @@ pub fn gaps_section(findings: &[Finding]) -> String { let of = |s: Settler| findings.iter().filter(move |f| f.settler() == s); let items: Vec = of(Settler::Proof) .chain(of(Settler::Owner)) - .map(Finding::line) + .map(item_line) .chain(of(Settler::Ci).map(|f| format!("{} {CI_MARK}", f.line()))) .collect(); if items.is_empty() { diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 01dc3ed8b..2ad8ab606 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -7,6 +7,7 @@ use crate::agent::provider::ModelProvider; use crate::clients::github::GitHubClient; use crate::models::{ResumeMessage, TicketMessage, TicketSource, TokenUsage}; use crate::passes::quarantine::{self, Gate}; +use crate::passes::RunUsageValues; use crate::passes::{ attr_n, attr_s, implement, plan, review, save_checkpoint, write_pass_trace, FileCache, }; @@ -2785,7 +2786,10 @@ async fn fix_context( &state.http, )?; - let usage = load_usage_from_checkpoint(state, &msg.team_id, &msg.run_id).await; + // This invocation's calls only: every run write adds them to what the + // record holds. (Restoring a running total from the checkpoint and SETting + // it wiped the run's cost once that checkpoint's 7-day TTL expired.) + let usage = TokenUsage::default(); // Load rules and repo instructions so CI fix / review fix have full context let rules = super::load_rules(state, &ticket_msg).await; @@ -3170,6 +3174,9 @@ async fn run_pending_round( .await?; } RoundEnd::Done { files: 0 } => { + if kind == run_round::Kind::SecurityFix { + recheck_security(state, msg, &mut ctx, &pr).await; + } if kind == run_round::Kind::CiFix { super::record_ci_outcome( state, @@ -3203,6 +3210,9 @@ async fn run_pending_round( ) .await; } + if kind == run_round::Kind::SecurityFix { + recheck_security(state, msg, &mut ctx, &pr).await; + } save_checkpoint( state, &msg.team_id, @@ -3232,6 +3242,73 @@ async fn run_pending_round( Ok(()) } +/// After a security fix round: the security check runs again on the pull +/// request, and its Open items say what it found. Fixed, the items go and +/// the pull request may be marked ready; still failing, or a check that +/// didn't run, the items stay (with what it found now) and it stays a draft. +async fn recheck_security( + state: &WorkerState, + msg: &ResumeMessage, + ctx: &mut FixContext, + pr: &PrRef<'_>, +) { + let _ = super::update_pass(state, &msg.team_id, &msg.run_id, "security").await; + let plan = plan::PlanResult { + proposal: String::new(), + tasks: String::new(), + spec: String::new(), + design: String::new(), + repo_tasks: vec![], + fix: None, + }; + let verdict = super::security::Verdict::of( + super::security::run( + state, + &ctx.ticket_msg, + &ctx.github, + &plan, + pr.branch, + &ctx.repo_instructions, + &ctx.provider, + &mut ctx.usage, + &FileCache::default(), + Some(&msg.run_id), + ) + .await, + ); + let note = match &verdict { + super::security::Verdict::Passed => "Security check passed after the security fix", + super::security::Verdict::Findings(_) => { + "Security issues remain after the security fix: they stay under Open items and the pull request stays a draft" + } + super::security::Verdict::NotChecked(_) => { + "The security check couldn't run after the security fix: the pull request stays a draft" + } + }; + super::add_progress_note(state, &msg.team_id, &msg.run_id, note).await; + let items = super::security::open_items(&verdict, false); + let body = match ctx + .github + .get_pull_request(pr.owner, pr.repo, pr.number) + .await + { + Ok(p) => p["body"].as_str().unwrap_or("").to_string(), + Err(e) => { + warn!(run_id = msg.run_id, error = %e, "Could not read the PR to update its security items"); + return; + } + }; + if let Some(updated) = super::proof::with_security_items(&body, &items) { + if let Err(e) = ctx + .github + .update_pr_body(pr.owner, pr.repo, pr.number, &updated) + .await + { + warn!(run_id = msg.run_id, error = %e, "Could not update the PR's security items"); + } + } +} + async fn load_unprocessed_events( state: &WorkerState, run_id: &str, @@ -3521,52 +3598,6 @@ fn collect_review_feedback(events: &[RunEvent]) -> String { .join("\n\n---\n\n") } -async fn load_usage_from_checkpoint( - state: &WorkerState, - team_id: &str, - run_id: &str, -) -> TokenUsage { - if state.config.checkpoints_table_name.is_empty() { - return TokenUsage::default(); - } - let result = state - .dynamo - .get_item() - .table_name(&state.config.checkpoints_table_name) - .key("team_id", attr_s(team_id)) - .key("sk", attr_s(&format!("RUN#{run_id}"))) - .send() - .await; - - match result { - Ok(output) => { - if let Some(item) = output.item() { - let get_n = |key: &str| -> u64 { - item.get(key) - .and_then(|v| v.as_n().ok()) - .and_then(|n| n.parse().ok()) - .unwrap_or(0) - }; - let cost = item - .get("cost_usd") - .and_then(|v| v.as_n().ok()) - .and_then(|n| n.parse::().ok()); - TokenUsage::restored( - &state.config.model_id, - get_n("tokens_in"), - get_n("tokens_out"), - get_n("cache_read"), - get_n("cache_write"), - cost, - ) - } else { - TokenUsage::default() - } - } - Err(_) => TokenUsage::default(), - } -} - /// Compare the current failure against the stored one, persist the update, and /// return true if the run has STALLED (same failure repeating → halt). The pure /// decision (`stall_decision` / `ci_failure_signature`) is unit-tested. @@ -3725,7 +3756,7 @@ async fn set_run_awaiting_ci( duration: u64, ) -> Result> { let now = chrono::Utc::now().to_rfc3339(); - let cost = usage.estimated_cost(); + let delta = usage.unrecorded(); // Conditional on the run NOT being cancelled: a user cancel must be // durable — a racing CI-fix/resume invocation used to blindly overwrite @@ -3739,8 +3770,9 @@ async fn set_run_awaiting_ci( .key("run_id", attr_s(run_id)) .update_expression( "SET #s = :s, pr_url = :pr, pr_number = :pn, branch = :b, \ - tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, cache_write_tokens = :cwt, \ - cost_usd = :c, duration_s = :d, updated_at = :t, current_pass = :cp, \ + tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, current_pass = :cp, \ status_run_id = :sri \ REMOVE error_message, #err, #inc", ) @@ -3754,11 +3786,7 @@ async fn set_run_awaiting_ci( .expression_attribute_values(":pr", attr_s(pr_url)) .expression_attribute_values(":pn", attr_n(pr_number)) .expression_attribute_values(":b", attr_s(branch)) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{:.4}", cost))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("awaiting_ci")) @@ -3766,7 +3794,10 @@ async fn set_run_awaiting_ci( .send() .await; match res { - Ok(_) => Ok(true), + Ok(_) => { + usage.mark_recorded(&delta); + Ok(true) + } // Display for a service error is only "service error" — classify on // the typed error, or a cancelled run surfaced as a hard failure. Err(e) @@ -3901,6 +3932,18 @@ async fn mark_ready( info!(pr_number, "PR is closed — not marking ready"); return; } + // Security issues not fixed yet (or a security check that + // didn't run) are listed under Open items: the PR stays a + // draft until they're gone. + if super::proof::holds_security_items( + pr.get("body").and_then(|v| v.as_str()).unwrap_or(""), + ) { + info!( + pr_number, + "Security items open in the description — the PR stays a draft" + ); + return; + } // E2E fix and generated-test PRs wait for their repeat runs. if !proven && pr @@ -4034,7 +4077,7 @@ async fn complete_run_with_status( duration: u64, ) -> Result<(), Box> { let now = chrono::Utc::now().to_rfc3339(); - let cost = usage.estimated_cost(); + let delta = usage.unrecorded(); let res = state .dynamo @@ -4044,8 +4087,9 @@ async fn complete_run_with_status( .key("run_id", attr_s(run_id)) .update_expression( "SET #s = :s, pr_url = :pr, pr_number = :pn, branch = :b, \ - tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, cache_write_tokens = :cwt, \ - cost_usd = :c, duration_s = :d, updated_at = :t, current_pass = :cp, \ + tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, current_pass = :cp, \ status_run_id = :sri \ REMOVE error_message, #err", ) @@ -4055,11 +4099,7 @@ async fn complete_run_with_status( .expression_attribute_values(":pr", attr_s(pr_url)) .expression_attribute_values(":pn", attr_n(pr_number)) .expression_attribute_values(":b", attr_s(branch)) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .expression_attribute_values(":c", attr_n(format!("{:.4}", cost))) + .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) @@ -4070,7 +4110,10 @@ async fn complete_run_with_status( .send() .await; match res { - Ok(_) => super::webhooks::emit_run(state, &msg.team_id, run_id, status).await, + Ok(_) => { + usage.mark_recorded(&delta); + super::webhooks::emit_run(state, &msg.team_id, run_id, status).await + } Err(e) if format!("{e:?}").contains("ConditionalCheckFailed") => { info!(run_id, "Run is cancelled — not overwriting with completion"); return Ok(()); diff --git a/services/worker/src/passes/round.rs b/services/worker/src/passes/round.rs index 2c3ea582e..f2c9b1b8c 100644 --- a/services/worker/src/passes/round.rs +++ b/services/worker/src/passes/round.rs @@ -427,6 +427,7 @@ pub(crate) async fn round_message( Kind::CiFix => "Fix the failing checks", Kind::ReviewFix => "Address the review", Kind::Feedback => "Address the review comments", + Kind::SecurityFix => "Fix the security issues the check found", }; let conventions = super::load_git_conventions(state, team_id, &ticket.ticket_id).await; conventions.commit_message(&super::ticket_tokens(ticket), summary) diff --git a/services/worker/src/passes/security.rs b/services/worker/src/passes/security.rs index 451afc24c..d117a3e0d 100644 --- a/services/worker/src/passes/security.rs +++ b/services/worker/src/passes/security.rs @@ -15,6 +15,141 @@ pub struct SecurityResult { pub summary: String, } +/// What the security check concluded about the change. +#[derive(Debug, Clone, PartialEq)] +pub enum Verdict { + Passed, + /// Issues, as the audit wrote them. + Findings(String), + /// The check didn't reach a verdict (an API or model error). Never a + /// pass: an error used to count as one, and the PR opened unchecked. + NotChecked(String), +} + +impl Verdict { + pub fn of(r: Result>) -> Verdict { + match r { + Ok(r) if r.passed => Verdict::Passed, + Ok(r) => Verdict::Findings(r.summary), + Err(e) => Verdict::NotChecked(common::run_fail::error_text(&*e)), + } + } + + pub fn passed(&self) -> bool { + matches!(self, Verdict::Passed) + } +} + +/// What the coder is told in a security round whose check didn't run before +/// the pull request opened: look, fix what's found, change nothing otherwise. +/// The check runs again when the round ends. +pub fn recheck_feedback(why: &str) -> String { + format!( + "The security check couldn't run on this change before the pull request opened ({}). \ + Review the change on this branch for security issues: injection, unsafe input handling, \ + secrets in code or logs, missing authorization, unpinned or misspelled dependencies. Fix \ + any you find. If you find none, change nothing.", + common::truncate_str(why.trim(), 300) + ) +} + +/// What the coder is told in a security fix. +pub fn fix_feedback(summary: &str) -> String { + format!("Security audit found vulnerabilities. Fix ALL of the following:\n\n{summary}") +} + +/// One issue of the audit's report: its heading, file and remediation. +fn issues(summary: &str) -> Vec<(String, String, String)> { + let mut out: Vec<(String, String, String)> = Vec::new(); + for line in summary.lines() { + let t = line.trim(); + if let Some(h) = t.strip_prefix("### ") { + out.push((h.trim().to_string(), String::new(), String::new())); + } else if let Some(last) = out.last_mut() { + let field = |name: &str| { + t.trim_start_matches(['-', '*', ' ']) + .strip_prefix(name) + .map(|v| v.trim_start_matches(['*', ':', ' ']).trim().to_string()) + }; + if let Some(f) = field("**File:**").or_else(|| field("File:")) { + last.1 = f; + } else if let Some(r) = field("**Remediation:**").or_else(|| field("Remediation:")) { + last.2 = r; + } + } + } + out +} + +/// The security work the pull request still owes, as Open items: each issue +/// not fixed yet, or the check that didn't run. Each is marked, and the pull +/// request stays a draft while one is listed. `fixing` when a security fix +/// round is about to work on the issues in a fresh invocation. +pub fn open_items(v: &Verdict, fixing: bool) -> Vec { + let settle = if fixing { + "CoderHelm works on it in a fresh step on this pull request and runs the check again; the pull request stays a draft until then." + } else { + "Fix it on this branch; the pull request stays a draft while this line is here (delete it once the fix is checked)." + }; + match v { + Verdict::Passed => Vec::new(), + Verdict::NotChecked(why) => vec![super::proof::Finding { + point: "security_unchecked".to_string(), + detail: format!( + "The security check couldn't run on this change ({}).", + common::truncate_str(why.trim(), 160) + ), + settle: if fixing { + "CoderHelm runs it again in a fresh step on this pull request; the pull request stays a draft until it passes." + } else { + "Check the change for security issues before merging; the pull request stays a draft while this line is here (delete it once checked)." + } + .to_string(), + check: "security".to_string(), + ..Default::default() + }], + Verdict::Findings(summary) => { + let found = issues(summary); + if found.is_empty() { + let flat = summary + .replace("SECURITY_FAIL", "") + .split_whitespace() + .collect::>() + .join(" "); + return vec![super::proof::Finding { + point: "security".to_string(), + detail: if flat.is_empty() { + "The security check found issues in this change.".to_string() + } else { + flat + }, + settle: settle.to_string(), + check: "security".to_string(), + ..Default::default() + }]; + } + found + .into_iter() + .map(|(title, file, fix)| super::proof::Finding { + point: "security".to_string(), + detail: if file.is_empty() { + format!("{title}.") + } else { + format!("{title} in `{file}`.") + }, + settle: if fix.is_empty() { + settle.to_string() + } else { + format!("{fix} {settle}") + }, + check: "security".to_string(), + ..Default::default() + }) + .collect() + } + } +} + #[allow(clippy::too_many_arguments)] pub async fn run( state: &WorkerState, @@ -282,3 +417,82 @@ impl ToolExecutor for SecurityToolExecutor<'_> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + const REPORT: &str = "SECURITY_FAIL\n\n### [HIGH] — SQL built from user input\n- **File:** src/db.rs:42\n- **Category:** A03 Injection\n- **Remediation:** Use a bound parameter.\n\n### [LOW] — Token logged\n- **File:** src/auth.rs:7\n"; + + /// A check that errored is never a pass. + #[test] + fn an_error_is_not_a_pass() { + let v = Verdict::of(Err("service error: throttled".into())); + assert!(!v.passed()); + assert!(matches!(v, Verdict::NotChecked(ref e) if e.contains("throttled"))); + let items = open_items(&v, false); + assert_eq!(items.len(), 1); + assert_eq!(items[0].point, "security_unchecked"); + assert!(Verdict::of(Ok(SecurityResult { + passed: true, + summary: String::new() + })) + .passed()); + } + + /// Each issue the audit names is its own Open item, with where and how. + #[test] + fn findings_become_open_items() { + let items = open_items(&Verdict::Findings(REPORT.to_string()), true); + assert_eq!(items.len(), 2); + assert!(items[0].detail.contains("SQL built from user input")); + assert!(items[0].detail.contains("`src/db.rs:42`")); + assert!(items[0].settle.starts_with("Use a bound parameter.")); + assert!(items[0].settle.contains("fresh step")); + assert!(items[1].detail.contains("`src/auth.rs:7`")); + // A report without headings is still one item, never none. + let one = open_items( + &Verdict::Findings("SECURITY_FAIL eval of input".into()), + false, + ); + assert_eq!(one.len(), 1); + assert!(one[0].detail.contains("eval of input")); + } + + /// The items hold the draft and come out of the description when fixed, + /// leaving every other Open item alone. + #[test] + fn the_description_holds_security_items_until_they_are_fixed() { + use crate::passes::proof; + let other = proof::Finding { + point: "assumption".into(), + detail: "The API returns at most 100 rows.".into(), + ..Default::default() + }; + let mut all = vec![other]; + all.extend(open_items(&Verdict::Findings(REPORT.into()), true)); + let body = format!("## Summary\nx\n\n{}", proof::gaps_section(&all)); + assert!(proof::holds_security_items(&body)); + + let fixed = proof::with_security_items(&body, &[]).unwrap(); + assert!(!proof::holds_security_items(&fixed)); + assert!(fixed.contains("The API returns at most 100 rows.")); + assert!(fixed.contains("## Open items")); + + // Still failing after the fix: the new findings replace the old. + let again = open_items(&Verdict::NotChecked("timeout".into()), false); + let body2 = proof::with_security_items(&body, &again).unwrap(); + assert!(proof::holds_security_items(&body2)); + assert!(!body2.contains("SQL built from user input")); + assert!(body2.contains("Security check did not run")); + + // Only security items: the section goes when they do. + let only = format!( + "## Summary\nx\n\n{}", + proof::gaps_section(&open_items(&Verdict::Findings(REPORT.into()), false)) + ); + let gone = proof::with_security_items(&only, &[]).unwrap(); + assert!(!gone.contains("Open items")); + assert_eq!(proof::with_security_items(&gone, &[]), None); + } +}