diff --git a/docs/incidents.md b/docs/incidents.md index bccb98177..4a9a08a58 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -59,6 +59,7 @@ pipeline still calls it there. | ab. `ab_label_prefix` | A failing-test fix's staging deploy and staging end-to-end checks were skipped on its draft. The reading of why went through the staging workflow line by line and kept every quoted string next to a label test as a label name, so a prefix test (`startsWith(github.event.label.name, 'E2E:')`) became a label named `E2E:`, and a condition that needs the staging label *and* `CI:E2E` read as either one. The staging label was refused, the team's `E2E:*` family let the bare `E2E:` through, and CoderHelm added `CI:E2E` and `E2E:`. Adding a missing label creates it, so the repository got an `E2E:` label that matches no area, and `CI:E2E` alone could never run the job. | A job's `if:` is read as an expression (multi-line blocks included) into the label combinations that run it, with those of the jobs it needs. A prefix or substring test is a pattern, never a label: CoderHelm adds only an existing repository label that satisfies it, the one the team's settings name when several do, and nothing when that isn't one certain label; a family allows `E2E:nav`, never `E2E:`. A label is added only when it alone runs the check, the settings allow it, it isn't a deploy, staging or production label and none is on the pull request; otherwise the hold names the exact real label for a person to add. Labels the old reading added that were a bare prefix or couldn't run their check alone come off when CoderHelm itself put them on, and a bare-prefix repository label GitHub made for that add is deleted when nothing else carries it. | | ac. `ac_partial_and_red_ci` | A Jira run stopped after two steps that changed nothing (the coder twice said the last planned file needed no change, in words the plan check did not know) and a separate salvage path opened "⚠️ Partial", "Closes #0", "ran out of time" and marked it completed; another run's CI fix changed nothing and the run was completed with its pull request marked ready while every check was red. | One path opens a stopped run's pull request (`stop_pr`: ticket line, Not finished with done and left tasks and the recorded reason); no body names issue `#0` (client guard); a planned file the coder says needs no change settles and stays settled across steps; a step after a stalled one takes one task with a different approach; a CI fix that changes nothing tries again with fresh evidence (reporter comments, annotations, rerun on infrastructure failures), then holds the draft with what fails and the run needs a person; `ready::decide` never marks a pull request ready with a failing or running check; a source scan allows `create_pull_request` and `mark_pr_ready` only in their one place each. | | ad. `ad_hand_back_reply` | A coder ended its step with "I couldn't finish, please complete the remaining tasks manually". Nothing it lacked was a credential, access, a product decision, an ambiguous ticket or an approval; its words alone handed the work to a person. | A model reply that hands the work back for a reason not on the human-only list is not an ending: the implement pass tells the coder to change its approach and runs it again, and a reply that still changes nothing is a step without progress, which climbs the supervisor's ladder (one task, other tools, a re-split, the strongest model, then the stuck task deferred with its reason) until the run finishes with what is done. Only a reply naming something on the list makes a hand-back. Every coder's system prompt carries the same stance (`ownership::coder_stance`), and a source scan fails on a hand-off phrase in any prompt or message (`ownership`). | +| ae. `ae_budget_rounds` | Two loops of fix rounds still stopped on their own budget after the supervisor took every other ending. At eight automatic pushes the CI-only rounds on a finished run's pull request marked it ready, completed the run with its checks red and said a comment naming a change would start the next round, even while each round turned another red check green; at two rounds the self-review on CoderHelm's own pull request said the same and left its findings holding the draft, even while each round closed one. | Both loops follow `supervisor::next_round`: rounds go on while they make progress (checks that were red turn green, findings close), past the cap up to twice it and below the spend ceiling; a round without progress changes approach (one item, a fresh context with small edits, a re-split, the strongest model). When the rounds end, the findings left move to "Deferred" with the reason and stop holding the draft, and the run finishes; red checks are reverted to the last green head and deferred, or, when nothing can come out, the run fails with what fails and why. No message asks for a comment to go on: the phrases are on the `ownership` hand-off list. | ## Adding a case diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index 194e67c50..58660256c 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -758,6 +758,21 @@ pub(crate) async fn run_for_branch( Some((get("run_id"), get("status"))) } +/// What the pull request is told when CoderHelm's fix rounds on its E2E +/// failures end: what still fails, and why the rounds ended. No hand-off. +fn e2e_rounds_ended_note(caused: &[&Line], why: &str) -> String { + format!( + "These E2E failures may come from this change, and CoderHelm's fix rounds on them ended \ + ({why}). Each round tried a different approach once one made no progress. Still \ + failing:\n\n{}", + caused + .iter() + .map(|l| format!("- {}", l.text)) + .collect::>() + .join("\n") + ) +} + /// What happens when E2E fails on a PR Coderhelm opened: fix what the change /// broke; otherwise confirm with one re-run and say why, once. async fn own_pr_failures( @@ -814,23 +829,36 @@ async fn own_pr_failures( info!(pr, run_id, "E2E failure left to the run's own CI-fix loop"); return; } - if !super::claim_auto_fix_slot(state, &msg.team_id, &run_id).await { - super::record_ci_outcome( - state, - &msg.team_id, - &run_id, - super::CiOutcome::HandedOff(super::GaveUp::Budget), - ) - .await; - let body = format!( - "These E2E failures may come from this change. CoderHelm has used the automatic fix rounds this PR has, so it doesn't start another on its own; a comment naming a change starts the next one right away:\n\n{}", - caused.iter().map(|l| format!("- {}", l.text)).collect::>().join("\n") - ); - let _ = gh - .create_issue_comment(&msg.repo_owner, &msg.repo_name, pr, &body) + // The same rounds as every CI fix after the run, by the supervisor's + // rule: on while failures turn green, a new approach when a round + // makes no progress, and when they end the pull request says what + // fails and why, never "a comment starts the next one". + let failing: Vec = caused.iter().map(|l| l.title.clone()).collect(); + let rung = match super::claim_auto_fix_round(state, &msg.team_id, &run_id, &failing).await { + super::AutoFix::Round(rung) => rung, + super::AutoFix::Busy => { + info!( + pr, + run_id, "E2E fix round not claimed now (busy or unreadable)" + ); + return; + } + super::AutoFix::End(why) => { + super::record_ci_outcome( + state, + &msg.team_id, + &run_id, + super::CiOutcome::HandedOff(super::GaveUp::NoProgress), + ) .await; - return; - } + let body = e2e_rounds_ended_note(&caused, &why); + super::add_progress_note(state, &msg.team_id, &run_id, &body).await; + let _ = gh + .create_issue_comment(&msg.repo_owner, &msg.repo_name, pr, &body) + .await; + return; + } + }; let body = format!( "E2E tests failed on this PR's commit `{sha}` and nothing outside this change explains them (they aren't known to be flaky and they pass on `{main}`). Fix the application code this PR changed so these tests pass. Do not change, skip or loosen the tests themselves unless the test is plainly wrong about the intended behaviour, and say so if it is.\n\n{items}\n\nRun: {url}", sha = msg.head_sha.get(..7).unwrap_or(&msg.head_sha), @@ -845,7 +873,7 @@ async fn own_pr_failures( .collect::>() .join("\n"), url = run.url, - ); + ) + &super::supervisor::round_instruction(rung, "these E2E failures"); let fb = FeedbackMessage { github_wait: Default::default(), team_id: msg.team_id.clone(), diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index a6017258f..0d98378c5 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -249,41 +249,7 @@ pub async fn run( } if !branch.is_empty() && may_update { // The run's ticket, so the merge commit carries its real key. - let ticket_msg = crate::models::TicketMessage { - github_wait: Default::default(), - team_id: msg.team_id.clone(), - installation_id: msg.installation_id, - source: if ticket.2 > 0 { - TicketSource::Github - } else { - TicketSource::Jira - }, - ticket_id: ticket.0.clone(), - title: ticket.1.clone(), - body: String::new(), - repo_owner: msg.repo_owner.clone(), - repo_name: msg.repo_name.clone(), - issue_number: ticket.2, - sender: String::new(), - requester: None, - base_branch, - image_attachments: vec![], - continuation: 0, - continuation_run_id: None, - first_attempt_ms: 0, - resume_from: None, - retry_of_run: false, - model_retries: 0, - ticket_type: None, - ticket_update_note: None, - ticket_history_note: None, - plan_cache_key: None, - team_instructions: String::new(), - coder_learning: String::new(), - person_direction: None, - answers: Vec::new(), - new_run_id: None, - }; + let ticket_msg = run_ticket_message(&msg, &ticket, base_branch); if let Some(ask) = &update_ask { let (line, pushed) = super::branch_update::run( state, @@ -378,29 +344,38 @@ pub async fn run( if resume_owns_ci && msg.review_id == 0 { info!(run_id = %msg.run_id, status = %run_status, "Run is awaiting CI / running — resume owns CI, not attaching CI failures"); } - let mut ci_failure_block = if msg.review_id == 0 && !resume_owns_ci { + // The failing checks (names, and the log the fix reads). + let (failing_checks, ci_logs) = if msg.review_id == 0 && !resume_owns_ci { let branch = get_pr_branch(state, &msg).await.unwrap_or_default(); - match fetch_ci_failures(&github, &msg, &branch).await { - Some(logs) => format!( - "\n## CI Failures\nThe following CI checks are failing. Fix these issues as well:\n\n```\n{}\n```\n", - if logs.len() > 12000 { format!("... (truncated)\n{}", common::tail_str(&logs, 12000)) } else { logs } - ), - None => String::new(), - } + fetch_ci_failures(&github, &msg, &branch) + .await + .unwrap_or_default() } else { + Default::default() + }; + let mut ci_failure_block = if ci_logs.is_empty() { String::new() + } else { + format!( + "\n## CI Failures\nThe following CI checks are failing. Fix these issues as well:\n\n```\n{}\n```\n", + if ci_logs.len() > 12000 { format!("... (truncated)\n{}", common::tail_str(&ci_logs, 12000)) } else { ci_logs.clone() } + ) }; // CI fixing riding along with a human comment is still an automated fix: - // it draws from the same per-run auto-fix budget as CI-only cycles (claimed - // below). Out of budget → answer the human, leave CI to a person. + // it draws from the same per-run rounds as CI-only cycles (claimed below), + // by the supervisor's rule. When the rounds are over, the person's + // comment is still answered, without the CI fix. let ci_only_cycle = comments.is_empty() && msg.review_body.trim().is_empty(); - if !ci_failure_block.is_empty() - && !ci_only_cycle - && !super::claim_auto_fix_slot(state, &msg.team_id, &msg.run_id).await - { - info!(run_id = %msg.run_id, "Auto-fix budget spent — answering feedback without the CI fix"); - ci_failure_block.clear(); + let mut ci_rung = super::supervisor::Rung::Continue; + if !ci_failure_block.is_empty() && !ci_only_cycle { + match super::claim_auto_fix_round(state, &msg.team_id, &msg.run_id, &failing_checks).await { + super::AutoFix::Round(rung) => ci_rung = rung, + other => { + info!(run_id = %msg.run_id, ?other, "No CI fix round — answering feedback without the CI fix"); + ci_failure_block.clear(); + } + } } let has_ci_failures = !ci_failure_block.is_empty(); @@ -464,18 +439,43 @@ pub async fn run( // CI-ONLY churn (no unanswered human comment or review to answer — the // all-empty case already returned above, so reaching here with both empty - // means CI failures are the sole driver) is the automated-fix path. Draw it - // from the durable budget so a PR that structurally can't go green (e.g. - // codegen that can't run in the sandbox) can't churn forever. Human feedback - // is ALWAYS honored, never budget-gated. The claim is atomic, so concurrent - // feedback webhooks for one run can't overshoot the cap. - if comments.is_empty() - && msg.review_body.trim().is_empty() - && !super::claim_auto_fix_slot(state, &msg.team_id, &msg.run_id).await - { - end_auto_fix_rounds(state, &github, &msg).await; - return Ok(()); + // means CI failures are the sole driver) is the automated-fix path, under + // the supervisor's rule (`claim_auto_fix_round`): rounds go on while + // checks that were red turn green, up to twice the cap and below the + // spend ceiling; a round without progress changes approach; when the + // rounds are over the run ends with what fails and why + // (`end_auto_fix_rounds`), never waiting on a comment. Human feedback is + // ALWAYS honored, never budget-gated. The claim is a compare-and-set, so + // concurrent feedback webhooks for one run can't take the same round. + if comments.is_empty() && msg.review_body.trim().is_empty() { + match super::claim_auto_fix_round(state, &msg.team_id, &msg.run_id, &failing_checks).await { + super::AutoFix::Round(rung) => ci_rung = rung, + super::AutoFix::End(why) => { + end_auto_fix_rounds( + state, + &github, + &msg, + &ticket, + &failing_checks, + &ci_logs, + &why, + &usage, + start.elapsed().as_secs(), + ) + .await; + return Ok(()); + } + super::AutoFix::Busy => { + info!(run_id = %msg.run_id, "Another invocation holds this CI round — nothing to do here"); + return Ok(()); + } + } } + // A round without progress changes approach (`supervisor::next_rung`). + ci_failure_block.push_str(&super::supervisor::round_instruction( + ci_rung, + &format!("the failing checks ({})", failing_checks.join(", ")), + )); // A person asked for this: the run guard's counts start over. A cycle only // CI asked for is a pass like any other, and the guard can stop it. if comments.is_empty() && msg.review_body.trim().is_empty() { @@ -943,7 +943,12 @@ Rules: vec![serde_json::json!({"type": "text", "text": prompt})], )]; - let model_id = provider.primary_model_id(); + // A round on the ladder's escalate rung takes the strongest model. + let model_id = if ci_rung == super::supervisor::Rung::Escalate { + provider.implement_model_id("complex") + } else { + provider.primary_model_id() + }; let mut response = provider::converse( state, &provider, @@ -3430,12 +3435,13 @@ pub(crate) fn failed_check_lines(failed: &[&serde_json::Value]) -> String { out } -/// Check CI status for a PR branch. Returns Some(logs) if there are failures, None if CI is green or absent. +/// Check CI status for a PR branch. Returns the failing checks' names and +/// their logs if there are failures, None if CI is green or absent. async fn fetch_ci_failures( github: &GitHubClient, msg: &FeedbackMessage, branch: &str, -) -> Option { +) -> Option<(Vec, String)> { if branch.is_empty() { return None; } @@ -3457,6 +3463,12 @@ async fn fetch_ci_failures( if failed.is_empty() { return None; } + let names: Vec = failed + .iter() + .map(|r| r["name"].as_str().unwrap_or("check").to_string()) + .collect::>() + .into_iter() + .collect(); // Try to get workflow run logs for the first failed check let workflow_run_id = failed @@ -3469,7 +3481,7 @@ async fn fetch_ci_failures( .get_workflow_run_logs(&msg.repo_owner, &msg.repo_name, workflow_run_id) .await { - return Some(logs); + return Some((names, logs)); } } @@ -3479,13 +3491,14 @@ async fn fetch_ci_failures( .await { if !annotations.is_empty() { - return Some(annotations); + return Some((names, annotations)); } } // Last resort: the failed checks' names, and for a commit status (CI // outside GitHub Actions) what it said and where its log is. - Some(failed_check_lines(&failed)) + let lines = failed_check_lines(&failed); + Some((names, lines)) } /// Make sure the run's PR is open before feedback work starts, reattaching or @@ -3497,109 +3510,130 @@ const CANCEL_PR_CLOSED_BY_HUMAN: &str = "pr_closed_by_human"; /// Whether the run has been cancelled (consistent read — cancel must win /// against a racing pass). -/// End the automated CI fix rounds on a PR once their budget is spent. +/// End the CI-only fix rounds on a PR once the supervisor's rule ends them +/// (`claim_auto_fix_round` gave `AutoFix::End`): the same ending as the +/// run's own CI loop (`resume::end_red_ci_rounds`). What broke the checks +/// comes out first (back to the last green head, else the last planned +/// task, deferred and named on the pull request) and CI decides again; +/// when nothing can come out, the run ends failed with what fails and why. +/// Never "a comment starts the next round": nothing waits on a person. /// -/// Ordering matters for crash-safety. The RELIABLE, idempotent signals run -/// first — mark the PR ready and finalize the run (cancel-guarded, clearing the -/// stale partial/error marker) — so that even if this invocation dies mid-way, -/// the human still sees a ready PR and a redelivery just repeats these no-ops. -/// The explanatory note + PR comment run LAST, gated by an atomic -/// `handoff_notified` marker so repeated webhooks on the now-finalized run don't -/// spam the PR. If the comment is lost to a crash, the PR is already marked -/// ready — the worst case is a missing comment, never a stuck draft. -async fn end_auto_fix_rounds(state: &WorkerState, github: &GitHubClient, msg: &FeedbackMessage) { +/// Once per head: a later webhook on the same red head finds the marker +/// and does nothing, so the pull request and the ticket hear it once. +#[allow(clippy::too_many_arguments)] +async fn end_auto_fix_rounds( + state: &WorkerState, + github: &GitHubClient, + msg: &FeedbackMessage, + ticket: &(String, String, u64), + failing: &[String], + logs: &str, + why: &str, + usage: &TokenUsage, + duration: u64, +) { use aws_sdk_dynamodb::types::AttributeValue; - // Respect a cancel (best-effort early out; the status write below is also - // cancel-guarded for the race window). + // Respect a cancel (best-effort early out; the endings below are + // cancel-guarded too). if run_is_cancelled(state, &msg.team_id, &msg.run_id).await { return; } - - // (1) Reliable signal: un-draft the PR. Idempotent (no-ops if already ready). - crate::passes::resume::mark_pr_ready( - state, - &msg.team_id, - github, - &msg.repo_owner, - &msg.repo_name, - msg.pr_number, - ) - .await; - - // (2) Finalize the run — completed, stale error cleared, never clobbering a - // cancel. Safe to repeat on redelivery. - let now = chrono::Utc::now().to_rfc3339(); - let wrote = state + let branch = get_pr_branch(state, msg).await.unwrap_or_default(); + let head = super::round::branch_head(github, &msg.repo_owner, &msg.repo_name, &branch).await; + let first = state .dynamo .update_item() .table_name(&state.config.runs_table_name) .key("team_id", AttributeValue::S(msg.team_id.clone())) .key("run_id", AttributeValue::S(msg.run_id.clone())) - .update_expression( - "SET #s = :s, status_run_id = :sri, updated_at = :t REMOVE error_message, #err", - ) - .condition_expression(common::run_status::not_ended("#s")) - .expression_attribute_names("#s", "status") - .expression_attribute_names("#err", "error") - .expression_attribute_values(":s", AttributeValue::S("completed".to_string())) - .expression_attribute_values( - ":sri", - AttributeValue::S(format!("completed#{}", msg.run_id)), - ) - .expression_attribute_values(":t", AttributeValue::S(now)) - .ended_values() + .update_expression("SET auto_fix_end_head = :h") + .condition_expression("attribute_not_exists(auto_fix_end_head) OR auto_fix_end_head <> :h") + .expression_attribute_values(":h", AttributeValue::S(head.clone())) .send() .await .is_ok(); - if wrote { - super::webhooks::emit_run(state, &msg.team_id, &msg.run_id, "completed").await; + if !first { + info!(run_id = %msg.run_id, head = %head, "CI fix rounds already ended on this head"); + return; } - // When it was handed off (the first time only), for the weekly summary. - super::record_ci_outcome( + warn!(run_id = %msg.run_id, why, "CI fix rounds end: what broke the checks comes out, or the run fails with what fails"); + let base_branch = resolve_pr_base(github, msg).await; + let ticket_msg = run_ticket_message(msg, ticket, base_branch); + let url = format!( + "https://github.com/{}/{}/pull/{}", + msg.repo_owner, msg.repo_name, msg.pr_number + ); + let excerpt = super::resume::failure_excerpt(logs); + if let Err(e) = super::resume::end_red_ci_rounds( state, - &msg.team_id, + &ticket_msg, &msg.run_id, - super::CiOutcome::HandedOff(super::GaveUp::NoChange), + github, + (&branch, msg.pr_number, &url), + usage, + duration, + failing, + &excerpt, + &auto_fix_rounds_tried(why), ) - .await; - - // (3) Explain ONCE. The marker write wins for exactly one invocation; a - // redelivered/concurrent event sees the marker and skips (no PR spam). Done - // last so a crash here can't suppress the reliable signals above. - let first_notify = state - .dynamo - .update_item() - .table_name(&state.config.runs_table_name) - .key("team_id", AttributeValue::S(msg.team_id.clone())) - .key("run_id", AttributeValue::S(msg.run_id.clone())) - .update_expression("SET handoff_notified = :true") - .condition_expression("attribute_not_exists(handoff_notified)") - .expression_attribute_values(":true", AttributeValue::Bool(true)) - .send() - .await - .is_ok(); - if first_notify { - warn!(run_id = %msg.run_id, "Auto-fix budget spent: CI fix rounds stop on this pull request"); - let note = auto_fix_spent_note(); - super::add_progress_note(state, &msg.team_id, &msg.run_id, ¬e).await; - let _ = github - .create_issue_comment(&msg.repo_owner, &msg.repo_name, msg.pr_number, ¬e) - .await; + .await + { + warn!(run_id = %msg.run_id, error = %e, "Could not end the CI fix rounds"); } } -/// What CoderHelm says when its CI fix rounds on a pull request are spent: -/// what it did, where the pull request stands, and what starts the next -/// round. Never a hand-off. -fn auto_fix_spent_note() -> String { - format!( - "CoderHelm ran {} fix rounds on this pull request's CI and it is still red; the failing \ - checks are listed on the pull request, which stays held until they pass. CoderHelm \ - stops starting rounds on its own here so the pull request doesn't loop, and a comment \ - naming a change starts the next round right away.", - super::MAX_AUTO_FIX_PUSHES - ) +/// What the CI-only fix rounds tried, as the failing-checks section and the +/// run's failure name it: how many rounds, and why they ended. +pub(crate) fn auto_fix_rounds_tried(why: &str) -> Vec { + vec![format!( + "CoderHelm's CI fix rounds on this pull request, each with a different approach once one \ + made no progress; they ended after {why}" + )] +} + +/// The run's ticket as a message, for the passes that work on the pull +/// request (the conflict merge, the end of the CI fix rounds). +fn run_ticket_message( + msg: &FeedbackMessage, + ticket: &(String, String, u64), + base_branch: String, +) -> crate::models::TicketMessage { + crate::models::TicketMessage { + github_wait: Default::default(), + team_id: msg.team_id.clone(), + installation_id: msg.installation_id, + source: if ticket.2 > 0 { + TicketSource::Github + } else { + TicketSource::Jira + }, + ticket_id: ticket.0.clone(), + title: ticket.1.clone(), + body: String::new(), + repo_owner: msg.repo_owner.clone(), + repo_name: msg.repo_name.clone(), + issue_number: ticket.2, + sender: String::new(), + requester: None, + base_branch, + image_attachments: vec![], + continuation: 0, + continuation_run_id: None, + first_attempt_ms: 0, + resume_from: None, + retry_of_run: false, + model_retries: 0, + ticket_type: None, + ticket_update_note: None, + ticket_history_note: None, + plan_cache_key: None, + team_instructions: String::new(), + coder_learning: String::new(), + person_direction: None, + answers: Vec::new(), + new_run_id: None, + } } /// A person ended the run (cancelled or closed it): no feedback runs on it. diff --git a/services/worker/src/passes/incidents/aa_promised_round.rs b/services/worker/src/passes/incidents/aa_promised_round.rs index 483df7599..b3470306a 100644 --- a/services/worker/src/passes/incidents/aa_promised_round.rs +++ b/services/worker/src/passes/incidents/aa_promised_round.rs @@ -171,7 +171,7 @@ fn every_round_budget_bounds_it() { handed: true, ..base.clone() }, - "handed the findings to a person", + "fix rounds on its own review's findings ended", ), ( RoundBudget { @@ -247,10 +247,10 @@ fn the_pipeline_queues_the_round_and_routes_finished_runs_to_it() { assert!(fn_src(ready_src, "async fn fix_own_findings(").contains("queue_own_review_round(")); let resume_src = include_str!("../resume.rs"); - // The run's own stop marks its rounds as over, so none is queued after. - assert!(fn_src(resume_src, "async fn stop_on_own_findings(").contains("OWN_REVIEW_HANDED")); + // The run's own end of its rounds marks them over, so none is queued after. + assert!(fn_src(resume_src, "async fn finish_on_own_findings(").contains("OWN_REVIEW_HANDED")); let queue = fn_src(resume_src, "pub(crate) async fn queue_own_review_round("); - assert!(queue.contains("claim_auto_fix_slot(")); + assert!(queue.contains("claim_auto_fix_slot_upto(")); assert!(queue.contains("Kind::ReviewFix")); let review_src = include_str!("../review_pr.rs"); diff --git a/services/worker/src/passes/incidents/ae_budget_rounds.rs b/services/worker/src/passes/incidents/ae_budget_rounds.rs new file mode 100644 index 000000000..a21bd6114 --- /dev/null +++ b/services/worker/src/passes/incidents/ae_budget_rounds.rs @@ -0,0 +1,281 @@ +//! ae. Two loops of fix rounds still stopped on their own budget and waited +//! on a person after #635 moved every other ending onto the supervisor: +//! +//! - the CI-only fix rounds on a finished run's pull request: at eight +//! automatic pushes CoderHelm marked the pull request ready, completed the +//! run with its checks red, and said it "stops starting rounds on its own +//! here ... a comment naming a change starts the next round right away", +//! even when every round had turned another red check green; +//! - the self-review rounds on CoderHelm's own pull request: at two rounds +//! it posted "a comment naming a change starts the next round right away" +//! and left the findings holding the draft, even when each round closed +//! one. +//! +//! Guarantee: both loops follow the supervisor's rule +//! (`supervisor::next_round`). Rounds go on while they make progress +//! (checks that were red turn green, findings close), past the cap up to +//! twice it and below the run's spend ceiling. A round without progress +//! changes approach (one item, a fresh context with small edits, a +//! re-split, the strongest model). When the rounds end, what is left is +//! deferred with the reason (the findings move to "Deferred" and stop +//! holding the draft; what broke the checks is reverted to the last green +//! head and deferred), or, when nothing can come out and checks are red, +//! the run fails with exactly what fails. Nothing waits on a comment. + +use super::fixture::fn_src; +use crate::passes::supervisor::{self, Ending, Revert, RoundStep, Rung}; +use crate::passes::{feedback, own_review, ownership, resume, review_pr, MAX_AUTO_FIX_PUSHES}; + +const OLD_CI: &str = "a comment naming a change starts the next round right away"; + +fn checks(range: std::ops::RangeInclusive) -> Vec { + range.map(|i| format!("check-{i}")).collect() +} + +/// Drives the CI-only rounds over the failing checks each round leaves +/// (`after[i]` fails once round `i` ran): what each round's claim gave, and +/// how the loop ended (`None` while checks were still red and a round was +/// given for each). +fn ci_rounds(after: &[Vec], first: Vec) -> (Vec, Vec) { + let (mut rounds, mut before, mut stalled) = (0u32, Vec::::new(), 0u32); + let mut failing = first; + let mut steps = Vec::new(); + for next in after { + if failing.is_empty() { + break; + } + let step = crate::passes::auto_fix_step(rounds, &before, &failing, stalled, 0.0); + steps.push(step.clone()); + let RoundStep::Round { stalled: s, .. } = step else { + break; + }; + rounds += 1; + stalled = s; + before = failing; + failing = next.clone(); + } + (steps, failing) +} + +/// The old rule: a round only while fewer than eight pushes were taken. +fn old_ci_rounds(needed: usize) -> usize { + needed.min(MAX_AUTO_FIX_PUSHES as usize) +} + +#[test] +fn ci_only_rounds_past_the_cap_go_on_while_checks_turn_green_and_finish() { + // Twelve red checks; every round turns one green (a lint stage, then + // types, then each test suite). + let after: Vec> = (2..=13).map(|i| checks(i..=12)).collect(); + let (steps, left) = ci_rounds(&after, checks(1..=12)); + assert!(left.is_empty(), "the checks end green: {left:?}"); + assert_eq!(steps.len(), 12); + assert!(steps.len() > MAX_AUTO_FIX_PUSHES as usize); + assert!(steps.len() <= supervisor::ceiling(MAX_AUTO_FIX_PUSHES) as usize); + for s in &steps { + assert_eq!( + s, + &RoundStep::Round { + rung: Rung::Continue, + stalled: 0 + } + ); + } + // Green: the run finishes, nothing deferred, nothing failing. + assert_eq!( + supervisor::end_of_rounds(&[], "", &[]), + Ending::Finished { deferred: vec![] } + ); + // The old rule stopped after eight rounds with four checks still red + // and asked for a comment. + assert_eq!(old_ci_rounds(12), 8); + assert_eq!(after[old_ci_rounds(12) - 1].len(), 4); +} + +#[test] +fn ci_only_rounds_without_progress_change_approach_then_end_with_the_cause() { + let red = checks(1..=2); + let after: Vec> = (0..20).map(|_| red.clone()).collect(); + let (steps, left) = ci_rounds(&after, red.clone()); + let rungs: Vec = steps + .iter() + .filter_map(|s| match s { + RoundStep::Round { rung, .. } => Some(*rung), + RoundStep::End { .. } => None, + }) + .collect(); + assert_eq!( + rungs, + vec![ + Rung::Continue, + Rung::Narrow, + Rung::SwitchTools, + Rung::Resplit, + Rung::Escalate + ] + ); + for r in &rungs[1..] { + assert!(!supervisor::round_instruction(*r, "the failing checks").is_empty()); + } + assert!(supervisor::round_instruction(Rung::Escalate, "x").contains(supervisor::ESCALATED)); + let Some(RoundStep::End { why }) = steps.last() else { + panic!("{steps:?}") + }; + assert!(why.contains("made no progress"), "{why}"); + // What broke the checks comes out first, deferred with the reason, and + // CI decides again. + let heads = vec![("c9".to_string(), false), ("c8".to_string(), true)]; + assert_eq!( + supervisor::revert_for(&heads, &[], 0), + Revert::ToHead("c8".into()) + ); + // Nothing can come out: the run fails with what fails and why. + assert_eq!( + supervisor::end_of_rounds(&[], why, &left), + Ending::Failed, + "red checks never finish" + ); + let tried = feedback::auto_fix_rounds_tried(why); + let cause = format!( + "{}. {}", + resume::ci_failing_reason(&left, "error[E0425]: cannot find value", tried.len()), + tried.join("; ") + ); + assert!(cause.contains("check-1, check-2"), "{cause}"); + assert!(cause.contains(why.as_str()), "{cause}"); + assert!(!ownership::hands_back_without_reason(&cause), "{cause}"); + assert!(!cause.contains("comment"), "{cause}"); + + // Past the cap, a round that made no progress ends the rounds too. + let at_cap = crate::passes::auto_fix_step(MAX_AUTO_FIX_PUSHES, &red, &red, 0, 0.0); + assert!(matches!(at_cap, RoundStep::End { .. }), "{at_cap:?}"); + // And near the spend ceiling, whatever the progress. + let spent = crate::passes::auto_fix_step(1, &checks(1..=3), &red, 0, 190.0); + assert!(matches!(spent, RoundStep::End { .. }), "{spent:?}"); +} + +/// Drives the self-review rounds over the findings each review leaves open. +fn self_rounds(open: &[usize]) -> Vec { + let (mut rounds, mut before, mut stalled) = (0u32, None, 0u32); + let mut steps = Vec::new(); + for &now in open { + if now == 0 { + break; + } + let step = review_pr::self_review_step(rounds, before, now, stalled, 0.0); + steps.push(step.clone()); + let RoundStep::Round { stalled: s, .. } = step else { + break; + }; + rounds += 1; + stalled = s; + before = Some(now); + } + steps +} + +#[test] +fn self_review_rounds_past_the_cap_go_on_while_findings_close() { + // Each review finds one fewer: four rounds, past the cap of two, and the + // fourth review approves. + let steps = self_rounds(&[4, 3, 2, 1, 0]); + assert_eq!(steps.len(), 4); + assert!(steps.iter().all(|s| matches!( + s, + RoundStep::Round { + rung: Rung::Continue, + .. + } + ))); + assert!(steps.len() > own_review::MAX_FIX_ROUNDS as usize); + // The old cap stopped after two with two findings open and asked for a + // comment. + assert_eq!(own_review::MAX_FIX_ROUNDS, 2); + // The ceiling holds even while they close: twice the cap. + let long = self_rounds(&[9, 8, 7, 6, 5, 4, 3]); + assert!(matches!(long.last(), Some(RoundStep::End { why }) if why.contains("twice"))); + assert_eq!( + long.len() as u32, + supervisor::ceiling(own_review::MAX_FIX_ROUNDS) + 1 + ); +} + +#[test] +fn self_review_rounds_without_progress_defer_the_findings_and_finish() { + let steps = self_rounds(&[2, 2, 2, 2]); + assert!(matches!( + steps[1], + RoundStep::Round { + rung: Rung::Narrow, + stalled: 1 + } + )); + let Some(RoundStep::End { why }) = steps.last() else { + panic!("{steps:?}") + }; + let open = vec![ + "Retry loop never backs off (`src/sync.rs:88`)".to_string(), + "Cursor skips tied rows (`src/cursor.rs:12`)".to_string(), + ]; + let body = format!( + "Closes #12\n\n{}\n\n## Summary\nx", + own_review::section(&open) + ); + assert!(own_review::hold(&body).is_some()); + let now = own_review::defer_findings(&body, &open, why); + // Deferred, named with the reason, and no longer holding the draft: the + // ready decision holds it only while required checks are red. + assert!(own_review::hold(&now).is_none(), "{now}"); + assert!(now.contains("## Deferred\n- Retry loop never backs off")); + assert!(now.contains(why.as_str())); + let note = review_pr::self_review_end_note(&open, why); + assert!(note.contains("deferred"), "{note}"); + assert!(note.contains("- Cursor skips tied rows"), "{note}"); + assert!(!ownership::hands_back_without_reason(¬e), "{note}"); + assert!(!note.contains(OLD_CI), "{note}"); +} + +#[test] +fn neither_loop_ends_by_waiting_on_a_comment() { + // The CI-only rounds end through the supervisor's red-CI ending + // (revert to green, else failed with the cause), never by completing + // the run with the checks red. + let fb = include_str!("../feedback.rs"); + let end = fn_src(fb, "\nasync fn end_auto_fix_rounds("); + assert!(end.contains("resume::end_red_ci_rounds(")); + assert!(!end.contains("\"completed\"")); + let gate = fn_src(fb, "\npub async fn run("); + assert!(gate.contains("super::claim_auto_fix_round(")); + assert!(!gate.contains("claim_auto_fix_slot(")); + let rs = include_str!("../resume.rs"); + let red = fn_src(rs, "\npub(crate) async fn end_red_ci_rounds("); + let (revert, fail) = ( + red.find("revert_to_green(").unwrap(), + red.find("super::fail_run(").unwrap(), + ); + assert!(revert < fail); + // The own-review rounds defer what is open and finish. + let fin = fn_src(rs, "\nasync fn finish_on_own_findings("); + assert!(fin.contains("own_review::defer_findings(")); + assert!(fin.contains("wait_for_review(")); + assert!(!rs.contains("stop_on_own_findings(")); + // The self-review rounds too. + let pr = include_str!("../review_pr.rs"); + assert!(pr.contains("SelfRound::End(why) => {")); + let ended = fn_src(pr, "\nasync fn end_self_review_rounds("); + assert!(ended.contains("own_review::defer_findings(")); + assert!(ended.contains("ready::request(")); + // The ready decision defers a finished run's findings once its rounds + // are over, instead of holding them for a person. + let ready = include_str!("../ready.rs"); + assert!(fn_src(ready, "\nasync fn fix_own_findings(").contains("OwnRound::Defer(why)")); + // The words the old endings used are on the hand-off list, so the + // source scan (`ownership`) fails if one comes back. + for p in [ + "naming a change starts", + "stops starting rounds", + "comment to continue", + ] { + assert!(ownership::HAND_OFF_PHRASES.contains(&p), "{p}"); + } +} diff --git a/services/worker/src/passes/incidents/k_own_review_findings.rs b/services/worker/src/passes/incidents/k_own_review_findings.rs index 80cc65f93..c8f649df2 100644 --- a/services/worker/src/passes/incidents/k_own_review_findings.rs +++ b/services/worker/src/passes/incidents/k_own_review_findings.rs @@ -10,10 +10,11 @@ //! optional improvement to correct code) before the PR is marked ready or //! the merge armed. The review lists them at the top of the description and //! requests changes; the run takes them in review-fix rounds; the next -//! review resolves the threads the new commit settled. It goes on while the -//! rounds make progress, for at most two fix rounds; two rounds without -//! progress, or the cap, stop it with the PR still a draft, the findings -//! listed, and the run `needs_input`. A +//! review resolves the threads the new commit settled. It goes on by the +//! supervisor's rule: while the rounds make progress, past the cap of two up +//! to twice it; a round without progress changes approach; when the rounds +//! end, the findings still open are deferred with the reason on the pull +//! request and the run finishes, never waiting on a person. A //! verdict is never APPROVE while a finding holds the merge. use super::fixture::*; @@ -135,7 +136,8 @@ fn the_review_posts_never_approve_with_a_blocker_and_arms_nothing_on_open_findin } #[test] -fn the_run_fixes_them_in_rounds_and_stops_after_two_without_progress() { +fn the_run_fixes_them_in_rounds_and_defers_what_the_rounds_cant_close() { + use crate::passes::supervisor::Rung; let resume = include_str!("../resume.rs"); // A review with open own findings fails the run's review: a fix round // follows, never ready_or_prove. @@ -145,27 +147,36 @@ fn the_run_fixes_them_in_rounds_and_stops_after_two_without_progress() { let mut end = Ending::default(); // Round 1 fixed one of three: progress, another round. assert_eq!( - own_review::next(Some(3), &open, 0, 0, 0), - Next::Fix { stalled: 0 } + own_review::next(Some(3), &open, 0, 0, 0, 0.0), + Next::Fix { + stalled: 0, + rung: Rung::Continue + } ); - // Two rounds in a row with the same two open: stop. + // The same two open: the next round changes approach. assert_eq!( - own_review::next(Some(2), &open, 0, 0, 1), - Next::Fix { stalled: 1 } + own_review::next(Some(2), &open, 0, 0, 1, 0.0), + Next::Fix { + stalled: 1, + rung: Rung::Narrow + } ); - match own_review::next(Some(2), &open, 0, 1, 1) { - Next::Stop(reason) => { - end.status = common::run_status::NEEDS_INPUT.into(); - end.draft = true; - end.said(reason); + // At the cap and still no progress: the findings are deferred on the + // pull request and the run finishes. + match own_review::next(Some(2), &open, 0, 1, own_review::MAX_FIX_ROUNDS, 0.0) { + Next::Finish { why } => { + end.status = common::run_status::COMPLETED.into(); + let body = own_review::defer_findings(&own_review::section(&open), &open, &why); + end.draft = own_review::hold(&body).is_some(); + end.said(own_review::finish_reason(&open, &why)); } other => panic!("{other:?}"), } - assert_eq!(end.status, "needs_input"); - assert!(end.draft); - assert!(end.says("- A (`a.py:1`)")); - assert!(end.says("stays a draft")); + assert_eq!(end.status, "completed"); + assert!(!end.draft); + assert!(end.says("- [ ] A (`a.py:1`)")); + assert!(end.says("deferred")); // Nothing open: ready. - assert_eq!(own_review::next(Some(2), &[], 1, 1, 2), Next::Ready); + assert_eq!(own_review::next(Some(2), &[], 1, 1, 2, 0.0), Next::Ready); end.never_says(OLD); } diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 7cdae5f99..5f29e8034 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -20,6 +20,7 @@ mod aa_promised_round; mod ab_label_prefix; mod ac_partial_and_red_ci; mod ad_hand_back_reply; +mod ae_budget_rounds; mod b_open_pr_retry; mod c_codegen_egress; mod d_echoed_markers; diff --git a/services/worker/src/passes/incidents/p_finished_work_loop.rs b/services/worker/src/passes/incidents/p_finished_work_loop.rs index 989cf55f5..e7c07e7d0 100644 --- a/services/worker/src/passes/incidents/p_finished_work_loop.rs +++ b/services/worker/src/passes/incidents/p_finished_work_loop.rs @@ -317,7 +317,7 @@ fn every_pass_continuation_and_round_goes_through_the_guard() { let cont = fn_of( src, "\nasync fn try_auto_continue(", - "\n/// Hard, signature-INDEPENDENT", + "\npub(crate) const MAX_AUTO_FIX_PUSHES", ); assert!( cont.find("run_guard::on_continuation(").unwrap() < cont.find(".send_message()").unwrap() diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 601f3cfba..ca6885409 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -405,9 +405,10 @@ async fn try_auto_continue( } } -/// Hard, signature-INDEPENDENT ceiling on how many times the automated post-PR -/// loops (CI-fix, review-fix, feedback) may push a fix to a PR before it is -/// handed to a human. This is the backstop for thrash that (a) mutating-error +/// The cap on how many times the automated post-PR loops (CI-fix, +/// review-fix, feedback) push a fix to a PR. Past it, rounds go on only +/// while they make progress, up to twice it (`claim_auto_fix_round`, +/// `supervisor::next_round`); then the run ends with what fails and why. This is the backstop for thrash that (a) mutating-error /// stall detection can't catch (each cycle emits different errors, so the /// signature never repeats) and (b) a dropped resume ("run already running") /// lets bypass the per-cycle counter while the uncapped feedback loop keeps @@ -423,13 +424,24 @@ pub(crate) const MAX_AUTO_FIX_PUSHES: u32 = 8; /// increment are ONE conditional write, so concurrent invocations (feedback is /// unserialized: several webhooks for one run can run at once) can never /// overshoot the cap. Returns true if a slot was claimed (proceed with the fix), -/// false if the budget is spent (hand off to a human). Fails CLOSED: a +/// false if the budget is spent (no round). Fails CLOSED: a /// non-ConditionalCheckFailed error also returns false, because the feedback /// path has NO other cap (no per-cycle counter, no wall-clock) and failing open /// there would resurrect the exact unbounded churn this prevents. A transient -/// DynamoDB blip therefore causes an early, RECOVERABLE hand-off — strictly -/// safer than thrash. +/// DynamoDB blip therefore skips a round — strictly safer than thrash. pub(crate) async fn claim_auto_fix_slot(state: &WorkerState, team_id: &str, run_id: &str) -> bool { + claim_auto_fix_slot_upto(state, team_id, run_id, MAX_AUTO_FIX_PUSHES).await +} + +/// [`claim_auto_fix_slot`] up to `max` pushes: a caller that already +/// decided, by the supervisor's rule, that rounds past the cap make progress +/// claims up to [`supervisor::ceiling`]. +pub(crate) async fn claim_auto_fix_slot_upto( + state: &WorkerState, + team_id: &str, + run_id: &str, + max: u32, +) -> bool { match state .dynamo .update_item() @@ -439,20 +451,145 @@ pub(crate) async fn claim_auto_fix_slot(state: &WorkerState, team_id: &str, run_ .update_expression("ADD auto_fix_pushes :one") .condition_expression("attribute_not_exists(auto_fix_pushes) OR auto_fix_pushes < :max") .expression_attribute_values(":one", attr_n(1)) - .expression_attribute_values(":max", attr_n(u64::from(MAX_AUTO_FIX_PUSHES))) + .expression_attribute_values(":max", attr_n(u64::from(max))) .send() .await { Ok(_) => true, Err(e) => { if !format!("{e:?}").contains("ConditionalCheckFailed") { - warn!(run_id, error = %e, "auto-fix slot claim errored — failing closed (hand off)"); + warn!(run_id, error = %e, "auto-fix slot claim errored — failing closed (no round)"); } false } } } +/// What the supervisor's rule gives a CI fix round outside the run's own CI +/// loop (the CI-only rounds on a finished run's pull request, an E2E +/// failure sent back to the run). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum AutoFix { + /// Take the round, with this rung's approach. + Round(supervisor::Rung), + /// The rounds are over (`supervisor::RoundStep::End`): the run ends with + /// what fails and why. + End(String), + /// Another invocation is taking a round now, or the record couldn't be + /// read: no round from this one, and nothing ends. + Busy, +} + +/// The supervisor's rule for the next CI fix round after the run's own CI +/// loop: `rounds` pushes taken, `before` the checks failing at the last +/// round, `failing` those failing now, `stalled` rounds in a row without +/// progress, `spent` the run's spend. +pub(crate) fn auto_fix_step( + rounds: u32, + before: &[String], + failing: &[String], + stalled: u32, + spent: f64, +) -> supervisor::RoundStep { + supervisor::next_round(&supervisor::RoundFacts { + rounds, + cap: MAX_AUTO_FIX_PUSHES, + progressed: supervisor::ci_progress(before, failing), + stalled, + core: true, + spent_usd: spent, + cap_usd: run_ceiling::MAX_RUN_SPEND_USD, + }) +} + +/// Claims a CI fix round by the supervisor's rule (`supervisor::next_round` +/// over the run's automatic pushes, `MAX_AUTO_FIX_PUSHES` as the cap): +/// rounds go on while checks that were red turn green (`failing` is what +/// fails now, compared with what failed at the last round), up to twice the +/// cap and below the run's spend ceiling, and a round without progress +/// climbs the ladder. The read and the write are one compare-and-set on the +/// push count, so concurrent invocations can't both take the same round. +pub(crate) async fn claim_auto_fix_round( + state: &WorkerState, + team_id: &str, + run_id: &str, + failing: &[String], +) -> AutoFix { + let spent = run_ceiling::load(state, team_id, run_id) + .await + .map(|t| t.spend_usd) + .unwrap_or(0.0); + for _ in 0..2 { + let item = match 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("auto_fix_pushes, auto_fix_failing, auto_fix_stalled") + .consistent_read(true) + .send() + .await + { + Ok(o) => o.item.unwrap_or_default(), + Err(e) => { + warn!(run_id, error = %e, "Could not read the run's fix rounds — no round now"); + return AutoFix::Busy; + } + }; + let n = |k: &str| { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse::().ok()) + .unwrap_or(0) + }; + let rounds = n("auto_fix_pushes"); + let before: Vec = item + .get("auto_fix_failing") + .and_then(|v| v.as_s().ok()) + .and_then(|s| serde_json::from_str(s).ok()) + .unwrap_or_default(); + let step = auto_fix_step(rounds, &before, failing, n("auto_fix_stalled"), spent); + let (rung, stalled) = match step { + supervisor::RoundStep::End { why } => return AutoFix::End(why), + supervisor::RoundStep::Round { rung, stalled } => (rung, stalled), + }; + let seen = if rounds == 0 { + "(attribute_not_exists(auto_fix_pushes) OR auto_fix_pushes = :seen)" + } else { + "auto_fix_pushes = :seen" + }; + let wrote = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET auto_fix_failing = :f, auto_fix_stalled = :s ADD auto_fix_pushes :one", + ) + .condition_expression(seen) + .expression_attribute_values( + ":f", + attr_s(&serde_json::to_string(failing).unwrap_or_default()), + ) + .expression_attribute_values(":s", attr_n(u64::from(stalled))) + .expression_attribute_values(":one", attr_n(1)) + .expression_attribute_values(":seen", attr_n(u64::from(rounds))) + .send() + .await; + match wrote { + Ok(_) => return AutoFix::Round(rung), + Err(e) if format!("{e:?}").contains("ConditionalCheckFailed") => continue, + Err(e) => { + warn!(run_id, error = %e, "Could not claim a fix round — no round now"); + return AutoFix::Busy; + } + } + } + AutoFix::Busy +} + /// TTL for the per-run WRITER slot, in seconds. Slightly past the 960s /// stale-run reset so a crashed holder never blocks a post-reset retry for /// more than ~1 minute after the reset fires. diff --git a/services/worker/src/passes/own_review.rs b/services/worker/src/passes/own_review.rs index 702ff0664..97598c4c2 100644 --- a/services/worker/src/passes/own_review.rs +++ b/services/worker/src/passes/own_review.rs @@ -16,20 +16,23 @@ //! - The run takes them in a review-fix round (`run_fix_round`), pushes, //! and the next review of the new head resolves the threads the commit //! settled and rewrites the section, or removes it when nothing is left. -//! - It goes on while the rounds make progress (fewer open findings, or a -//! round that pushed changes), for at most [`MAX_FIX_ROUNDS`] rounds. Two -//! rounds in a row without progress, or the cap, stop it ([`next`]): the -//! findings stay listed, the PR stays a draft, and the run waits on a -//! person (`needs_input`). Uncapped, two runs spent $29 in 17 rounds -//! where the count of open findings went down by one and back up. +//! - It goes on by the supervisor's rule ([`next`], +//! `supervisor::next_round`): while the rounds make progress (fewer open +//! findings, or a round that pushed changes) up to twice +//! [`MAX_FIX_ROUNDS`] and below the run's spend ceiling. A round without +//! progress changes approach (one finding only, a fresh context with +//! small edits, a re-split, the strongest model). When the rounds end, the +//! findings still open are deferred with the reason ([`defer_findings`]): +//! they move from "Open review findings" to "Deferred" on the pull +//! request, the run finishes, and the draft is held only while required +//! checks are red. Uncapped, two runs once spent $29 in 17 rounds where +//! the count of open findings went down by one and back up; the ceiling +//! and the progress rule keep that bound, and nothing waits on a person. //! - A finished run's PR held on its findings never waits on a round //! nothing queued. The ready decision queues one review-fix round for //! them, once per head, while the run has rounds left ([`round_left`]), -//! and waits for it; with none left, or once a round ran on the head and -//! the findings are still there, the hold names what a person does -//! ([`person_todo`]) and promises no CoderHelm work. A PR once stayed a -//! draft for days on "CoderHelm fixes them in its review rounds" after its -//! run had spent its fix budget. +//! and waits for it; when the run's rounds are over ([`rounds_over`]) the +//! findings are deferred the same way instead of held for a person. //! - Each round is told what the rounds before it found and looked up //! ([`round_note`], [`fix_feedback`]), so it doesn't repeat the same //! database and live-data lookups from scratch. @@ -37,7 +40,6 @@ //! People's PRs are unchanged: the findings are posted for the author. use super::review_agent::{Evidence, Finding}; -use super::steps; pub const START: &str = ""; pub const END: &str = ""; @@ -159,10 +161,10 @@ pub fn fixing_why(n: usize) -> String { #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RoundBudget { pub status: String, - /// The run guard stopped the run: a person has it. + /// The run guard stopped the run. pub guard_open: bool, - /// The run itself stopped its rounds and handed the findings to a - /// person (`own_review_handed`). + /// The run's own rounds on its findings ended and deferred what was + /// left (`own_review_handed`). pub handed: bool, /// Fix rounds taken on the own review's findings. pub rounds: u32, @@ -172,11 +174,43 @@ pub struct RoundBudget { pub cycles: usize, /// The head a round was last queued for (`own_fix_head`). pub queued_head: String, + /// Findings open at the run's last review (`own_review_open`). + pub open_before: Option, + /// Findings open now, when the caller knows them: fewer than + /// `open_before` is progress, which earns rounds past the caps. + pub open_now: Option, +} + +/// Whether the run's rounds on its findings are over, by the supervisor's +/// rule: `Some(why)` when they are (the run ended them, or the caps are +/// reached without progress, or the ceilings are), and what is open is then +/// deferred with that reason. +pub fn rounds_over(b: &RoundBudget, max_pushes: u32, max_cycles: usize) -> Option { + use super::supervisor::{ceiling, may_extend}; + if b.handed { + return Some("the run's fix rounds on its own review's findings ended".into()); + } + let progressed = matches!((b.open_before, b.open_now), (Some(was), Some(now)) if now < was); + if !may_extend(b.rounds, MAX_FIX_ROUNDS, progressed) { + return Some(format!( + "the run took its fix rounds on its own review's findings ({} while they made \ + progress, up to {})", + b.rounds, + ceiling(MAX_FIX_ROUNDS) + )); + } + let cycles = u32::try_from(b.cycles).unwrap_or(u32::MAX); + let max_cycles = u32::try_from(max_cycles).unwrap_or(u32::MAX); + if !may_extend(b.pushes, max_pushes, progressed) || !may_extend(cycles, max_cycles, progressed) + { + return Some("the run's automatic fix budget is spent".into()); + } + None } /// Whether a fix round may be queued now for the findings on `head`: /// `Err` names why not, for the log. The round counts against the same -/// budgets the run's own rounds draw on. +/// budgets the run's own rounds draw on ([`rounds_over`]). pub fn round_left( b: &RoundBudget, head: &str, @@ -193,16 +227,8 @@ pub fn round_left( if b.guard_open { return Err("the run guard stopped the run".into()); } - if b.handed { - return Err("the run stopped its rounds and handed the findings to a person".into()); - } - if b.rounds >= MAX_FIX_ROUNDS { - return Err(format!( - "the run took its {MAX_FIX_ROUNDS} fix rounds on its own review's findings" - )); - } - if b.pushes >= max_pushes || b.cycles >= max_cycles { - return Err("the run's automatic fix budget is spent".into()); + if let Some(why) = rounds_over(b, max_pushes, max_cycles) { + return Err(why); } if b.queued_head == head { return Err("a fix round already ran on this head".into()); @@ -210,8 +236,9 @@ pub fn round_left( Ok(()) } -/// Fix rounds a run takes on its own review's findings before it hands the -/// PR to a person with the findings still listed. +/// The cap on fix rounds a run takes on its own review's findings. Past it, +/// rounds go on only while they make progress, up to twice it +/// (`supervisor::next_round`); then what is open is deferred. pub const MAX_FIX_ROUNDS: u32 = 2; /// What follows a review of CoderHelm's own PR. @@ -219,66 +246,95 @@ pub const MAX_FIX_ROUNDS: u32 = 2; pub enum Next { /// Nothing is open: the PR may be marked ready and the merge armed. Ready, - /// Another fix round, with this many rounds without progress before it. - Fix { stalled: u32 }, - /// Two rounds in a row made no progress, or [`MAX_FIX_ROUNDS`] rounds - /// ran: the run stops, the findings stay listed and the PR stays a - /// draft. - Stop(String), + /// Another fix round, with this many rounds without progress before it + /// and the ladder's approach for it. + Fix { + stalled: u32, + rung: super::supervisor::Rung, + }, + /// The rounds are over: what is open is deferred with this reason + /// ([`finish_reason`], [`defer_findings`]) and the run finishes. + Finish { why: String }, +} + +/// Whether what is left is core work: a finding in a readme or the docs is +/// not, and is deferred first when rounds stall. +fn core_left(items: &[String]) -> bool { + items.iter().any(|i| { + let path = i + .rsplit_once("(`") + .map(|(_, p)| p.trim_end_matches(')').trim_end_matches('`')) + .unwrap_or(""); + let path = path.split(':').next().unwrap_or(path); + super::supervisor::is_core(path, i, false) + }) } -/// What follows. `before`: the findings open at the previous review of -/// this run (`None` at the first); `after`: those open now; -/// `pushed_files`: what the last fix round changed; `stalled`: rounds -/// without progress so far; `rounds`: fix rounds this run already took. +/// What follows, by the supervisor's rule (`supervisor::next_round`). +/// `before`: the findings open at the previous review of this run (`None` +/// at the first); `after`: those open now; `pushed_files`: what the last fix +/// round changed; `stalled`: rounds without progress so far; `rounds`: fix +/// rounds this run already took; `spent_usd`: the run's spend. pub fn next( before: Option, after: &[String], pushed_files: usize, stalled: u32, rounds: u32, + spent_usd: f64, ) -> Next { + use super::supervisor::{findings_progress, next_round, RoundFacts, RoundStep}; if after.is_empty() { return Next::Ready; } - let progress = before.is_none_or(|b| after.len() < b) || pushed_files > 0; - // A round that fixed something earns another past the cap, up to twice - // it (`supervisor::may_extend`): the budget follows progress. - if !super::supervisor::may_extend(rounds, MAX_FIX_ROUNDS, progress) { - return Next::Stop(cap_reason(after)); - } - if progress { - return Next::Fix { stalled: 0 }; - } - let stalled = stalled.saturating_add(1); - if steps::stops_for_stall(stalled) { - return Next::Stop(stop_reason(after)); + match next_round(&RoundFacts { + rounds, + cap: MAX_FIX_ROUNDS, + progressed: findings_progress(before, after.len(), pushed_files), + stalled, + core: core_left(after), + spent_usd, + cap_usd: super::run_ceiling::MAX_RUN_SPEND_USD, + }) { + RoundStep::Round { rung, stalled } => Next::Fix { stalled, rung }, + RoundStep::End { why } => Next::Finish { why }, } - Next::Fix { stalled } } -/// Why the fix rounds stopped, with the findings still open. -pub fn stop_reason(items: &[String]) -> String { - let list: Vec = items.iter().map(|i| format!("- {i}")).collect(); +/// What the run says when its rounds on its own findings end: what is +/// deferred and why, and that the run finishes. +pub fn finish_reason(items: &[String], why: &str) -> String { + let list: Vec = items.iter().map(|i| format!("- [ ] {i}")).collect(); format!( - "Stopped: {} fix rounds in a row didn't fix any of CoderHelm's own review findings. \ - Still open:\n{}\nThe pull request stays a draft with these listed under \"Open review \ - findings\".", - steps::MAX_STALLED_STEPS, + "CoderHelm's fix rounds on its own review's findings ended ({why}). These are deferred, \ + listed under \"Deferred\" on the pull request with that reason, and the run finishes:\n{}", list.join("\n") ) } -/// Why the fix rounds stopped at the cap, with the findings still open. -pub fn cap_reason(items: &[String]) -> String { - let list: Vec = items.iter().map(|i| format!("- [ ] {i}")).collect(); - format!( - "CoderHelm took its fix rounds on its own review's findings (up to {} while they made \ - progress) and these are still open, deferred and listed under \"Open review findings\" \ - on the pull request:\n{}", - MAX_FIX_ROUNDS * 2, - list.join("\n") - ) +/// The description with the open findings deferred: the "Open review +/// findings" section (which holds the draft) removed, and each finding +/// listed under "Deferred" with `why`. Unchanged when nothing is listed. +pub fn defer_findings(body: &str, items: &[String], why: &str) -> String { + if items.is_empty() { + return body.to_string(); + } + let mut rest = body.to_string(); + if let (Some(a), Some(b)) = (rest.find(START), rest.find(END)) { + if b > a { + rest.replace_range(a..b + END.len(), ""); + } + } + let rest = rest.trim().replace("\n\n\n", "\n\n"); + let lines: Vec = items + .iter() + .map(|i| format!("- {i}: deferred from CoderHelm's own review ({why})")) + .collect(); + if rest.contains("## Deferred") { + format!("{}\n{}", rest.trim_end(), lines.join("\n")) + } else { + format!("{}\n\n## Deferred\n{}", rest.trim_end(), lines.join("\n")) + } } /// What a fix round is told: every open finding, fixed now, and what the @@ -413,17 +469,29 @@ mod tests { } #[test] - fn rounds_go_on_while_they_make_progress_and_stop_after_two_without() { - let two = vec!["a".to_string(), "b".to_string()]; - assert_eq!(next(Some(2), &[], 0, 1, 1), Next::Ready); - assert_eq!(next(None, &two, 0, 0, 0), Next::Fix { stalled: 0 }); - assert_eq!(next(Some(3), &two, 0, 1, 1), Next::Fix { stalled: 0 }); - assert_eq!(next(Some(2), &two, 4, 1, 1), Next::Fix { stalled: 0 }); - assert_eq!(next(Some(2), &two, 0, 0, 1), Next::Fix { stalled: 1 }); - match next(Some(2), &two, 0, 1, 1) { - Next::Stop(why) => { - assert!(why.contains("- a\n- b")); - assert!(why.contains("stays a draft")); + fn rounds_go_on_while_they_make_progress_and_change_approach_without() { + use super::super::supervisor::Rung; + let two = vec![ + "a (`src/a.rs:1`)".to_string(), + "b (`src/b.rs:2`)".to_string(), + ]; + let fix = |stalled, rung| Next::Fix { stalled, rung }; + assert_eq!(next(Some(2), &[], 0, 1, 1, 0.0), Next::Ready); + assert_eq!(next(None, &two, 0, 0, 0, 0.0), fix(0, Rung::Continue)); + assert_eq!(next(Some(3), &two, 0, 1, 1, 0.0), fix(0, Rung::Continue)); + assert_eq!(next(Some(2), &two, 4, 1, 1, 0.0), fix(0, Rung::Continue)); + // Under the cap a round without progress changes approach, never + // stops: one finding only, then a fresh context with small edits. + assert_eq!(next(Some(2), &two, 0, 0, 1, 0.0), fix(1, Rung::Narrow)); + assert_eq!(next(Some(2), &two, 0, 1, 1, 0.0), fix(2, Rung::SwitchTools)); + // At the cap without progress the rounds end: deferred, never a wait. + match next(Some(2), &two, 0, 1, MAX_FIX_ROUNDS, 0.0) { + Next::Finish { why } => { + let said = finish_reason(&two, &why); + assert!(said.contains("- [ ] a (`src/a.rs:1`)\n- [ ] b (`src/b.rs:2`)")); + assert!(said.contains("deferred")); + assert!(said.contains("the run finishes")); + assert!(!said.contains("stays a draft")); } other => panic!("{other:?}"), } @@ -431,28 +499,96 @@ mod tests { #[test] fn rounds_go_on_past_the_cap_while_they_fix_things_then_defer_the_rest() { + use super::super::supervisor::Rung; let open = vec!["a (`x.rs:1`)".to_string(), "b (`y.rs:2`)".to_string()]; - assert_eq!(next(Some(3), &open, 2, 0, 1), Next::Fix { stalled: 0 }); + let go = Next::Fix { + stalled: 0, + rung: Rung::Continue, + }; + assert_eq!(next(Some(3), &open, 2, 0, 1, 0.0), go); // At the cap, a round that fixed something earns another // (`supervisor::may_extend`), up to twice the cap. - assert_eq!( - next(Some(3), &open, 2, 0, MAX_FIX_ROUNDS), - Next::Fix { stalled: 0 } - ); + assert_eq!(next(Some(3), &open, 2, 0, MAX_FIX_ROUNDS, 0.0), go); + assert_eq!(next(Some(3), &open, 0, 0, MAX_FIX_ROUNDS * 2 - 1, 0.0), go); assert!(matches!( - next(Some(2), &open, 0, 0, MAX_FIX_ROUNDS), - Next::Stop(_) + next(Some(2), &open, 0, 0, MAX_FIX_ROUNDS, 0.0), + Next::Finish { .. } )); - match next(Some(3), &open, 2, 0, MAX_FIX_ROUNDS * 2) { - Next::Stop(why) => { - assert!(why.contains("- [ ] a (`x.rs:1`)\n- [ ] b (`y.rs:2`)")); - assert!(why.contains("deferred")); - assert!(!why.contains("Handed to a person")); - } + match next(Some(3), &open, 2, 0, MAX_FIX_ROUNDS * 2, 0.0) { + Next::Finish { why } => assert!(why.contains("twice"), "{why}"), + other => panic!("{other:?}"), + } + // Near the spend ceiling the rounds end too, progress or not. + match next(Some(3), &open, 2, 0, 0, 190.0) { + Next::Finish { why } => assert!(why.contains("spend ceiling"), "{why}"), other => panic!("{other:?}"), } // Nothing open is ready whatever the count. - assert_eq!(next(Some(1), &[], 0, 0, 9), Next::Ready); + assert_eq!(next(Some(1), &[], 0, 0, 9, 0.0), Next::Ready); + } + + #[test] + fn deferred_findings_leave_the_hold_and_are_listed_with_why() { + let items = vec!["A (`a.rs:1`)".to_string(), "B (`README.md`)".to_string()]; + let body = format!("Closes #4\n\n{}\n\n## Summary\nx", section(&items)); + assert!(hold(&body).is_some()); + let now = defer_findings(&body, &items, "the rounds stopped closing findings"); + assert!(hold(&now).is_none(), "{now}"); + assert!(listed(&now).is_empty()); + assert!(now.contains("## Summary\nx")); + assert!(now.contains( + "## Deferred\n- A (`a.rs:1`): deferred from CoderHelm's own review (the rounds \ + stopped closing findings)" + )); + // An existing "Deferred" section gets the lines added. + let again = defer_findings("x\n\n## Deferred\n- t: why", &items[..1], "w"); + assert_eq!(again.matches("## Deferred").count(), 1); + assert!(again.ends_with("- A (`a.rs:1`): deferred from CoderHelm's own review (w)")); + assert_eq!(defer_findings("x", &[], "w"), "x"); + } + + #[test] + fn a_finished_runs_rounds_are_over_by_the_same_rule() { + let base = RoundBudget { + status: "completed".into(), + ..Default::default() + }; + assert_eq!(rounds_over(&base, 8, 10), None); + let at_cap = RoundBudget { + rounds: MAX_FIX_ROUNDS, + open_before: Some(3), + ..base.clone() + }; + // At the cap without progress known: over. + assert!(rounds_over(&at_cap, 8, 10).is_some()); + // At the cap with fewer open than at the last review: one more. + let closing = RoundBudget { + open_now: Some(2), + ..at_cap.clone() + }; + assert_eq!(rounds_over(&closing, 8, 10), None); + assert_eq!(round_left(&closing, "h", 8, 10), Ok(())); + // The ceiling holds whatever the progress. + let ceiling = RoundBudget { + rounds: MAX_FIX_ROUNDS * 2, + ..closing.clone() + }; + assert!(rounds_over(&ceiling, 8, 10).is_some()); + // Pushes past their cap only while progressing, up to twice it. + let pushes = RoundBudget { + pushes: 9, + ..closing.clone() + }; + assert_eq!(rounds_over(&pushes, 8, 10), None); + assert!(rounds_over( + &RoundBudget { + pushes: 16, + ..closing + }, + 8, + 10 + ) + .is_some()); } #[test] diff --git a/services/worker/src/passes/ownership.rs b/services/worker/src/passes/ownership.rs index 19433d62c..50a444f00 100644 --- a/services/worker/src/passes/ownership.rs +++ b/services/worker/src/passes/ownership.rs @@ -77,6 +77,17 @@ pub const HAND_OFF_PHRASES: &[&str] = &[ "best effort attempt", "if you can't, say so and stop", "if you cannot, say so and stop", + // A loop of fix rounds that stops on its own budget and waits for a + // person's comment to go on (the CI-only feedback rounds, the + // self-review rounds, the E2E rounds did): the supervisor's rule ends + // them instead, deferred with the reason or failed with the cause. + "comment to continue", + "comment naming a change", + "naming a change starts", + "starts the next round right away", + "starts the next one right away", + "stop starting rounds", + "stops starting rounds", ]; /// How a model's reply gives the work up, besides [`HAND_OFF_PHRASES`]. diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index 1c0205f7a..f4e72053b 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -1120,7 +1120,9 @@ pub fn wants_own_round(f: &Facts) -> bool { /// CoderHelm's own open review findings hold the draft: a review-fix round /// is queued for them while the run has rounds left (once per head), and -/// the decision waits for it. Otherwise they are a person's to deal with. +/// the decision waits for it. When the run's rounds are over by the +/// supervisor's rule, they are deferred on the pull request with the reason +/// and hold nothing. async fn fix_own_findings(ctx: &Ctx<'_>, run_id: &str, f: &mut Facts) { if !wants_own_round(f) { return; @@ -1138,7 +1140,33 @@ async fn fix_own_findings(ctx: &Ctx<'_>, run_id: &str, f: &mut Facts) { { super::resume::OwnRound::Fixing => f.own_fixing = true, super::resume::OwnRound::Person(why) => { - info!(pr = ctx.pr, run_id, why = %why, "No fix round for the own review's findings: a person has them"); + info!(pr = ctx.pr, run_id, why = %why, "No fix round for the own review's findings now"); + } + super::resume::OwnRound::Defer(why) => { + // The run's rounds on them are over (the supervisor's rule): they + // are deferred on the pull request with the reason and hold + // nothing, so the draft waits only on what else holds it. + let body = super::own_review::defer_findings(&f.body, &items, &why); + match ctx + .github + .update_pr_body(ctx.owner, ctx.repo, ctx.pr, &body) + .await + { + Ok(_) => { + info!(pr = ctx.pr, run_id, why = %why, "The run's rounds on its own review's findings are over: deferred"); + super::add_progress_note( + ctx.state, + ctx.team_id, + run_id, + &super::own_review::finish_reason(&items, &why), + ) + .await; + f.body = body; + } + Err(e) => { + warn!(pr = ctx.pr, run_id, error = %e, "Could not defer the own review's findings on the pull request") + } + } } } } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index a6998396d..de43623d8 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3039,24 +3039,32 @@ pub async fn run( ) .await?; } else { - // Own review findings: another round while the rounds make - // progress; two rounds in a row without it stop the run with the - // PR still a draft and the findings listed at its top. + // Own review findings, by the supervisor's rule: another round + // while the rounds make progress (up to twice the cap), a round + // without progress changes approach, and when the rounds end + // what is open is deferred and the run finishes. if !own_open.is_empty() { let progress = own_review_progress(&run_record); + let spent = super::run_ceiling::load(state, &msg.team_id, &msg.run_id) + .await + .map(|t| t.spend_usd) + .unwrap_or(0.0); match super::own_review::next( progress.open_before, &own_open, 0, progress.stalled, progress.rounds, + spent, ) { - super::own_review::Next::Stop(reason) => { - stop_on_own_findings( + super::own_review::Next::Finish { why } => { + finish_on_own_findings( state, &ticket_msg, + &github, &msg.run_id, - &reason, + &own_open, + &why, &pr_url, pr_number, &branch, @@ -3067,41 +3075,7 @@ pub async fn run( mark_events_processed(state, &msg.run_id, &events).await; return Ok(()); } - super::own_review::Next::Fix { .. } - if progress.rounds > 0 - && super::stop_judge::cycle_licence( - state, - &ticket_msg, - &msg.run_id, - "own_review", - progress.rounds, - super::own_review::MAX_FIX_ROUNDS, - &super::stop_judge::evidence_lines( - "CoderHelm's own review", - &own_open, - ), - ) - .await - .is_none() => - { - // The stop judge found no named blocker worth another - // round: the draft goes to a person with what is open. - stop_on_own_findings( - state, - &ticket_msg, - &msg.run_id, - &super::own_review::cap_reason(&own_open), - &pr_url, - pr_number, - &branch, - &usage, - wall_clock_secs(created_at, &start), - ) - .await?; - mark_events_processed(state, &msg.run_id, &events).await; - return Ok(()); - } - super::own_review::Next::Fix { stalled } => { + super::own_review::Next::Fix { stalled, rung } => { record_own_review_progress( state, &msg.team_id, @@ -3111,6 +3085,15 @@ pub async fn run( progress.rounds.saturating_add(1), ) .await; + review_result + .summary + .push_str(&super::supervisor::round_instruction( + rung, + &format!( + "CoderHelm's own review findings ({})", + own_open.join("; ") + ), + )); } super::own_review::Next::Ready => {} } @@ -3145,13 +3128,15 @@ pub async fn run( ) .await; if !own_open.is_empty() { - // Never hand over a PR with its own review's findings - // open as if it were ready: it stays a draft, listed. - stop_on_own_findings( + // The fix budget ended the rounds: what is open is + // deferred with that reason and the run finishes. + finish_on_own_findings( state, &ticket_msg, + &github, &msg.run_id, - &super::own_review::stop_reason(&own_open), + &own_open, + "the run's automatic fix budget is spent", &pr_url, pr_number, &branch, @@ -3615,7 +3600,12 @@ async fn run_fix_round( &ctx.rules, &ctx.repo_instructions, Some(&feedback), - "medium", + // A round on the ladder's escalate rung takes the strongest model. + if round.feedback.contains(super::supervisor::ESCALATED) { + "complex" + } else { + "medium" + }, &ctx.provider, &mut ctx.usage, &FileCache::default(), @@ -5202,8 +5192,12 @@ async fn record_own_round_note( pub(crate) enum OwnRound { /// A review-fix round for them is queued or running on this head. Fixing, - /// No round will run: a person deals with them. Why, for the log. + /// No round runs now (the run isn't finished, a round already ran on + /// this head, the record couldn't be read). Why, for the log. Person(String), + /// The run's rounds on them are over (`own_review::rounds_over`): they + /// are deferred with this reason and hold nothing. + Defer(String), } /// The record fields that say what a finished run has left for a round on @@ -5232,6 +5226,11 @@ pub(crate) fn own_round_budget( pushes: n("auto_fix_pushes"), cycles, queued_head: s(OWN_FIX_HEAD), + open_before: item + .get("own_review_open") + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse::().ok()), + open_now: None, } } @@ -5306,10 +5305,25 @@ pub(crate) async fn queue_own_review_round( return OwnRound::Fixing; } let cycles = load_cycle_from_checkpoint(state, team_id, run_id).await; - let budget = own_round_budget(&item, cycles); + let mut budget = own_round_budget(&item, cycles); + budget.open_now = Some(items.len()); if let Err(why) = super::own_review::round_left(&budget, head, super::MAX_AUTO_FIX_PUSHES, MAX_CI_FIX_CYCLES) { + // The rounds are over by the supervisor's rule: the findings are + // deferred, never held for a person. + let finished = common::run_status::COMPLETED == status + || common::run_status::SUCCESS == status + || common::run_status::NEEDS_INPUT == status; + if finished && !budget.guard_open { + if let Some(over) = super::own_review::rounds_over( + &budget, + super::MAX_AUTO_FIX_PUSHES, + MAX_CI_FIX_CYCLES, + ) { + return OwnRound::Defer(over); + } + } return OwnRound::Person(why); } let Some((ticket, branch)) = super::recheck::message_of(&item) else { @@ -5348,8 +5362,18 @@ pub(crate) async fn queue_own_review_round( .expression_attribute_values(":h", attr_s(head)) .expression_attribute_values(":zero", attr_n(0)) .expression_attribute_values(":one", attr_n(1)) - .expression_attribute_values(":maxr", attr_n(super::own_review::MAX_FIX_ROUNDS)) - .expression_attribute_values(":maxp", attr_n(super::MAX_AUTO_FIX_PUSHES)) + // `round_left` decided by the supervisor's rule; the claim keeps the + // ceilings (twice each cap) so two deciders can't overshoot them. + .expression_attribute_values( + ":maxr", + attr_n(super::supervisor::ceiling( + super::own_review::MAX_FIX_ROUNDS, + )), + ) + .expression_attribute_values( + ":maxp", + attr_n(super::supervisor::ceiling(super::MAX_AUTO_FIX_PUSHES)), + ) .expression_attribute_values(":t", attr_s(&now)) .send() .await; @@ -5383,7 +5407,14 @@ pub(crate) async fn queue_own_review_round( warn!(run_id, why = %why, "The fix round for the own review's findings couldn't be queued"); OwnRound::Person(why) }; - if !super::claim_auto_fix_slot(state, team_id, run_id).await { + if !super::claim_auto_fix_slot_upto( + state, + team_id, + run_id, + super::supervisor::ceiling(super::MAX_AUTO_FIX_PUSHES), + ) + .await + { return give_back("the run's automatic fix budget is spent".into()).await; } let base_sha = @@ -5428,10 +5459,10 @@ pub(crate) async fn queue_own_review_round( team_id, run_id, &format!( - "{}: a review fix round takes them (round {} of {}).", + "{}: a review fix round takes them (round {}; up to {} while rounds make progress).", super::own_review::fixing_why(items.len()), budget.rounds + 1, - super::own_review::MAX_FIX_ROUNDS + super::supervisor::ceiling(super::own_review::MAX_FIX_ROUNDS) ), ) .await; @@ -5444,15 +5475,23 @@ pub(crate) async fn queue_own_review_round( OwnRound::Fixing } -/// The run stops with its own review's findings still open: it says which -/// and why, waits on a person (`needs_input`, never `completed`), and the PR -/// stays a draft with them listed at its top. +/// The run's rounds on its own review's findings ended (by the +/// supervisor's rule, `own_review::next`, or the fix budget): what is open +/// is deferred with the reason, moved from "Open review findings" (which +/// holds the draft) to "Deferred" on the pull request +/// (`own_review::defer_findings`). The ready decision then holds the draft +/// only while required checks are red, and the run finishes through the +/// supervisor's ending (`wait_on_person`: completed with what is deferred, +/// or failed with what fails while its checks are red). It waits on a +/// person only for a need on the human-only list. #[allow(clippy::too_many_arguments)] -async fn stop_on_own_findings( +async fn finish_on_own_findings( state: &WorkerState, msg: &TicketMessage, + github: &GitHubClient, run_id: &str, - reason: &str, + open: &[String], + why: &str, pr_url: &str, pr_number: u64, branch: &str, @@ -5461,10 +5500,12 @@ async fn stop_on_own_findings( ) -> Result<(), Box> { warn!( run_id, - pr_number, "Own review findings still open — the PR stays a draft" + pr_number, + open = open.len(), + "Own review rounds ended — the findings left are deferred and the run finishes" ); // The run's rounds on them are over: the ready decision never queues - // another one, and its hold names what a person does. + // another one. if let Err(e) = state .dynamo .update_item() @@ -5477,11 +5518,43 @@ async fn stop_on_own_findings( .send() .await { - warn!(run_id, error = %e, "Could not record that the own review's rounds stopped"); + warn!(run_id, error = %e, "Could not record that the own review's rounds ended"); + } + let reason = super::own_review::finish_reason(open, why); + match github + .get_pull_request(&msg.repo_owner, &msg.repo_name, pr_number) + .await + { + Ok(p) => { + let body = p["body"].as_str().unwrap_or(""); + let now = super::own_review::defer_findings(body, open, why); + if now != body { + if let Err(e) = github + .update_pr_body(&msg.repo_owner, &msg.repo_name, pr_number, &now) + .await + { + warn!(run_id, error = %e, "Could not list the deferred findings on the pull request"); + } + } + } + Err(e) => { + warn!(run_id, error = %e, "Could not read the pull request to defer the findings") + } } - super::add_progress_note(state, &msg.team_id, run_id, reason).await; + super::add_progress_note(state, &msg.team_id, run_id, &reason).await; + // The one ready decision: with the findings deferred, only red + // required checks hold the draft. + mark_pr_ready( + state, + &msg.team_id, + github, + &msg.repo_owner, + &msg.repo_name, + pr_number, + ) + .await; wait_for_review( - state, msg, run_id, reason, pr_url, pr_number, branch, usage, duration, + state, msg, run_id, &reason, pr_url, pr_number, branch, usage, duration, ) .await } @@ -5586,6 +5659,100 @@ async fn hand_off_red_ci( .await } +/// The CI fix rounds outside the run's own CI loop (the CI-only rounds on a +/// finished run's pull request) ended by the supervisor's rule with checks +/// still red: the supervisor's ending, as [`hand_off_red_ci`] has it. What +/// broke the checks comes out first ([`revert_to_green`]), deferred and +/// named on the pull request, and the run waits for CI on the result like +/// any finished run. When nothing can come out the run ends failed, with +/// the failing checks, the error and what was tried on the pull request +/// and as the run's cause (`supervisor::end_of_rounds`); the pull request +/// stays a draft while the checks are red. Never a wait on a person. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn end_red_ci_rounds( + state: &WorkerState, + ticket_msg: &TicketMessage, + run_id: &str, + github: &GitHubClient, + (branch, number, url): (&str, u64, &str), + usage: &TokenUsage, + duration: u64, + checks: &[String], + excerpt: &str, + tried: &[String], +) -> Result<(), Box> { + let msg = ResumeMessage { + team_id: ticket_msg.team_id.clone(), + run_id: run_id.to_string(), + installation_id: ticket_msg.installation_id, + ..Default::default() + }; + let pr = PrRef { + owner: &ticket_msg.repo_owner, + repo: &ticket_msg.repo_name, + branch, + number, + url, + }; + if let Some(note) = revert_to_green(state, &msg, ticket_msg, github, &pr, excerpt).await { + super::add_progress_note(state, &msg.team_id, run_id, ¬e).await; + set_run_awaiting_ci( + state, ticket_msg, run_id, url, number, branch, usage, duration, + ) + .await?; + return Ok(()); + } + super::record_ci_outcome( + state, + &msg.team_id, + run_id, + super::CiOutcome::HandedOff(super::GaveUp::NoProgress), + ) + .await; + let failing = if checks.is_empty() { + vec!["the repository's CI".to_string()] + } else { + checks.to_vec() + }; + let ending = super::supervisor::end_of_rounds(&[], &tried.join("; "), &failing); + let section = ci_failing_section( + checks, + excerpt, + tried, + "Nothing on this branch can come out to make these checks pass, so the run ended \ + failed with this cause; the pull request stays a draft while they fail.", + ); + match github.get_pull_request(pr.owner, pr.repo, number).await { + Ok(p) => { + let body = with_ci_failing(p["body"].as_str().unwrap_or(""), §ion); + if let Err(e) = github + .update_pr_body(pr.owner, pr.repo, number, &body) + .await + { + warn!(run_id, error = %e, "Could not write what fails on the pull request"); + } + } + Err(e) => warn!(run_id, error = %e, "Could not read the pull request to say what fails"), + } + // The one ready decision: a failing check holds the draft, named. + mark_pr_ready(state, &msg.team_id, github, pr.owner, pr.repo, number).await; + let reason = format!( + "{}. {}", + ci_failing_reason(checks, excerpt, tried.len()), + tried.join("; ") + ); + if ending != super::supervisor::Ending::Failed { + error!( + run_id, + ?ending, + "Red checks after the rounds must end the run failed" + ); + } + warn!(run_id, reason = %reason, "CI stays red after the fix rounds and nothing can come out: the run failed"); + super::fail_run(state, ticket_msg, run_id, &reason, usage, duration).await; + Ok(()) +} + /// What a revert writes (each path with its content, or `None` to remove /// it), the tasks it defers with why, and the note to record. type Reverted = (Vec<(String, Option)>, Vec<(String, String)>, String); diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 868767605..611a4e5fe 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -4101,45 +4101,42 @@ async fn run_once( pr = msg.pr_number, "Self-review flipped from APPROVE to REQUEST_CHANGES — not re-fixing on a flip (hysteresis)" ); - } else if claim_self_review_round( - state, - &msg.team_id, - &msg.repo_owner, - &msg.repo_name, - msg.pr_number, - ) - .await - { - // Under the cap — apply the fixes. A new commit re-triggers the review. - feed_review_back_to_run(state, &msg, &record_body).await; - } else if claim_once( - state, - &msg.team_id, - &format!( - "SELFREVIEWHANDOFF#{}/{}#{:0>6}", - msg.repo_owner, msg.repo_name, msg.pr_number - ), - ) - .await - { - // Cap reached — stop starting fix rounds on our own, and say so once. - let _ = github - .create_issue_comment( - &msg.repo_owner, - &msg.repo_name, - msg.pr_number, - &format!( - "I've made {MAX_SELF_REVIEW_FIX_ROUNDS} fix rounds on my own review of this \ - PR and each round still finds something, so I stop starting rounds on my \ - own here. My latest findings are above, each with what fixing it takes; a \ - comment naming a change starts the next round right away." - ), - ) - .await; - info!( - pr = msg.pr_number, - "Self-review fix cap reached — rounds stop, findings stay on the PR" - ); + } else { + // The convergence rule is the supervisor's: rounds go on while + // they close findings, up to twice the cap and below the run's + // spend ceiling; a round without progress changes approach; when + // the rounds end, what is open is deferred on the pull request + // with the reason and the ready decision takes it. + match claim_self_review_round( + state, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + &own_open, + ) + .await + { + SelfRound::Fix(rung) => { + let body = format!( + "{record_body}{}", + super::supervisor::round_instruction( + rung, + &format!("CoderHelm's own review findings ({})", own_open.join("; ")), + ) + ); + feed_review_back_to_run(state, &msg, &body).await; + } + SelfRound::End(why) => { + end_self_review_rounds(state, &github, &msg, &own_open, &why).await; + } + SelfRound::Busy => { + info!( + pr = msg.pr_number, + "Self-review round not claimed now (busy or unreadable)" + ); + } + } } } @@ -4372,42 +4369,218 @@ pub async fn review_for_run( } } -/// How many self-review → self-fix rounds CoderHelm runs on its OWN PR before it -/// gives up and hands to a human. Bounds the review↔fix loop so a flip-flopping -/// verdict can't churn commits/reviews forever (one PR hit 67 commits / 44 reviews -/// oscillating APPROVE↔REQUEST_CHANGES). The same cap as the run's own fix -/// rounds (`own_review::MAX_FIX_ROUNDS`). +/// The cap on self-review → self-fix rounds CoderHelm runs on its OWN PR. Past +/// it, rounds go on only while they close findings, up to twice it +/// (`supervisor::next_round`); then what is open is deferred. Bounds the +/// review↔fix loop so a flip-flopping verdict can't churn commits/reviews +/// forever (one PR hit 67 commits / 44 reviews oscillating +/// APPROVE↔REQUEST_CHANGES). The same cap as the run's own fix rounds +/// (`own_review::MAX_FIX_ROUNDS`). const MAX_SELF_REVIEW_FIX_ROUNDS: u32 = super::own_review::MAX_FIX_ROUNDS; -/// Claim one self-review→fix round for this PR (atomic conditional increment). -/// True while under MAX_SELF_REVIEW_FIX_ROUNDS (proceed with the fix); false once -/// the cap is reached — or on ANY error (fail CLOSED, like claim_auto_fix_slot: -/// never keep looping when the bound can't be confirmed). Self-expires via TTL so -/// a genuinely fresh re-run of the ticket later starts over. +/// What the supervisor's rule gives a self-review fix round. +#[derive(Debug, Clone, PartialEq, Eq)] +enum SelfRound { + /// Take the round, with this rung's approach. + Fix(super::supervisor::Rung), + /// The rounds are over: what is open is deferred with this reason. + End(String), + /// Another review is taking a round now, or the record couldn't be + /// read: no round from this one, and nothing ends. + Busy, +} + +/// The supervisor's rule for the next self-review fix round: `rounds` +/// taken, the findings open at the last one (`open_before`) and now +/// (`open_now`), `stalled` rounds in a row without progress, `spent` the +/// run's spend. +pub(crate) fn self_review_step( + rounds: u32, + open_before: Option, + open_now: usize, + stalled: u32, + spent: f64, +) -> super::supervisor::RoundStep { + super::supervisor::next_round(&super::supervisor::RoundFacts { + rounds, + cap: MAX_SELF_REVIEW_FIX_ROUNDS, + progressed: super::supervisor::findings_progress(open_before, open_now, 0), + stalled, + core: true, + spent_usd: spent, + cap_usd: super::run_ceiling::MAX_RUN_SPEND_USD, + }) +} + +/// Claims one self-review → fix round for this PR by the supervisor's rule +/// (`supervisor::next_round`): the record keeps the rounds taken, the +/// findings open at the last one and the rounds in a row without progress, +/// and the claim is a compare-and-set on the round count. `open` is what the +/// review found open now. Self-expires via TTL so a genuinely fresh re-run of +/// the ticket later starts over. async fn claim_self_review_round( state: &WorkerState, team_id: &str, owner: &str, repo: &str, pr: u64, -) -> bool { + open: &[String], +) -> SelfRound { let sk = format!("SELFREVIEWROUNDS#{owner}/{repo}#{pr:0>6}"); let ttl = chrono::Utc::now().timestamp() as u64 + 3 * 86_400; - state - .dynamo - .update_item() - .table_name(&state.config.settings_table_name) - .key("pk", attr_s(team_id)) - .key("sk", attr_s(&sk)) - .update_expression("SET #ttl = :ttl ADD rounds :one") - .condition_expression("attribute_not_exists(rounds) OR rounds < :max") - .expression_attribute_names("#ttl", "ttl") - .expression_attribute_values(":one", attr_n(1)) - .expression_attribute_values(":max", attr_n(u64::from(MAX_SELF_REVIEW_FIX_ROUNDS))) - .expression_attribute_values(":ttl", attr_n(ttl)) - .send() - .await - .is_ok() + let spent = match lookup_run_by_pr(state, team_id, owner, repo, pr).await { + Some(run_id) => super::run_ceiling::load(state, team_id, &run_id) + .await + .map(|t| t.spend_usd) + .unwrap_or(0.0), + None => 0.0, + }; + for _ in 0..2 { + let item = match state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(&sk)) + .consistent_read(true) + .send() + .await + { + Ok(o) => o.item.unwrap_or_default(), + Err(e) => { + warn!(pr, error = %e, "Could not read the self-review rounds — no round now"); + return SelfRound::Busy; + } + }; + let n = |k: &str| { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse::().ok()) + }; + let rounds = n("rounds").unwrap_or(0); + let step = self_review_step( + rounds, + n("open").map(|v| v as usize), + open.len(), + n("stalled").unwrap_or(0), + spent, + ); + let (rung, stalled) = match step { + super::supervisor::RoundStep::End { why } => return SelfRound::End(why), + super::supervisor::RoundStep::Round { rung, stalled } => (rung, stalled), + }; + let seen = if rounds == 0 { + "attribute_not_exists(rounds) OR rounds = :seen" + } else { + "rounds = :seen" + }; + let wrote = state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(&sk)) + .update_expression("SET #ttl = :ttl, #open = :o, stalled = :s ADD rounds :one") + .condition_expression(seen) + .expression_attribute_names("#ttl", "ttl") + .expression_attribute_names("#open", "open") + .expression_attribute_values(":one", attr_n(1)) + .expression_attribute_values(":seen", attr_n(rounds)) + .expression_attribute_values(":o", attr_n(open.len())) + .expression_attribute_values(":s", attr_n(stalled)) + .expression_attribute_values(":ttl", attr_n(ttl)) + .send() + .await; + match wrote { + Ok(_) => return SelfRound::Fix(rung), + Err(e) if format!("{e:?}").contains("ConditionalCheckFailed") => continue, + Err(e) => { + warn!(pr, error = %e, "Could not claim a self-review round — no round now"); + return SelfRound::Busy; + } + } + } + SelfRound::Busy +} + +/// The self-review rounds on CoderHelm's own PR ended by the supervisor's +/// rule: what is open is deferred on the pull request with the reason +/// (`own_review::defer_findings`, so it no longer holds the draft), the +/// pull request says so once, and the ready decision takes it (the draft +/// stays only while required checks are red). Never "a comment starts the +/// next round". +async fn end_self_review_rounds( + state: &WorkerState, + github: &GitHubClient, + msg: &ReviewMessage, + open: &[String], + why: &str, +) { + if !open.is_empty() { + match github + .get_pull_request(&msg.repo_owner, &msg.repo_name, msg.pr_number) + .await + { + Ok(p) => { + let body = p["body"].as_str().unwrap_or(""); + let now = super::own_review::defer_findings(body, open, why); + if now != body { + if let Err(e) = github + .update_pr_body(&msg.repo_owner, &msg.repo_name, msg.pr_number, &now) + .await + { + warn!(pr = msg.pr_number, error = %e, "Could not list the deferred findings on the pull request"); + } + } + } + Err(e) => { + warn!(pr = msg.pr_number, error = %e, "Could not read the pull request to defer the findings") + } + } + } + if claim_once( + state, + &msg.team_id, + &format!( + "SELFREVIEWHANDOFF#{}/{}#{:0>6}", + msg.repo_owner, msg.repo_name, msg.pr_number + ), + ) + .await + { + let _ = github + .create_issue_comment( + &msg.repo_owner, + &msg.repo_name, + msg.pr_number, + &self_review_end_note(open, why), + ) + .await; + } + info!( + pr = msg.pr_number, + why, "Self-review rounds ended — open findings deferred" + ); + super::ready::request(state, msg).await; +} + +/// What the pull request is told when the self-review rounds end: what was +/// deferred and why, and what happens next. No hand-off. +pub(crate) fn self_review_end_note(open: &[String], why: &str) -> String { + if open.is_empty() { + return format!( + "CoderHelm finished its fix rounds on its own review of this pull request ({why}). \ + The ready decision takes it from here: the draft is held only while required checks \ + fail." + ); + } + let list: Vec = open.iter().map(|i| format!("- {i}")).collect(); + format!( + "CoderHelm finished its fix rounds on its own review of this pull request ({why}). These \ + findings are deferred, listed under \"Deferred\" in the description with that reason:\n{}\n\n\ + The ready decision takes it from here: the draft is held only while required checks fail.", + list.join("\n") + ) } /// Perform a one-time action for a key (e.g. post the handoff notice once). diff --git a/services/worker/src/passes/supervisor.rs b/services/worker/src/passes/supervisor.rs index df8883879..415789e45 100644 --- a/services/worker/src/passes/supervisor.rs +++ b/services/worker/src/passes/supervisor.rs @@ -46,6 +46,12 @@ //! - **Budget follows progress** ([`may_extend`]): a loop at its round cap //! that is still fixing things gets more rounds, up to twice the cap; a //! run near its spend ceiling ships what is done ([`near_spend_cap`]). +//! The loops of fix rounds after the work (the CI-only rounds on a +//! finished run's pull request, the self-review and own-review rounds) +//! take each round by [`next_round`]: on while rounds make progress, a new +//! rung of the ladder when one makes none, and at the end what is left +//! deferred with the reason or the run failed with the cause +//! ([`end_of_rounds`]), never a wait on a person's comment. //! //! The tests at the bottom replay every historical stuck run's shape //! ([`replay`], `supervisor_replays.rs`) and read the worker's sources so a @@ -215,6 +221,153 @@ pub fn defer_reason(rung_count: u32, task: &str, core: bool) -> String { ) } +// ── Round budgets ─────────────────────────────────────────────────────────── + +/// The hard ceiling on a loop's rounds: twice its cap. +pub fn ceiling(cap: u32) -> u32 { + cap.saturating_mul(2) +} + +/// What a loop of fix rounds (the CI-only rounds on a finished run's pull +/// request, the rounds on CoderHelm's own review findings) decides its next +/// round from. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct RoundFacts { + /// Rounds the loop already took. + pub rounds: u32, + /// The loop's cap: rounds past it only while they make progress, up to + /// [`ceiling`]. + pub cap: u32, + /// The last round made progress (checks that were red turned green, + /// findings closed, the branch moved with changes for them). + pub progressed: bool, + /// Rounds in a row without progress before the last one. + pub stalled: u32, + /// What is left is core to the work (a readme line is not). + pub core: bool, + pub spent_usd: f64, + pub cap_usd: f64, +} + +/// The next step of a loop of fix rounds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RoundStep { + /// Take another round with this rung's approach; `stalled` is recorded + /// for the next decision. + Round { rung: Rung, stalled: u32 }, + /// The rounds are over: what is left is deferred with `why`, and the run + /// finishes ([`end_of_rounds`]). Never a wait on a person. + End { why: String }, +} + +/// The supervisor's rule for a loop of fix rounds: keep going while the +/// rounds make progress, up to twice the cap and below the spend ceiling; a +/// round without progress climbs the ladder ([`next_rung`]: narrow, fresh +/// context, re-split, the strongest model); the ladder's end, the ceiling, +/// or a round past the cap that made no progress ends the rounds. +pub fn next_round(f: &RoundFacts) -> RoundStep { + let stalled = if f.progressed { + 0 + } else { + f.stalled.saturating_add(1) + }; + if near_spend_cap(f.spent_usd, f.cap_usd) { + return RoundStep::End { + why: "the run is near its spend ceiling".into(), + }; + } + if f.rounds >= ceiling(f.cap) { + return RoundStep::End { + why: format!( + "{} rounds, the most this loop takes (twice its {} while rounds make progress)", + f.rounds, f.cap + ), + }; + } + if !may_extend(f.rounds, f.cap, f.progressed) { + return RoundStep::End { + why: format!( + "{} rounds, and the last one past the first {} made no progress", + f.rounds, f.cap + ), + }; + } + match next_rung(stalled, f.core) { + Rung::Defer | Rung::Ship => RoundStep::End { + why: format!( + "{stalled} rounds in a row made no progress, each with a different approach \ + (one item only, a fresh context with small edits, a re-split{})", + if f.core { ", the strongest model" } else { "" } + ), + }, + rung => RoundStep::Round { rung, stalled }, + } +} + +/// Whether a CI fix round made progress: a check that was red before it is +/// no longer red. The first round (nothing recorded before it) counts as +/// progress. A new check failing while every earlier one still fails is +/// not. +pub fn ci_progress(before: &[String], after: &[String]) -> bool { + before.is_empty() || before.iter().any(|c| !after.contains(c)) +} + +/// Whether a round on review findings made progress: fewer open than at the +/// review before it (`None` at the first), or the round pushed changes. +pub fn findings_progress(before: Option, after: usize, pushed_files: usize) -> bool { + before.is_none_or(|b| after < b) || pushed_files > 0 +} + +/// What a round on a rung is told, for `what` the round fixes. Empty for +/// [`Rung::Continue`], [`Rung::Defer`] and [`Rung::Ship`]. +pub fn round_instruction(rung: Rung, what: &str) -> String { + let what = common::truncate_str(what.trim(), 600); + match rung { + Rung::Continue | Rung::Defer | Rung::Ship => String::new(), + Rung::Narrow => format!( + "\n\n## This round's approach\nThe last round made no progress on: {what}. Take one \ + item only, the first one, and finish it in this round." + ), + Rung::SwitchTools => format!( + "\n\n## This round's approach\nTwo rounds in a row made no progress on: {what}. Start \ + fresh from the pull request's diff; don't redo work that is done. Read the files in \ + the parts you need and edit them in place with small edits, never rewrite a whole \ + file. If an edit is refused, read the exact current text around it and edit again." + ), + Rung::Resplit => format!( + "\n\n## This round's approach\nThree rounds made no progress on: {what}. Split the \ + first item into two or three smaller changes, write the list as the first lines of \ + your final message, and make only the first change now." + ), + Rung::Escalate => format!( + "\n\n## This round's approach\n{ESCALATED} Four rounds made no progress on: {what}. \ + Read the code around it and the tests that cover it, find why the earlier rounds \ + didn't land (a refused edit, a wrong file, a failing build), and make the change." + ), + } +} + +/// The words that mark a round taken on [`Rung::Escalate`]: a fix round +/// that carries them runs on the strongest model. +pub const ESCALATED: &str = "This round runs on the strongest model."; + +/// How a loop of fix rounds ends, by the one ending rule ([`end`]): `left` +/// (failing checks, findings) deferred with `why`, finished with them +/// listed on the pull request, or failed with the cause while checks of +/// ours are red (`ci_failing`). Never a wait on a person. +pub fn end_of_rounds(left: &[String], why: &str, ci_failing: &[String]) -> Ending { + end(&EndFacts { + deferred: left + .iter() + .map(|l| format!("{l} (deferred: {why})")) + .collect(), + ci_failing: ci_failing.to_vec(), + has_work: true, + ladder_spent: true, + ..Default::default() + }) +} + // ── Red checks ────────────────────────────────────────────────────────────── /// How many reverts the supervisor makes on one pull request before the @@ -503,6 +656,76 @@ mod tests { assert!(!may_extend(6, 3, true)); } + #[test] + fn rounds_follow_progress_climb_the_ladder_and_end_without_a_wait() { + let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::>(); + assert!(ci_progress(&[], &s(&["lint"]))); + assert!(ci_progress(&s(&["lint", "test"]), &s(&["test", "e2e"]))); + assert!(!ci_progress(&s(&["test"]), &s(&["test", "e2e"]))); + assert!(findings_progress(Some(3), 2, 0)); + assert!(findings_progress(Some(2), 2, 1)); + assert!(!findings_progress(Some(2), 2, 0)); + let f = RoundFacts { + rounds: 9, + cap: 8, + progressed: true, + core: true, + cap_usd: 200.0, + ..Default::default() + }; + assert_eq!( + next_round(&f), + RoundStep::Round { + rung: Rung::Continue, + stalled: 0 + } + ); + assert!(matches!( + next_round(&RoundFacts { rounds: 16, ..f }), + RoundStep::End { .. } + )); + assert!(matches!( + next_round(&RoundFacts { + progressed: false, + ..f + }), + RoundStep::End { .. } + )); + assert_eq!( + next_round(&RoundFacts { + rounds: 2, + progressed: false, + stalled: 1, + ..f + }), + RoundStep::Round { + rung: Rung::SwitchTools, + stalled: 2 + } + ); + // A non-core item (a readme line) is deferred after three. + assert!(matches!( + next_round(&RoundFacts { + rounds: 3, + progressed: false, + stalled: 2, + core: false, + ..f + }), + RoundStep::End { .. } + )); + // The ending: deferred and finished when green, failed when red; + // never a wait. + let left = s(&["a finding"]); + match end_of_rounds(&left, "why", &[]) { + Ending::Finished { deferred } => { + assert_eq!(deferred, s(&["a finding (deferred: why)"])) + } + e => panic!("{e:?}"), + } + assert_eq!(end_of_rounds(&left, "why", &s(&["build"])), Ending::Failed); + } + #[test] fn red_checks_revert_to_green_then_by_task_and_never_empty_the_pull_request() { let heads = vec![("c3".to_string(), false), ("c2".to_string(), true)];