diff --git a/docs/incidents.md b/docs/incidents.md index 86363db22..42d96bcc4 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -97,6 +97,7 @@ pipeline still calls it there. | br. `br_description_writer_upgrade` | After the description writer was upgraded (a final review in the one save, the repository's template as the structure), a pull request opened the day before kept its old text: six checks "Not run: still running when this was written", the file to read first and the way back said twice, filler and a raw page id. Its head had not moved and its checked text was unchanged, so its stamp said current and nothing rebuilt it. | The stamp names the writer version (`description::WRITER`, raised with every change to what a description says or how it is laid out); a description built by another writer, or before the version, is not current. The pull request watch's sweep catches up open pull requests CoderHelm opened, whatever the age of their run: a few per team each sweep (`pr_watch::CATCH_UP_PER_TEAM`), inside its GitHub budget, each rebuilt once and marked on its run. A description still wholly CoderHelm's is built again from the facts of the head alone: nothing of the old text is kept, not even in a fold, except a line that closes an issue. A security fix's pull request gets the same: its sections are computed from the lockfile on the head and nothing else of its old body is kept (`security_fixes::fresh_body`). A description with no CoderHelm stamp, or whose checked text a person changed, is left as it is. | | br. `br_description_writer_upgrade` | After the description writer was upgraded (a final review in the one save, the repository's template as the structure), a pull request opened the day before kept its old text: six checks "Not run: still running when this was written", the file to read first and the way back said twice, filler and a raw page id. Its head had not moved and its checked text was unchanged, so its stamp said current and nothing rebuilt it. | The stamp names the writer version (`description::WRITER`, raised with every change to what a description says or how it is laid out); a description built by another writer, or before the version, is not current. The pull request watch's sweep catches up open pull requests CoderHelm opened, whatever the age of their run: a few per team each sweep (`pr_watch::CATCH_UP_PER_TEAM`), inside its GitHub budget, each rebuilt once and marked on its run. A description still wholly CoderHelm's is built again from the facts of the head alone: nothing of the old text is kept, not even in a fold, except a line that closes an issue. A description with no CoderHelm stamp, or whose checked text a person changed, is left as it is. | | bs. `bs_cut_plan_revision` | A ticket with a long history was planned, and the plan check sent the plan back with two open items. The revision reached the output limit partway through its last block. The planner was told the coder's note ("make a change in small edit_file calls"), wrote only its decision block again, and the worker read only that last turn: no tasks, no design. The run failed with "empty or malformed plan ... retry the run" and the first plan was thrown away. | A planner's cut answer is continued where it stopped and read together with what came before the cut, file by file (`plan_sections`). A cut turn's note fits its loop: the coder's edit note only where there are edit tools, the planner's "continue the document" note, a shorter answer for everyone else. A revision that comes back empty, cut off or malformed never replaces a valid file, and a send-back asks for only the files that change. Files still missing are asked for alone, twice at most, the second with a larger output budget. A plan still not usable is planned again in a fresh step, then reported as CoderHelm's own failure, saying what it lacked. No run tells a person to retry it. | +| bt. `bt_proof_answer_closes` | A security update's own review asked for proof of the build and unit tests on the head. The fix rounds changed no code: the second ran every check on the head, all passing, and one runtime check it started was cut short by the step's time. The ledger counted that as a block, the round pushed nothing so no review read the head again, and the draft was held for a person ("Fix them on the branch, or remove a finding") while the merge standing said no person was needed. | A round that pushed nothing is read by a review of the same head, with the round's account in the reviewer's context, and a finding answered with proof closes there. A command, check or codegen a step is too short to start is owed: the pass continues in a fresh step that runs it first, and a round cut short by time is never a block. Nothing on CoderHelm's side holds a draft for a person: what is left after every approach is listed as CoderHelm's note and the pull request goes ready, with CoderHelm's verdict kept so nothing merges over it. A stuck run is sent back to its review on the next look of the ready sweep or the pull request's watch. | ## Adding a case diff --git a/services/worker/src/passes/dep_fix.rs b/services/worker/src/passes/dep_fix.rs index 84e426e7e..222fd0338 100644 --- a/services/worker/src/passes/dep_fix.rs +++ b/services/worker/src/passes/dep_fix.rs @@ -1661,6 +1661,7 @@ pub async fn implement_result( writes: Default::default(), outside_plan: Vec::new(), refused: Vec::new(), + owed: Vec::new(), evidence: super::proof::RunEvidence { notes: run.report_md(), checks: run diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index e7edc521c..ac6edb113 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -144,6 +144,34 @@ pub struct ImplementResult { pub outside_plan: Vec<(String, String)>, /// Edits the round was refused and never made. pub refused: Vec, + /// Commands (and `run_checks`) the coder asked for that this step had + /// too little time left to start: owed, never dropped. The pass then + /// counts as cut short, and the round continues in a fresh step that + /// runs them first ([`owed_first`]). + pub owed: Vec, +} + +/// The name an owed `run_checks` call carries in [`ImplementResult::owed`]. +pub const OWED_CHECKS: &str = "run_checks (the repository's checks)"; +const OWED_START: &str = "\n\n## Owed from the step before\n"; + +/// A continuing round's instructions with the checks its last step was too +/// short to start, to run first. Replaces an earlier such section, so a +/// round continued twice carries the newest list once. +pub fn owed_first(feedback: &str, owed: &[String]) -> String { + let base = feedback + .find(OWED_START) + .map_or(feedback, |i| &feedback[..i]); + if owed.is_empty() { + return base.to_string(); + } + let list: Vec = owed.iter().map(|c| format!("- `{c}`")).collect(); + format!( + "{base}{OWED_START}The step before this one was too short to start these. Run each \ + first, as its own call, with this step's full time, then go on. Write a result only \ + from output you have here:\n{}", + list.join("\n") + ) } #[allow(clippy::too_many_arguments)] @@ -800,6 +828,7 @@ pub async fn run( ci_steps, check_results: std::sync::Mutex::new(Vec::new()), sandbox_record: std::sync::Mutex::new(Default::default()), + owed: std::sync::Mutex::new(Vec::new()), last_checks_passed: std::sync::atomic::AtomicBool::new(true), codegen_cmd, codegen_env, @@ -1192,7 +1221,12 @@ pub async fn run( // Cut short by the deadline: the loop's own marker, or the pass ended // inside the wrap-up window (the agent summarized what was left). - let timed_out = reached_deadline(&closing, deadline, std::time::Instant::now()); + // A command or check this step was too short to start is owed: the pass + // is cut short and continues in a fresh step that runs it first, never + // a round that ends with the check unrun. + let owed = std::mem::take(&mut *executor.write_executor.owed.lock().unwrap()); + let timed_out = + reached_deadline(&closing, deadline, std::time::Instant::now()) || !owed.is_empty(); if closing == crate::agent::anthropic::TIMED_OUT_REPLY { closing.clear(); } @@ -1255,6 +1289,7 @@ pub async fn run( writes, outside_plan, refused, + owed, evidence: super::proof::RunEvidence { sources, lookups, @@ -1917,6 +1952,8 @@ struct WriteToolExecutor<'a> { /// or why it gave no result: the proof check names the real reason a /// check didn't run. sandbox_record: std::sync::Mutex, + /// Commands the step had too little time to start ([`ImplementResult::owed`]). + owed: std::sync::Mutex>, /// Verdict of the most recent run_checks (incl. tests). Starts true (nothing /// run yet ⇒ no red seen); set on every run_checks so the finish path can /// warn when the agent stops on a red result. @@ -2774,6 +2811,14 @@ impl<'a> WriteToolExecutor<'a> { Some(check_now_text(left, build)) } + /// A command this step was too short to start: owed to the next one. + fn owe(&self, command: &str) { + let mut owed = self.owed.lock().unwrap(); + if !owed.iter().any(|c| c == command) { + owed.push(command.to_string()); + } + } + /// Should a hand-edit to `path` (whose current content is `existing`) be /// rejected and steered to run_codegen? True only when the repo HAS a codegen /// command, the file looks generated, AND this path hasn't already been @@ -2984,10 +3029,14 @@ impl<'a> WriteToolExecutor<'a> { ))); } if !sandbox.has_time(self.deadline) { - note(LogOutcome::soft_fail("not run: not enough time left")); + note(LogOutcome::soft_fail( + "not run yet: owed to the next step, which has its full time", + )); + self.owe(command); return Ok(json!( - "This step has too little time left for a sandbox build. Finish your changes; \ - CoderHelm runs the repository's checks before the run finishes." + "This step has too little time left to start that command. It is owed, not \ + dropped: this round continues in a fresh step with its full time and runs it \ + first. Save what you changed and stop now; don't write a result for it." )); } if let Some(gate) = &self.policy { @@ -3097,11 +3146,13 @@ impl<'a> WriteToolExecutor<'a> { } if !sandbox.has_time(self.deadline) { note(LogOutcome::soft_fail( - "not run: not enough time left in this step; the checks run in the next step", + "not run yet: owed to the next step, which has its full time", )); // The check is owed, not dropped: the settle stage runs it in a - // step with a full window before the run finishes (`settle`). + // step with a full window before the run finishes (`settle`), + // and a fix round continues in a fresh step that runs it first. self.sandbox_record.lock().unwrap().refused_for_time = true; + self.owe(OWED_CHECKS); return Ok(json!( "This step has too little time left for a sandbox build. Finish your changes \ now; CoderHelm runs the repository's checks on the branch in a fresh step \ @@ -3440,9 +3491,14 @@ impl<'a> WriteToolExecutor<'a> { ))); } if !sandbox.has_time(self.deadline) { - note(LogOutcome::soft_fail("not run: not enough time left")); + note(LogOutcome::soft_fail( + "not run yet: owed to the next step, which has its full time", + )); + self.owe("run_codegen"); return Ok(json!( - "Not enough time remains to run codegen; finalize your changes now." + "This step has too little time left to run codegen. It is owed, not dropped: \ + this round continues in a fresh step with its full time and runs it first. Save \ + what you changed and stop now." )); } let source = match self.sandbox_source(sandbox, run_id).await { diff --git a/services/worker/src/passes/incidents/bi_own_review_finishes.rs b/services/worker/src/passes/incidents/bi_own_review_finishes.rs index ff13c12d8..f492b069e 100644 --- a/services/worker/src/passes/incidents/bi_own_review_finishes.rs +++ b/services/worker/src/passes/incidents/bi_own_review_finishes.rs @@ -122,12 +122,13 @@ fn a_finding_the_ticket_comment_rules_out_is_dropped_by_the_ticket_not_deferred( let Plan::Settle { deferred, by_ticket, + noted, } = l.decide(&[NAV_AGAIN.to_string()], 0.0, 200.0) else { panic!("settled by the ticket"); }; - assert!(deferred.is_empty()); - let lines = ledger::settled_lines(&deferred, &by_ticket); + assert!(deferred.is_empty() && noted.is_empty()); + let lines = ledger::settled_lines(&deferred, &by_ticket, ¬ed); assert!(lines[0].contains("the ticket rules it out"), "{lines:?}"); // The review of the head then names it as a note, never a hold. let mut findings: Vec = serde_json::from_value(serde_json::json!([ diff --git a/services/worker/src/passes/incidents/bt_proof_answer_closes.rs b/services/worker/src/passes/incidents/bt_proof_answer_closes.rs new file mode 100644 index 000000000..ade6cb1ef --- /dev/null +++ b/services/worker/src/passes/incidents/bt_proof_answer_closes.rs @@ -0,0 +1,317 @@ +//! bt. A security-updates run opened a draft pull request and CoderHelm's +//! own review asked for changes on its head with one finding: "Build and +//! unit-test proof is from an earlier commit, not the head". The finding was +//! about proof, not code, so the fix rounds changed nothing: the second +//! round ran the build, lint, type-check and unit tests on the head, all +//! passing, and wrote the results in its account. One more check it started +//! (loading a native module at runtime) was cut short by the step's time. +//! The ledger recorded the finding as blocked for lack of time, the round +//! pushed nothing so no review read the head again, the run completed, and +//! the draft was held "for a person": "1 finding from CoderHelm's review is +//! still open. Fix them on the branch, or remove a finding". The merge +//! standing beside it said no person was needed. It stayed that way for +//! thirteen hours. +//! +//! Guarantee: a round that pushed nothing is read by a review of the same +//! head, with the round's account in the reviewer's context, and a finding +//! answered with proof closes there. A check cut short by a step's time is +//! owed, never a block: the round continues in a fresh step that runs it +//! first. Nothing on CoderHelm's side (time, round caps, budgets, its own +//! limits) holds a draft for a person: what is truly left after every +//! approach is listed on the pull request as CoderHelm's note and the pull +//! request goes ready. An already-stuck run recovers on the next look of +//! the ready sweep or the pull request's watch. + +use super::fixture::*; +use crate::passes::own_review_ledger::{ + self as ledger, Approach, Blocker, Completion, Ledger, Plan, Settled, +}; + +const OLD: &str = "Fix them on the branch, or remove a finding"; +const HEAD: &str = "4b1d0c9e2f7a"; + +/// The finding, as the review listed it. +const PROOF: &str = + "Build and unit-test proof is from an earlier commit, not the head (`package.json:200`)"; + +/// What the second round wrote: every check on the head passing, one +/// runtime check cut short by the step's time. +const ACCOUNT: &str = "I re-ran the build, lint, type-check and unit tests on the head commit \ +4b1d0c9, and all four pass. There were no code changes this round; the finding was about the \ +proof, not the code.\n- Build: passed (`pnpm run build`, exit 0).\n- Unit tests: passed \ +(`jest --ci`, 188 suites passed).\nEvidence:\n- Confirmed: the sandbox checked out 4b1d0c9.\n- \ +Unconfirmed [external:native module at runtime]: whether the module loads and runs a query. It \ +didn't run because the sandbox ran out of time this step."; + +/// The log line the cut-short check left. +fn cut_short_log() -> Vec { + vec![serde_json::json!({"content": "not run: not enough time left"})] +} + +/// The run's ledger as it was stored: one finding, one round observed and +/// recorded as blocked for time, and the second round ended with no review +/// reading it. +fn the_stuck_ledger() -> Ledger { + let json = serde_json::json!({ + "findings": [{ + "item": PROOF, "attempts": 1, "stalled": 0, "blocked": 1, + "last_blocked": ["no_time"], "person_claims": 0, "person_reason": "", + "person_what": "", "settled": null + }], + "last": {"taken": [PROOF], "blocked": ["no_time"], "account": ACCOUNT, "ended": true}, + "continues": 1 + }); + Ledger::of_json(&json.to_string()) +} + +#[test] +fn a_check_cut_short_by_time_is_resumed_never_blocked() { + let mut l = Ledger::default(); + let open = vec![PROOF.to_string()]; + l.observe(&open, ""); + // Round after round cut short by the step's time: past the block cap, + // the finding still gets a fresh round, never a hand-back. + for n in 1..=ledger::MAX_BLOCKED + 1 { + let Plan::Round { focus, .. } = l.decide(&open, 0.0, 200.0) else { + panic!("round {n}: another round, not an ending"); + }; + l.start_round(&focus); + l.end_round(ledger::blockers_of(&[], &cut_short_log()), ACCOUNT); + l.observe(&open, ""); + let t = &l.findings[0]; + assert_eq!(t.blocked, 0, "time is not a block: {t:?}"); + assert_eq!(t.cut_short, n); + match l.decide(&open, 0.0, 200.0) { + Plan::Round { + approach: Approach::Unblock(b), + fresh, + unscoped, + focus, + } => { + assert_eq!(b, vec![Blocker::NoTime]); + assert!(fresh, "it starts with its full time"); + assert!(!unscoped, "nothing was refused"); + let told = ledger::instruction(&Approach::Unblock(b), &focus); + assert!(told.contains("fresh step with its full time"), "{told}"); + assert!(told.contains("first"), "{told}"); + } + other => panic!("round {n}: {other:?}"), + } + } + // The stored record of the stuck run: its time block is not counted + // again, and the next round starts fresh. + let mut stuck = the_stuck_ledger(); + stuck.observe(&open, ""); + assert_eq!( + (stuck.findings[0].blocked, stuck.findings[0].cut_short), + (1, 1) + ); + assert!(matches!( + stuck.decide(&open, 0.0, 200.0), + Plan::Round { fresh: true, .. } + )); +} + +#[test] +fn a_step_too_short_for_a_check_owes_it_to_the_next_step() { + use crate::passes::implement::{owed_first, OWED_CHECKS}; + let base = "CoderHelm's own review found the issues below."; + let once = owed_first( + base, + &["node -e \"require('mod')\"".to_string(), OWED_CHECKS.into()], + ); + assert!(once.starts_with(base)); + assert!(once.contains("Run each first"), "{once}"); + assert!(once.contains("`node -e \"require('mod')\"`")); + // Continued twice: the newest list, once. + let twice = owed_first(&once, &["pnpm test".to_string()]); + assert_eq!(twice.matches("Owed from the step before").count(), 1); + assert!(twice.contains("`pnpm test`") && !twice.contains("require('mod')")); + assert_eq!(owed_first(&twice, &[]), base); + // The coder's command, `run_checks` and codegen owe what they can't + // start, and a pass that owes anything continues in a fresh step. + let implement = include_str!("../implement.rs"); + assert_eq!( + implement.matches("self.owe(").count(), + 3, + "every refusal for time owes" + ); + assert!(implement.contains("|| !owed.is_empty()")); + assert!(!implement.contains("finalize your changes now")); + let resume = include_str!("../resume.rs"); + let round = fn_src(resume, "\nasync fn run_fix_round("); + assert!(round.contains("owed_first(&round.feedback, &r.owed)")); +} + +#[test] +fn a_round_that_pushed_nothing_is_read_by_a_review_of_the_same_head() { + let mut l = the_stuck_ledger(); + assert!( + l.round_unread(), + "the second round's account was never read" + ); + // The reviewer is given the round's account and the rule for proof. + let account = l.last.as_ref().map(|r| r.account.clone()).unwrap(); + let section = crate::passes::review_pr::round_answer_section(&account); + assert!(section.contains("all four pass")); + assert!(section.contains("fixed when the proof is of this head")); + assert!(section.contains("only when the change rests on it")); + assert!(crate::passes::review_pr::round_answer_section(" ").is_empty()); + // The review accepts the proof: the finding is fixed and the head is + // approved, so the run completes and the pull request goes ready. + l.observe(&[], ""); + assert!(!l.round_unread()); + assert_eq!(l.findings[0].settled, Some(Settled::Fixed)); + assert_eq!(l.decide(&[], 0.0, 200.0), Plan::Ready); + assert_eq!( + ledger::completion(Some(("APPROVE", HEAD)), HEAD, &l), + Completion::Complete + ); + // Wired: a finished run's held draft sends the same head to review + // before anything else, the parked round's end goes back to review + // instead of completing, and the completion guard reviews again rather + // than rerunning checks that never review. + let resume = include_str!("../resume.rs"); + let queue = fn_src(resume, "\npub(crate) async fn queue_own_review_round("); + let unread = queue + .find("ledger.round_unread()") + .expect("reads the round first"); + assert!(unread < queue.find("round_left(").unwrap()); + assert!(queue.contains("review_head_again(")); + assert!(!queue.contains("#fh <> :h"), "no once-per-head rule"); + let pending = fn_src(resume, "\nasync fn run_pending_round("); + let review_fix = pending + .find("kind == run_round::Kind::ReviewFix") + .expect("a review-fix round has its own ending"); + assert!(review_fix < pending.find("mark_pr_ready(").unwrap()); + let guard = fn_src(resume, "\nasync fn own_review_completion("); + assert!(guard.contains("review_head_again(")); + assert!(!guard.contains("recheck_at_checks(")); +} + +#[test] +fn what_is_left_after_every_approach_is_a_note_on_a_ready_pull_request() { + use crate::passes::ready::{self, Ci, Decision, Facts}; + let open = vec![PROOF.to_string()]; + let mut l = Ledger::default(); + l.observe(&open, ""); + for _ in 0..ledger::MAX_STALLED { + let Plan::Round { focus, .. } = l.decide(&open, 0.0, 200.0) else { + panic!("a round"); + }; + l.start_round(&focus); + l.end_round(vec![], "Tried."); + l.observe(&open, ""); + } + let Plan::Unfixed { why } = l.decide(&open, 0.0, 200.0) else { + panic!("every approach taken"); + }; + // CoderHelm's limit: its note, never a hold on the run. + assert!(matches!( + ledger::completion(Some(("REQUEST_CHANGES", HEAD)), HEAD, &l), + Completion::Defer(_) + )); + l.note(&open, &why); + let Plan::Settle { + deferred, + by_ticket, + noted, + } = l.decide(&open, 0.0, 200.0) + else { + panic!("settled as a note"); + }; + assert!(deferred.is_empty() && by_ticket.is_empty()); + let lines = ledger::settled_lines(&deferred, &by_ticket, ¬ed); + assert!(lines[0].contains("CoderHelm's note"), "{lines:?}"); + assert!(!lines[0].contains("needs a person")); + // Its review no longer lists it as holding the draft, and never + // approves over it. + let mut findings: Vec = + serde_json::from_value(serde_json::json!([{ + "file": "package.json", "line": 200, "severity": "medium", + "category": "correctness", "evidence": "verified-defect", + "title": "Build and unit-test proof is from an earlier commit, not the head", + "body": "The results quoted are of an older commit." + }])) + .unwrap(); + let mut own_open = open.clone(); + let settled = crate::passes::review_pr::settle_own_findings(&l, &mut findings, &mut own_open); + assert!(own_open.is_empty()); + assert!(settled.is_empty(), "a note never clears the merge hold"); + assert!(findings[0].holds_merge()); + // A completion on that verdict completes: nothing more to do. + assert_eq!( + ledger::completion(Some(("REQUEST_CHANGES", HEAD)), HEAD, &l), + Completion::Complete + ); + // The pull request: the open-findings section goes, the note is listed, + // and the ready decision marks it ready. + let body = format!( + "{}\n\n## Summary\nSecurity updates.\n", + crate::passes::own_review::section(&open) + ); + let now = crate::passes::own_review::defer_findings(&body, &lines, "CoderHelm's notes"); + assert!(crate::passes::own_review::hold(&now).is_none()); + assert!(now.contains("## Deferred")); + let f = Facts { + draft: true, + body: now, + head: HEAD.into(), + security: true, + ci: Ci { + green: true, + why: String::new(), + }, + ..Default::default() + }; + assert!(matches!(ready::decide(&f), Decision::Ready { .. })); + let mut end = Ending { + status: "completed".into(), + ..Default::default() + }; + end.said(lines.join("\n")); + end.never_says(OLD); +} + +#[test] +fn no_coderhelm_limit_holds_the_draft_for_a_person() { + use crate::passes::ready::{self, Ci, Decision, Facts}; + use common::draft_hold::{DraftHold, Kind}; + // Findings listed while nothing is queued this moment: CoderHelm takes + // them on its next look, a wait that needs no person. + let body = crate::passes::own_review::section(&[PROOF.to_string()]); + let f = Facts { + draft: true, + body, + head: HEAD.into(), + security: true, + own_fixing: true, + ci: Ci { + green: true, + why: String::new(), + }, + ..Default::default() + }; + let Decision::Wait { why, .. } = ready::decide(&f) else { + panic!("a wait, not a hold"); + }; + let hold = DraftHold::new( + Kind::Waiting, + vec![common::draft_hold::Reason::new(&why, "")], + 42, + "", + ) + .unwrap(); + assert!(!hold.needs_person()); + assert!(!hold.summary().contains(OLD)); + // Every way out of the queue that isn't a round is a wait or a note: + // no "person" ending is left. + let resume = include_str!("../resume.rs"); + assert!(!resume.contains("OwnRound::Person")); + let ready_src = include_str!("../ready.rs"); + let fix = fn_src(ready_src, "\nasync fn fix_own_findings("); + assert!(fix.contains("OwnRound::Later(why)") && fix.contains("f.own_fixing = true")); + // The in-run ending for findings left after every approach lists them + // and finishes, never waiting on a person. + assert!(resume.contains("note_own_findings(state, &msg.team_id, &msg.run_id, &own_open, &why)")); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index c1627b553..0849ab389 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -58,6 +58,7 @@ mod bp_repo_traced_not_asked; mod bq_upstream_read_not_guessed; mod br_description_writer_upgrade; mod bs_cut_plan_revision; +mod bt_proof_answer_closes; mod c_codegen_egress; mod d_echoed_markers; mod e_large_generated_output; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 25a54af27..60ce9fec3 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -4075,6 +4075,7 @@ async fn run_passes( writes: Default::default(), outside_plan: Vec::new(), refused: Vec::new(), + owed: Vec::new(), // The first attempt's lookups weren't kept; the proof check's // fix round can make them again. evidence: proof::RunEvidence { diff --git a/services/worker/src/passes/own_review.rs b/services/worker/src/passes/own_review.rs index c840248c3..5177bc13a 100644 --- a/services/worker/src/passes/own_review.rs +++ b/services/worker/src/passes/own_review.rs @@ -26,10 +26,11 @@ //! rounds at a cap once deferred a one-line config omission the tools had //! blocked. The run's spend ceiling still bounds every loop. //! - 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; when the run's rounds are over ([`rounds_over`]) the -//! findings are deferred the same way instead of held for a person. +//! nothing queued. A round that pushed nothing is read by a review of the +//! same head first; otherwise the ready decision queues a review-fix round +//! while the ledger has an approach left, and waits for it. What is left +//! is listed as CoderHelm's note and the PR goes ready, never 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. diff --git a/services/worker/src/passes/own_review_ledger.rs b/services/worker/src/passes/own_review_ledger.rs index b0dd3c091..4fa639f3a 100644 --- a/services/worker/src/passes/own_review_ledger.rs +++ b/services/worker/src/passes/own_review_ledger.rs @@ -32,7 +32,16 @@ //! reaches), claimed by two honest rounds or by the round that exhausted //! every approach; //! - a finding that survives every approach without such a reason is -//! [`Plan::Unfixed`]: the run says so and never reports itself finished. +//! [`Plan::Unfixed`]: CoderHelm's own limit, never a person's to-do. The +//! pull request is marked ready with it listed as a deferred note. +//! +//! A round cut short by its step's time ([`Blocker::NoTime`]) is neither a +//! stall nor a block: the check it started is owed, and the next round +//! starts in a fresh step with its full time and runs that check first +//! ([`Track::cut_short`], up to [`MAX_CUT_SHORT`]). A security run once +//! answered a proof-only finding with every check passing on the head but +//! one runtime check the sandbox ran out of time for, and the finding was +//! handed to a person as "still open". use serde::{Deserialize, Serialize}; @@ -48,6 +57,11 @@ pub const MAX_STALLED: u32 = 5; /// Rounds on one finding that a tool or a guard blocked, each followed by a /// round that removes the block. pub const MAX_BLOCKED: u32 = 3; +/// Rounds on one finding cut short by their step's time, each followed by a +/// round in a fresh step with its full time. Only a safety bound: a check +/// cut short is resumed, and a round that keeps being cut short points at +/// something else, which the pull request then lists as a note. +pub const MAX_CUT_SHORT: u32 = 6; /// The most fix rounds a run takes on its own findings in all: every /// finding's bound, for the record's claim. pub const MAX_ROUNDS: u32 = 24; @@ -72,7 +86,8 @@ pub enum Blocker { Scope, /// An edit was refused for another reason. Refused, - /// Checks were skipped, or the round stopped, for lack of time. + /// A check was cut short, or the round stopped, by its step's time: + /// never a block, the check is owed to a fresh step. NoTime, /// A tool call failed on its own input (an `edits` sent as a string). ToolInput, @@ -83,7 +98,9 @@ impl Blocker { match self { Blocker::Scope => "an edit the fix needed was refused as outside the round's files", Blocker::Refused => "an edit the fix needed was refused", - Blocker::NoTime => "its checks were skipped because not enough time was left", + Blocker::NoTime => { + "a check it started was cut short by its step's time, before it finished" + } Blocker::ToolInput => "an edit failed on the tool's input shape", } } @@ -113,7 +130,9 @@ pub fn blockers_of( if text.contains("outside the round's files") { add(Blocker::Scope); } - if text.contains("not run: not enough time left") { + if text.contains("not run: not enough time left") + || text.contains("not run yet: owed to the next step") + { add(Blocker::NoTime); } if text.contains("edit_file not applied") { @@ -133,6 +152,12 @@ pub enum Settled { ByTicket { quote: String }, /// A person-gate reason: only a person can do it. Deferred { reason: String, what: String }, + /// CoderHelm's own rounds left it open after every approach they have + /// (`why`): listed on the pull request as CoderHelm's note, and the pull + /// request goes ready for review. Never a person's to-do, and never + /// approved over: CoderHelm's verdict on the head stays as it is, so + /// nothing merges on it. + Noted { why: String }, } /// One finding of the run's own review and every round taken on it. @@ -149,6 +174,10 @@ pub struct Track { /// Rounds a tool or a guard blocked. #[serde(default)] pub blocked: u32, + /// Rounds cut short by their step's time ([`Blocker::NoTime`]): neither + /// a stall nor a block, the next round resumes in a fresh step. + #[serde(default)] + pub cut_short: u32, /// What blocked the last round on it (empty when nothing did). #[serde(default)] pub last_blocked: Vec, @@ -209,6 +238,8 @@ pub enum Plan { Settle { deferred: Vec<(String, String)>, by_ticket: Vec<(String, String)>, + /// CoderHelm's notes: item, and what its rounds left ([`Settled::Noted`]). + noted: Vec<(String, String)>, }, /// Findings that survived every approach without a person-gate reason: /// the run is not finished and says so. @@ -418,12 +449,19 @@ impl Ledger { t.person_reason = code; t.person_what = what; } - if l.blocked.is_empty() { - t.stalled += 1; - t.last_blocked.clear(); - } else { - t.blocked += 1; - t.last_blocked = l.blocked.clone(); + match round_ending(&l.blocked) { + RoundEnding::Honest => { + t.stalled += 1; + t.last_blocked.clear(); + } + RoundEnding::CutShort => { + t.cut_short += 1; + t.last_blocked = vec![Blocker::NoTime]; + } + RoundEnding::Blocked => { + t.blocked += 1; + t.last_blocked = l.blocked.clone(); + } } // Two honest rounds that said the same person-gate reason. if t.person_claims >= 2 && t.last_blocked.is_empty() { @@ -436,7 +474,15 @@ impl Ledger { } fn exhausted(t: &Track) -> bool { - t.stalled >= MAX_STALLED || t.blocked >= MAX_BLOCKED + t.stalled >= MAX_STALLED || t.blocked >= MAX_BLOCKED || t.cut_short >= MAX_CUT_SHORT + } + + /// A round ended and no review has read it yet: its account (proof it + /// gave, a check it ran) is what the next review of the head judges. + /// A round that pushed nothing leaves the head where it was, so only a + /// review of that same head can read it. + pub fn round_unread(&self) -> bool { + self.last.as_ref().is_some_and(|l| l.ended) } /// What follows for the findings `open` now, by each one's own record. @@ -458,8 +504,10 @@ impl Ledger { let settle = || { let mut deferred = Vec::new(); let mut by_ticket = Vec::new(); + let mut noted = Vec::new(); for t in tracks.iter().copied() { match &t.settled { + Some(Settled::Noted { why }) => noted.push((t.item.clone(), why.clone())), Some(Settled::ByTicket { quote }) => { by_ticket.push((t.item.clone(), quote.clone())) } @@ -476,6 +524,7 @@ impl Ledger { Plan::Settle { deferred, by_ticket, + noted, } }; if live.is_empty() { @@ -504,8 +553,8 @@ impl Ledger { count(not.len()), not.iter() .map(|t| format!( - "{} rounds, {} blocked by tools or guards", - t.attempts, t.blocked + "{} rounds, {} blocked by tools or guards, {} cut short by time", + t.attempts, t.blocked, t.cut_short )) .collect::>() .join("; "), @@ -556,6 +605,29 @@ impl Ledger { } } + /// Records `items` as CoderHelm's notes ([`Settled::Noted`]): its own + /// rounds left them open for `why`. The pull request lists them and goes + /// ready; the review no longer holds the draft on them. + pub fn note(&mut self, items: &[String], why: &str) { + for item in items { + if self.find_mut(item).is_none() { + self.findings.push(Track { + item: item.clone(), + ..Default::default() + }); + } + let t = self.find_mut(item).expect("tracked above"); + if !matches!( + t.settled, + Some(Settled::ByTicket { .. } | Settled::Deferred { .. }) + ) { + t.settled = Some(Settled::Noted { + why: why.to_string(), + }); + } + } + } + /// Whether every finding still open on `open` is settled with a reason /// (a person-gate reason, or the ticket), so the review's verdict on the /// head must not hold on it. @@ -570,6 +642,37 @@ impl Ledger { } } +/// How a round ended, from what it met. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum RoundEnding { + /// Nothing blocked it: the model tried. + Honest, + /// Only its step's time cut it short: the check is owed, not blocked. + CutShort, + /// A tool or a guard blocked it. + Blocked, +} + +fn round_ending(blocked: &[Blocker]) -> RoundEnding { + if blocked.is_empty() { + RoundEnding::Honest + } else if blocked.iter().all(|b| *b == Blocker::NoTime) { + RoundEnding::CutShort + } else { + RoundEnding::Blocked + } +} + +/// The deferred note for findings CoderHelm's own rounds left open (`why`): +/// listed on the pull request, which is marked ready. Never a person's +/// to-do: it says what CoderHelm did and what is left. +pub fn note_lines(items: &[String], why: &str) -> Vec { + items + .iter() + .map(|i| format!("{i}: CoderHelm's note, left open after its own rounds ({why})")) + .collect() +} + fn deferred_words(code: &str, what: &str) -> String { let label = person_label(code).unwrap_or("only a person can do it"); if what.trim().is_empty() { @@ -600,6 +703,13 @@ pub fn instruction(approach: &Approach, focus: &[String]) -> String { match approach { Approach::All => String::new(), Approach::Ladder(r) => super::supervisor::round_instruction(*r, &what), + Approach::Unblock(b) if b.iter().all(|x| *x == Blocker::NoTime) => format!( + "\n\n## This round's approach\nThe last round on {what} was cut short by its step's \ + time before a check it started finished. That check is owed: this round starts in a \ + fresh step with its full time. Run the check the last round's account names as not \ + confirmed first, as its own `bash` call, then finish what is left. Write a result \ + only from output you have here." + ), Approach::Unblock(b) => format!( "\n\n## This round's approach\nThe last round on {what} didn't fail on the code: {}. \ This round removes that: it has no file boundary (edit the file the fix needs, and \ @@ -613,7 +723,11 @@ pub fn instruction(approach: &Approach, focus: &[String]) -> String { /// The deferred lines for the pull request: each item with its person-gate /// reason, and each item the ticket rules out with its words. -pub fn settled_lines(deferred: &[(String, String)], by_ticket: &[(String, String)]) -> Vec { +pub fn settled_lines( + deferred: &[(String, String)], + by_ticket: &[(String, String)], + noted: &[(String, String)], +) -> Vec { deferred .iter() .map(|(i, why)| format!("{i}: needs a person ({why})")) @@ -622,6 +736,11 @@ pub fn settled_lines(deferred: &[(String, String)], by_ticket: &[(String, String .iter() .map(|(i, q)| format!("{i}: not done, the ticket rules it out (\"{q}\")")), ) + .chain( + noted + .iter() + .flat_map(|(i, why)| note_lines(std::slice::from_ref(i), why)), + ) .collect() } @@ -634,8 +753,13 @@ pub enum Completion { /// Its review still asks for changes on the head: the run goes back to /// its checks and its review, not to "completed". Continue(String), - /// It asked for changes on the head after every approach: never - /// "completed"; the run ends with this, named. + /// It asked for changes on the head after every approach CoderHelm + /// has: CoderHelm's own limit, never a person's to-do. What is open is + /// listed on the pull request as a deferred note with this, and the + /// pull request is marked ready. + Defer(String), + /// A deferred finding has no reason only a person can give: never + /// "completed" on it. Hold(String), } @@ -658,9 +782,18 @@ pub fn completion(verdict: Option<(&str, &str)>, head: &str, ledger: &Ledger) -> if !changes { return Completion::Complete; } + // What the review still asks for is CoderHelm's own notes, listed on the + // ready pull request: nothing more to do, and nothing approved over. + let noted = ledger + .findings + .iter() + .any(|t| matches!(t.settled, Some(Settled::Noted { .. }))); + if noted && ledger.findings.iter().all(|t| t.settled.is_some()) { + return Completion::Complete; + } let short = head.get(..7).unwrap_or(head); if ledger.continues >= MAX_CONTINUES { - return Completion::Hold(format!( + return Completion::Defer(format!( "CoderHelm's review still asks for changes on `{short}` after the run went back to \ its checks {} times", ledger.continues @@ -671,7 +804,7 @@ pub fn completion(verdict: Option<(&str, &str)>, head: &str, ledger: &Ledger) -> .iter() .find(|t| t.settled.is_none() && Ledger::exhausted(t) && t.person_reason.is_empty()) { - return Completion::Hold(format!( + return Completion::Defer(format!( "CoderHelm's review still asks for changes on `{short}` and every approach on this \ finding was taken: {}", t.item @@ -899,10 +1032,10 @@ mod tests { Plan::Unfixed { why } => assert!(why.contains("every approach"), "{why}"), other => panic!("{other:?}"), } - // Never "completed" with it: the guard holds. + // CoderHelm's own limit: listed as its note, never held for a person. assert!(matches!( completion(Some(("REQUEST_CHANGES", "abcdef1234")), "abcdef1234", &l), - Completion::Hold(_) + Completion::Defer(_) )); } @@ -955,10 +1088,11 @@ mod tests { Plan::Settle { deferred, by_ticket, + noted, } => { assert!(deferred.is_empty()); assert_eq!(by_ticket.len(), 1); - let lines = settled_lines(&deferred, &by_ticket); + let lines = settled_lines(&deferred, &by_ticket, ¬ed); assert!(lines[0].contains("the ticket rules it out"), "{lines:?}"); } other => panic!("{other:?}"), @@ -1036,7 +1170,7 @@ mod tests { }; assert!(matches!( completion(Some(("REQUEST_CHANGES", "h")), "h", &spent), - Completion::Hold(_) + Completion::Defer(_) )); let bad = Ledger { findings: vec![Track { diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 1904ca260..1b8dbcfd0 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -675,8 +675,8 @@ async fn perform( _ => Performed::Settled, } } - super::resume::OwnRound::Person(why) => { - info!(run_id = %c.run_id, why = %why, "PR watch: no fix round for the review's findings now"); + super::resume::OwnRound::Later(why) => { + info!(run_id = %c.run_id, why = %why, "PR watch: no fix round for the review's findings this moment"); Performed::NotStarted } } diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index 31f7b4ea0..e5f44b12c 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -63,12 +63,14 @@ //! request once stayed a draft for days on "CoderHelm fixes them in its //! review rounds" after its run had spent its fix budget: no round ever //! ran. CoderHelm's own open review findings on a finished run's draft -//! queue one review-fix round, once per head, while the run has rounds -//! left (`resume::queue_own_review_round`), and the pull request waits for -//! it ("CoderHelm is fixing N findings from its review"); with no round -//! left, or once one ran on the head and the findings are still there, the -//! hold names what a person does. Every other hold says only what CoderHelm -//! does when something is queued to do it. +//! are CoderHelm's to finish (`resume::queue_own_review_round`): a round +//! no review has read yet sends the same head back to review, otherwise a +//! review-fix round is queued while the ledger has an approach left, and +//! the pull request waits for it ("CoderHelm is fixing N findings from its +//! review"). What is left after every approach is listed as CoderHelm's +//! note and the pull request goes ready; no CoderHelm limit holds it for a +//! person. Every other hold says only what CoderHelm does when something +//! is queued to do it. use std::collections::HashMap; @@ -1152,8 +1154,12 @@ async fn fix_own_findings(ctx: &Ctx<'_>, run_id: &str, f: &mut Facts) { .await { 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 now"); + // Nothing queued this moment, for a reason that passes by itself: + // CoderHelm takes them on its next look, a wait and never a + // person's to-do. + super::resume::OwnRound::Later(why) => { + info!(pr = ctx.pr, run_id, why = %why, "No fix round for the own review's findings this moment; the next look takes them"); + f.own_fixing = true; } super::resume::OwnRound::Defer(lines) => { // Every finding left is settled with its own reason (a diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 4d425ea55..387a12031 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3537,8 +3537,10 @@ pub async fn run( super::own_review_ledger::Plan::Settle { deferred, by_ticket, + noted, } => { - let lines = super::own_review_ledger::settled_lines(&deferred, &by_ticket); + let lines = + super::own_review_ledger::settled_lines(&deferred, &by_ticket, ¬ed); finish_on_own_findings( state, &ticket_msg, @@ -3557,13 +3559,20 @@ pub async fn run( return Ok(()); } super::own_review_ledger::Plan::Unfixed { why } => { - // Never "completed" with its own review asking for - // changes: the run ends with what is open, named. - wait_for_review( + // CoderHelm's own rounds took every approach they + // have: its limit, never a person's to-do. What is + // left is listed as its note and the pull request + // goes ready for review. + let lines = + note_own_findings(state, &msg.team_id, &msg.run_id, &own_open, &why) + .await; + finish_on_own_findings( state, &ticket_msg, + &github, &msg.run_id, - &why, + &lines, + "CoderHelm's notes, each with what its rounds left", &pr_url, pr_number, &branch, @@ -3725,19 +3734,25 @@ pub async fn run( mark_events_processed(state, &msg.run_id, &events).await; match end { RoundEnd::Parked => return Ok(()), + // A review-fix round that used every step it had: what it + // landed and its account are the head's to review now, and + // the ledger takes the next round in a fresh step. Never a + // run that finishes on a round cut short. RoundEnd::Incomplete => { - complete_run_with_status( + if set_run_awaiting_ci( state, &ctx.ticket_msg, &msg.run_id, - "completed", &pr_url, pr_number, &branch, &ctx.usage, wall_clock_secs(created_at, &start), ) - .await?; + .await? + { + send_delayed_resume(state, &msg, 5).await; + } return Ok(()); } RoundEnd::Done { files: 0 } if !own_open.is_empty() => { @@ -4150,7 +4165,10 @@ async fn run_fix_round( branch: pr.branch, }; match result { - Ok(r) if r.timed_out => { + Ok(mut r) if r.timed_out => { + // What this step was too short to start is owed: the next step + // of the round runs it first, with its full time. + round.feedback = super::implement::owed_first(&round.feedback, &r.owed); if round.may_continue() { park_round( state, @@ -4165,12 +4183,33 @@ async fn run_fix_round( .await } else { if round.kind == run_round::Kind::ReviewFix { + // Cut short, not blocked: the review of the head reads + // what it did, and the ledger's next round starts in a + // fresh step that runs what is owed first. + if !r.owed.is_empty() { + r.evidence.notes.push_str(&format!( + "\n\nOwed (cut short by the step's time, to run first next): {}", + r.owed + .iter() + .map(|c| format!("`{c}`")) + .collect::>() + .join("; ") + )); + } + record_own_round_note( + state, + &msg.team_id, + &msg.run_id, + &round.feedback, + &r.evidence, + ) + .await; Box::pin(super::own_review_ledger::record_round_end( state, &msg.team_id, &msg.run_id, vec![super::own_review_ledger::Blocker::NoTime], - "", + r.evidence.latest_notes(), )) .await; } @@ -4592,6 +4631,31 @@ async fn run_pending_round( } return Ok(()); } + // A review-fix round that pushed nothing (it answered with proof or a + // check it ran) or used every step it had: no push starts a review, so + // the run goes back to its review of the same head, which reads the + // round's account and closes what it answered. It once marked the pull + // request ready and completed here, with the finding left open on a + // head nothing would review again. + if kind == run_round::Kind::ReviewFix + && matches!(end, RoundEnd::Incomplete | RoundEnd::Done { files: 0 }) + { + if set_run_awaiting_ci( + state, + &ctx.ticket_msg, + &msg.run_id, + &pr_url, + pr_number, + &branch, + &ctx.usage, + wall_clock_secs(created_at, start), + ) + .await? + { + send_delayed_resume(state, msg, 5).await; + } + return Ok(()); + } match end { RoundEnd::Parked => {} RoundEnd::Incomplete => { @@ -5986,7 +6050,7 @@ async fn own_review_completion( msg: &TicketMessage, run_id: &str, pr_number: u64, - branch: &str, + _branch: &str, ) -> super::own_review_ledger::Completion { use super::own_review_ledger::{self as ledger, Completion}; let Ok(github) = GitHubClient::new( @@ -6022,43 +6086,77 @@ async fn own_review_completion( &head, &l, ); - let Completion::Continue(why) = &said else { - return said; + let body = pr["body"].as_str().unwrap_or(""); + let why = match &said { + Completion::Continue(why) => why.clone(), + // CoderHelm took every approach it has: what its review still asks + // for is listed as its note and the pull request goes ready for a + // person's review. Its own limit, never a person's to-do. + Completion::Defer(why) => { + let open: Vec = { + let listed = super::own_review::listed(body); + if listed.is_empty() { + l.findings + .iter() + .filter(|t| t.settled.is_none()) + .map(|t| t.item.clone()) + .collect() + } else { + listed + } + }; + let lines = note_own_findings(state, &msg.team_id, run_id, &open, why).await; + let now = super::own_review::defer_findings( + body, + &lines, + "CoderHelm's notes, each with what its rounds left", + ); + if now != body { + if let Err(e) = crate::passes::description::save( + &github, + &msg.repo_owner, + &msg.repo_name, + pr_number, + &now, + ) + .await + { + warn!(run_id, error = %e, "Could not list CoderHelm's notes on the pull request"); + } + } + super::add_progress_note( + state, + &msg.team_id, + run_id, + &super::own_review::finish_reason(&lines, why), + ) + .await; + mark_pr_ready( + state, + &msg.team_id, + &github, + &msg.repo_owner, + &msg.repo_name, + pr_number, + ) + .await; + return Completion::Complete; + } + _ => return said, }; l.continues += 1; ledger::save(state, &msg.team_id, run_id, &l).await; - let item = state - .dynamo - .get_item() - .table_name(&state.config.runs_table_name) - .key("team_id", attr_s(&msg.team_id)) - .key("run_id", attr_s(run_id)) - .consistent_read(true) - .send() - .await - .ok() - .and_then(|o| o.item) - .unwrap_or_default(); - let Some((ticket, _)) = super::recheck::message_of(&item) else { - return Completion::Hold(format!("{why}, but the run's record lacks what that needs")); - }; - let body = pr["body"].as_str().unwrap_or(""); - match super::recheck_at_checks( - state, - &ticket, - run_id, - branch, - super::recheck::carry_of(body).as_ref(), - why, - ) - .await - { - super::Handoff::Continued => { - info!(run_id, pr_number, %head, "Own review asks for changes on the head: the run goes on instead of completing"); - said - } - super::Handoff::Stopped(reason) => Completion::Hold(format!("{why}; {reason}")), + // The run goes back to its review of the head: the review reads what + // the last round found and closes what it answered, or the ledger takes + // the next round. Rechecking the run's own checks never reviews the + // head, and a run once completed again on the same open finding. + if review_head_again(state, &msg.team_id, run_id, msg.installation_id, &why).await { + info!(run_id, pr_number, %head, "Own review asks for changes on the head: the run goes back to its review instead of completing"); + return said; } + // The review couldn't be queued this moment: the pull request's watch + // and the ready sweep take it from here (`queue_own_review_round`). + Completion::Complete } /// Records the own-review progress on the run. Best-effort. @@ -6165,14 +6263,18 @@ async fn record_own_round_note( /// (`ready::settle`). #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum OwnRound { - /// A review-fix round for them is queued or running on this head. + /// A review-fix round for them, or CoderHelm's review of the head + /// reading what the last round found, is queued or running. Fixing, - /// 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), + /// Nothing is queued this moment for a reason that passes by itself (a + /// race with another decision, the record or the head not read, the run + /// still working): the next look takes them. Why, for the log. A wait, + /// never a person's to-do. + Later(String), /// Every finding left is settled with its own reason - /// (`own_review_ledger`): a person-gate reason, or the ticket's words. - /// The lines, each with its reason, are listed as deferred. + /// (`own_review_ledger`): a person-gate reason, the ticket's words, or + /// CoderHelm's note on what its own rounds left. The lines, each with + /// its reason, are listed as deferred and the pull request goes ready. Defer(Vec), } @@ -6232,8 +6334,120 @@ pub(crate) async fn run_finished(state: &WorkerState, team_id: &str, run_id: &st [COMPLETED, SUCCESS, NEEDS_INPUT].contains(&status.as_str()) } +/// CoderHelm's review reads the head again, for a run whose last word on +/// its own findings no review has read: a fix round that answered with +/// proof or a check and pushed nothing (the head didn't move, so no push +/// starts a review), or a completion its own review still asks changes of. +/// The run goes back to waiting on its CI and its review +/// (`awaiting_ci`), and the resume reviews the head with the round's +/// account in hand (`review_pr::review_for_run`). Never for a run a person +/// ended or the run guard stopped. True when the review is on its way. +pub(crate) async fn review_head_again( + state: &WorkerState, + team_id: &str, + run_id: &str, + installation_id: u64, + why: &str, +) -> bool { + use common::run_status::AWAITING_CI; + if state.config.ci_fix_queue_url.is_empty() || run_id.is_empty() { + return false; + } + let status = 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("#s") + .expression_attribute_names("#s", "status") + .consistent_read(true) + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| i.get("status").and_then(|v| v.as_s().ok()).cloned()) + .unwrap_or_default(); + if !may_review_again(&status) { + return false; + } + let claimed = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression( + "SET #s = :aw, status_run_id = :sri, current_pass = :aw, updated_at = :t \ + REMOVE waiting_on, wait_reminded_at", + ) + .condition_expression("#s = :was AND attribute_not_exists(guard_open)") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":aw", attr_s(AWAITING_CI)) + .expression_attribute_values(":sri", attr_s(&format!("{AWAITING_CI}#{run_id}"))) + .expression_attribute_values(":was", attr_s(&status)) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await; + if let Err(e) = claimed { + if !format!("{e:?}").contains("ConditionalCheckFailed") { + warn!(run_id, error = %e, "Could not send the run back to its review"); + } + return false; + } + let body = serde_json::json!({ + "type": "resume", + "team_id": team_id, + "run_id": run_id, + "installation_id": installation_id, + }); + let sent = state + .sqs + .send_message() + .queue_url(&state.config.ci_fix_queue_url) + .message_body(body.to_string()) + .delay_seconds(5) + .send() + .await; + if let Err(e) = sent { + warn!(run_id, error = %e, "Could not queue the review of the head"); + // Back as it was: the next look tries again. + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #s = :was, status_run_id = :sri") + .condition_expression("#s = :aw") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":was", attr_s(&status)) + .expression_attribute_values(":sri", attr_s(&format!("{status}#{run_id}"))) + .expression_attribute_values(":aw", attr_s(AWAITING_CI)) + .send() + .await; + return false; + } + super::add_progress_note( + state, + team_id, + run_id, + &format!("{why}: CoderHelm's review reads the head again with what the round found."), + ) + .await; + info!(run_id, why, "The run goes back to its review of the head"); + true +} + +/// Whether a run in `status` may be sent back to its review: finished, +/// waiting on a person, or still working; never one a person ended. +pub(crate) fn may_review_again(status: &str) -> bool { + use common::run_status::{COMPLETED, IN_FLIGHT, NEEDS_INPUT, SUCCESS}; + [COMPLETED, SUCCESS, NEEDS_INPUT].contains(&status) || IN_FLIGHT.contains(&status) +} + /// On the run: the head a review-fix round was queued for after the run -/// finished, so one is queued once per head. +/// finished. pub(crate) const OWN_FIX_HEAD: &str = "own_fix_head"; /// On the run: its rounds on its own review's findings stopped and a /// person has them; nothing queues another. @@ -6243,6 +6457,30 @@ pub(crate) const OWN_REVIEW_HANDED: &str = "own_review_handed"; /// `head`): queues one review-fix round for them while the run has rounds /// left, once per head, under the same budgets as the run's own rounds, and /// says whether one is on its way. Never promises a round nothing queued. +/// CoderHelm's own rounds left `items` open (`why`): recorded on the +/// ledger as its notes, so the review no longer lists them as holding the +/// draft, and returned as the lines the pull request lists. Never a +/// person's to-do. +async fn note_own_findings( + state: &WorkerState, + team_id: &str, + run_id: &str, + items: &[String], + why: &str, +) -> Vec { + let mut l = super::own_review_ledger::load(state, team_id, run_id).await; + l.note(items, why); + super::own_review_ledger::save(state, team_id, run_id, &l).await; + super::own_review_ledger::note_lines(items, why) +} + +fn n_of(item: &std::collections::HashMap, k: &str) -> u64 { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse::().ok()) + .unwrap_or(0) +} + pub(crate) async fn queue_own_review_round( state: &WorkerState, github: &GitHubClient, @@ -6251,8 +6489,13 @@ pub(crate) async fn queue_own_review_round( head: &str, items: &[String], ) -> OwnRound { + // Every way out that isn't a round: CoderHelm's own limit, listed on + // the pull request as its note, never held for a person. + let note = |why: String| async move { + OwnRound::Defer(note_own_findings(state, team_id, run_id, items, &why).await) + }; if run_id.is_empty() || items.is_empty() { - return OwnRound::Person("no run or nothing listed".into()); + return OwnRound::Later("no run or nothing listed".into()); } let item = match state .dynamo @@ -6267,7 +6510,7 @@ pub(crate) async fn queue_own_review_round( Ok(o) => o.item.unwrap_or_default(), Err(e) => { warn!(run_id, error = %e, "Could not read the run to fix its own review's findings"); - return OwnRound::Person("the run couldn't be read".into()); + return OwnRound::Later("the run couldn't be read".into()); } }; let status = item @@ -6287,6 +6530,34 @@ pub(crate) async fn queue_own_review_round( // while a finding has an approach left, deferred only with a person-gate // reason or settled by the ticket, never ended by a count of rounds. let mut ledger = super::own_review_ledger::of_item(&item); + // The last round's account no review has read (it answered with proof, + // ran a check, or was cut short, and pushed nothing): the review of this + // same head reads it first. A finding answered with proof closes there. + if ledger.round_unread() { + // The run is working (its own loop reviews the head when it is + // done): nothing is sent from here. + if common::run_status::IN_FLIGHT.contains(&status.as_str()) { + return OwnRound::Later("the run is still working".into()); + } + let installation_id = item + .get("installation_id") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or_else(|| github.installation_id()); + return if review_head_again( + state, + team_id, + run_id, + installation_id, + "The last fix round on CoderHelm's review findings pushed nothing new", + ) + .await + { + OwnRound::Fixing + } else { + OwnRound::Later("the review of the head couldn't be queued now".into()) + }; + } let ticket_text = super::own_review_ledger::ticket_text(state, team_id, &item).await; ledger.observe(items, &ticket_text); let spent = super::run_ceiling::load(state, team_id, run_id) @@ -6304,40 +6575,52 @@ pub(crate) async fn queue_own_review_round( super::own_review_ledger::Plan::Settle { deferred, by_ticket, + noted, } => { super::own_review_ledger::save(state, team_id, run_id, &ledger).await; return OwnRound::Defer(super::own_review_ledger::settled_lines( - &deferred, &by_ticket, + &deferred, &by_ticket, ¬ed, )); } super::own_review_ledger::Plan::Unfixed { why } => { super::own_review_ledger::save(state, team_id, run_id, &ledger).await; - return OwnRound::Person(why); + return note(why).await; } super::own_review_ledger::Plan::Ready => { - return OwnRound::Person("nothing the review raised is open".into()); + return OwnRound::Later("nothing the review raised is open".into()); } }; if let Err(why) = super::own_review::round_left( &super::own_review::RoundBudget { - // The ledger bounds the rounds, finding by finding. + // The ledger bounds the rounds, finding by finding, and the + // review of the head reads every round before the next one + // (`round_unread` above): a round on the same head after a + // proof-only answer is the ledger's call, not a once-per-head + // rule. rounds: 0, pushes: 0, cycles: 0, handed: false, + queued_head: String::new(), ..budget.clone() }, head, super::MAX_AUTO_FIX_PUSHES, MAX_CI_FIX_CYCLES, ) { - return OwnRound::Person(why); + // The run guard stopped the run: CoderHelm's limit, listed as its + // note. Anything else (the head not read, the run still working) + // passes by itself. + if budget.guard_open { + return note(why).await; + } + return OwnRound::Later(why); } let Some((ticket, branch)) = super::recheck::message_of(&item) else { - return OwnRound::Person("the run's record lacks what a round needs".into()); + return note("the run's record lacks what a fix round needs".into()).await; }; if state.config.ci_fix_queue_url.is_empty() { - return OwnRound::Person("no queue to run the round on".into()); + return note("no queue to run a fix round on".into()).await; } // Claim it: the run is working again, on this head, with one more round // taken. The same conditions as `round_left`, so two deciders can't both @@ -6356,7 +6639,6 @@ pub(crate) async fn queue_own_review_round( ) .condition_expression( "#s = :was AND attribute_not_exists(guard_open) AND attribute_not_exists(#hd) \ - AND (attribute_not_exists(#fh) OR #fh <> :h) \ AND (attribute_not_exists(own_review_rounds) OR own_review_rounds < :maxr) \ AND (attribute_not_exists(auto_fix_pushes) OR auto_fix_pushes < :maxp)", ) @@ -6385,8 +6667,20 @@ pub(crate) async fn queue_own_review_round( if let Err(e) = claim { if !format!("{e:?}").contains("ConditionalCheckFailed") { warn!(run_id, error = %e, "Could not claim a fix round for the own review's findings"); + return OwnRound::Later("the fix round couldn't be claimed now".into()); + } + // Its rounds ended (`own_review_handed`) or reached the ceiling: + // CoderHelm's limit, its note. Otherwise another decision changed + // the run first, and the next look sees what it did. + if item.contains_key(OWN_REVIEW_HANDED) + || n_of(&item, "own_review_rounds") >= u64::from(super::own_review_ledger::MAX_ROUNDS) + { + return note( + "CoderHelm's fix rounds on its own review's findings reached their ceiling".into(), + ) + .await; } - return OwnRound::Person("another decision changed the run first".into()); + return OwnRound::Later("another decision changed the run first".into()); } let give_back = |why: String| async move { let _ = state @@ -6410,7 +6704,7 @@ pub(crate) async fn queue_own_review_round( .send() .await; warn!(run_id, why = %why, "The fix round for the own review's findings couldn't be queued"); - OwnRound::Person(why) + OwnRound::Later(why) }; if !super::claim_auto_fix_slot_upto( state, @@ -6421,7 +6715,8 @@ pub(crate) async fn queue_own_review_round( ) .await { - return give_back("the run's automatic fix budget is spent".into()).await; + let _ = give_back("the run's automatic fix budget is spent".into()).await; + return note("the run's automatic fix budget is spent".into()).await; } let base_sha = super::round::branch_head(github, &ticket.repo_owner, &ticket.repo_name, &branch).await; @@ -7237,7 +7532,10 @@ async fn wait_on_person( // every approach it ends naming what its review still asks for. if pr_number > 0 { match Box::pin(own_review_completion(state, msg, run_id, pr_number, branch)).await { - super::own_review_ledger::Completion::Complete => {} + // Defer: CoderHelm's notes were listed and the pull request + // marked ready (`own_review_completion`); the run completes. + super::own_review_ledger::Completion::Complete + | super::own_review_ledger::Completion::Defer(_) => {} super::own_review_ledger::Completion::Continue(_) => return Ok(()), super::own_review_ledger::Completion::Hold(why) => { let why = format!("{reason}\n{why}"); @@ -7597,7 +7895,8 @@ async fn complete_run_with_status( // the run goes on, or ends saying what is open (`wait_on_person`). if status == common::run_status::COMPLETED && pr_number > 0 { match Box::pin(own_review_completion(state, msg, run_id, pr_number, branch)).await { - super::own_review_ledger::Completion::Complete => {} + super::own_review_ledger::Completion::Complete + | super::own_review_ledger::Completion::Defer(_) => {} super::own_review_ledger::Completion::Continue(_) => return Ok(()), super::own_review_ledger::Completion::Hold(why) => { return wait_for_review( diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 220073690..9cb34cdb0 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -2874,8 +2874,26 @@ async fn run_once( Some(run_id) => Box::pin(ticket_context_for_pr(state, &msg.team_id, run_id)).await, None => String::new(), }; - let extra_context = - format!("{graph_context}{ci_context}{quality_context}{plan_context}{ticket_context}"); + // What the run's last fix round answered: a round that answered a + // finding with proof (a check run on this head) pushed nothing, and + // only this review of the same head can read it and close the finding. + let round_context = match &own_run { + Some(run_id) => { + let ledger = + Box::pin(super::own_review_ledger::load(state, &msg.team_id, run_id)).await; + round_answer_section( + ledger + .last + .as_ref() + .filter(|l| l.ended) + .map_or("", |l| l.account.as_str()), + ) + } + None => String::new(), + }; + let extra_context = format!( + "{graph_context}{ci_context}{quality_context}{plan_context}{ticket_context}{round_context}" + ); // CoderHelm's own threads from earlier reviews, with the replies under them. // Still-open ones: the re-review reports each as fixed or answered (→ resolved @@ -5157,22 +5175,29 @@ pub(crate) fn settle_own_findings( format!(": {what}") } ), - Settled::Fixed => String::new(), + Settled::Fixed | Settled::Noted { .. } => String::new(), }; let mut settled = Vec::new(); for f in findings.iter_mut() { let line = super::own_review::thread_line(&f.file, f.line, &f.title); if let Some(s) = ledger.settled_item(&line) { + // CoderHelm's own note: listed on the ready pull request, still + // a finding of this review, never approved over. + if matches!(s, Settled::Noted { .. }) { + continue; + } super::review_policy::demote(f, &why(s)); settled.push(line); } } own_open.retain(|o| { - let keep = ledger.settled_item(o).is_none(); - if !keep && !settled.contains(o) { + let s = ledger.settled_item(o); + // A noted finding leaves the list that holds the draft, and keeps + // holding the merge (its thread stays open). + if s.is_some_and(|s| !matches!(s, Settled::Noted { .. })) && !settled.contains(o) { settled.push(o.clone()); } - keep + s.is_none() }); settled } @@ -5198,6 +5223,27 @@ async fn ticket_context_for_pr(state: &WorkerState, team_id: &str, run_id: &str) own_ticket_section(&text) } +/// The reviewer's section for what the run's last fix round answered on +/// the head: its own account, with the rule for judging proof. Empty when +/// no round ended unread. +pub(crate) fn round_answer_section(account: &str) -> String { + let account = account.trim(); + if account.is_empty() { + return String::new(); + } + format!( + "\n## What CoderHelm's last fix round answered on this head\nThe round below was asked \ + to fix your earlier findings on this pull request. Where it answered a finding with \ + proof rather than a code change (a check it ran on this head: the command, the commit \ + and the result), judge that proof. A finding that asked for proof is fixed when the \ + proof is of this head and shows the check passing: report it fixed and don't raise it \ + again. A claim with no command or result is not proof. A check the round names as not \ + confirmed is a finding only when the change rests on it; say exactly which check and \ + why.\n\n{}\n", + common::truncate_str(account, 8_000) + ) +} + /// The reviewer's section for the ticket of CoderHelm's own pull request. pub(crate) fn own_ticket_section(text: &str) -> String { if text.trim().is_empty() {