diff --git a/docs/incidents.md b/docs/incidents.md index a4c715fb5..6c133d5c6 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -51,6 +51,7 @@ pipeline still calls it there. | s. `s_silent_draft` | A new-feature run finished with CI green and CoderHelm's review approving, and its pull request stayed a draft. Four of CoderHelm's own sandbox checks had failed on the head, the mark-ready step returned without a word, and the run page said completed. The same day, mark-ready messages that hit GitHub's rate limit were dropped and five more pull requests stayed drafts. | One decision settles every pull request a finished run leaves, on every path. With CI green and the review approving, CoderHelm's own sandbox failures and checklist items never hold the draft: the pull request is marked ready with them under Open items. A hold that remains names each reason and what to do at the top of the description, at warn in the log, and on the run, which is `needs_input` while a person must act. A mark-ready GitHub refuses is tried again after its reset, a bounded number of times, and the last refusal is recorded on the run. A sweep decides again for finished runs left a draft with no recorded reason, respecting a person's draft and a closed pull request. | | t. `t_unrun_check_hold` | A check's gate couldn't install its package's dependencies (`pnpm: command not found` in CoderHelm's sandbox). The tooling failure went under Open items as a check the change didn't pass, and the pull request stayed a draft after CI passed. | A check CoderHelm's own tools couldn't run becomes an Open item CI settles, never a hold. A line written the old way stops holding once CI is green on the head and leaves the description when the pull request is marked ready. A check the change really failed still holds. The decision reads the repository's CI whenever such a line is in the description, not only when CoderHelm's own feature checks have findings: without that read, CI counted as not green and the line kept holding on every sweep. | | u. `u_stacked_plan_check` | A run stacked on an earlier part's open pull request reset to the default branch in every step, rebuilt and force-pushed its branch each time, and measured its plan against the other branch: 13 files that branch already changed read as not done, the coder found nothing to write, and the guard stopped the run after seven continuations. | A later step keeps the base an earlier step stacked it on; a planned file the stacked-on branch already changes is done there, and the plan check's note says so; a fall in the done count is reported on the run page, and its recovery counts as progress a bounded number of times. | +| w. `w_stale_hold_recheck` | A finished run's pull request stayed a draft on an Open items line a wrong rule wrote ("the change makes the staging content its end-to-end tests read out of date"). The rule was fixed, but the line was text in the description and nothing checked it again, so the hold stayed until a person edited it. The same run spent three steps writing nothing while its plan check fell from 37 to 23 and came back each step, and the guard counted each return as progress. | Every blocked line names the version of the code that wrote it. A pull request held on a line other code wrote is checked again on its head in a fresh step of the run, once per run and code version, with the checks whose failure is a hold run again on an unchanged head; the Open items are then written from what they find. A line the running code wrote never starts another check. A fall in the plan check's count and its return count as progress only when the run's coder wrote code in between, and every plan check measures with the stacked base. | ## Adding a case diff --git a/services/worker/build.rs b/services/worker/build.rs new file mode 100644 index 000000000..a8f92867c --- /dev/null +++ b/services/worker/build.rs @@ -0,0 +1,69 @@ +//! The version of the code that checks a change, for `passes::checks_version`. +//! +//! A hold CoderHelm's own checks write into a pull request's description is +//! text: nothing ran the check again when the code that wrote it changed, so +//! a pull request held by a rule that was later fixed stayed held. Each such +//! line now carries the version of the code that wrote it, and the ready +//! sweep checks the pull request again when the running code differs. +//! +//! The version is a hash of the worker's and the common crate's sources, so +//! it is the same wherever the same code runs (hosted or a self-hosted +//! install) and changes whenever that code does, with no build step to +//! remember. + +use std::path::{Path, PathBuf}; + +fn files(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + files(&p, out); + } else { + out.push(p); + } + } +} + +/// FNV-1a, 64 bits: stable across toolchains, unlike the standard hasher. +fn fnv(hash: &mut u64, bytes: &[u8]) { + for b in bytes { + *hash ^= u64::from(*b); + *hash = hash.wrapping_mul(0x0100_0000_01b3); + } +} + +fn main() { + let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".into())); + let dirs = [root.join("src"), root.join("../common/src")]; + let mut all = Vec::new(); + for d in &dirs { + println!("cargo:rerun-if-changed={}", d.display()); + files(d, &mut all); + } + // The same order everywhere: by path relative to the crate. + let mut named: Vec<(String, PathBuf)> = all + .into_iter() + .map(|p| { + let rel = p + .strip_prefix(&root) + .unwrap_or(&p) + .to_string_lossy() + .replace('\\', "/"); + (rel, p) + }) + .collect(); + named.sort(); + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for (rel, p) in &named { + fnv(&mut hash, rel.as_bytes()); + fnv(&mut hash, &[0]); + if let Ok(bytes) = std::fs::read(p) { + fnv(&mut hash, &bytes); + } + fnv(&mut hash, &[0]); + } + println!("cargo:rustc-env=CODERHELM_CHECKS_VERSION={hash:016x}"); +} diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 5904745da..043cca82f 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -1043,7 +1043,7 @@ pub async fn run( } } - let files = executor + let files: Vec = executor .write_executor .files_modified .lock() @@ -1051,6 +1051,11 @@ pub async fn run( .iter() .cloned() .collect(); + // The run's own code moved: what the run guard weighs a recovered plan + // check count against. + if let (Some(run_id), false) = (run_id, files.is_empty()) { + super::run_guard::wrote_code(state, &msg.team_id, run_id).await; + } // 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). diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 824662e05..d3f1842c6 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -37,3 +37,4 @@ mod s_silent_draft; mod t_unrun_check_hold; mod u_stacked_plan_check; mod v_dropped_field_hold; +mod w_stale_hold_recheck; diff --git a/services/worker/src/passes/incidents/u_stacked_plan_check.rs b/services/worker/src/passes/incidents/u_stacked_plan_check.rs index 430112ef1..793646738 100644 --- a/services/worker/src/passes/incidents/u_stacked_plan_check.rs +++ b/services/worker/src/passes/incidents/u_stacked_plan_check.rs @@ -125,6 +125,8 @@ fn a_fall_in_the_count_is_news_and_its_recovery_is_progress() { assert!(!g.apply(&Progress::TasksDone(17))); assert_eq!(g.task_drops, 2); g.on_continuation(1.0); + // The run's coder writes the lost work again. + g.on_own_code(); assert!( g.apply(&Progress::TasksDone(23)), "lost work done again is progress" @@ -138,6 +140,7 @@ fn a_fall_in_the_count_is_news_and_its_recovery_is_progress() { g.on_continuation(1.0); g.apply(&Progress::TasksDone(17)); g.on_continuation(1.0); + g.on_own_code(); g.apply(&Progress::TasksDone(23)); } assert!(g.task_drops > MAX_TASK_DROPS); diff --git a/services/worker/src/passes/incidents/w_stale_hold_recheck.rs b/services/worker/src/passes/incidents/w_stale_hold_recheck.rs new file mode 100644 index 000000000..c4f1eaedf --- /dev/null +++ b/services/worker/src/passes/incidents/w_stale_hold_recheck.rs @@ -0,0 +1,250 @@ +//! w. A run finished and its pull request stayed a draft. Under Open items a +//! line marked as a check the change didn't pass said "the change makes the +//! staging content its end-to-end tests read out of date". The rule that +//! wrote it was wrong and was fixed, but the line was text in the +//! description: nothing ran the check again when the code that wrote it +//! changed, so the pull request stayed held on every sweep until a person +//! edited the description. A mention of CoderHelm on the pull request only +//! resumes a fix round's unfinished work, and this one had none. +//! +//! The same run spent three fresh steps doing nothing. Each step started by +//! rebuilding its stacked branch, the plan check at the start of the step +//! measured the branch's own diff (23 of 38 tasks) and the check after the +//! coder measured with the stacked base (37 of 38). The run guard counted +//! each return to 37 as work done again, so it never stopped the steps, +//! though the coder wrote nothing in any of them. +//! +//! Guarantees: +//! - Every blocked line names the version of the code that wrote it. A pull +//! request held on a line other code wrote is checked again on its head by +//! a fresh step of the run, once per run and code version; the checks whose +//! failure is a hold run again even on an unchanged head, and the Open +//! items are written from what they find. +//! - A line the running code wrote never starts another check: no loop. +//! - A fall in the plan check's count and its return count as progress only +//! when the run's coder wrote code in between. Every plan check measures +//! with the stacked base. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; + +use super::fixture::fn_src; +use crate::passes::completeness::{self, Section}; +use crate::passes::proof; +use crate::passes::ready::{self, Ci, Decision, Facts}; +use crate::passes::recheck; +use crate::passes::run_guard::{GuardState, Ledger, Progress, Trip}; + +/// The reason the old rule wrote. +const STALE: &str = "the change makes the staging content its end-to-end tests read out of date."; + +/// A version of the checks other than the one running now. +const OLD_VERSION: &str = "00000000feedface"; + +/// The Open items as the run left them: written by older checks, with no +/// version (lines written before lines carried one) or an older one. +fn held_description(version: Option<&str>) -> String { + let section = proof::gaps_section(&[proof::check_item("The new-feature rules", STALE)]); + let now = proof::checked_by(proof::checks_version()); + let section = match version { + Some(v) => section.replace(&now, &proof::checked_by(v)), + None => section.replace(&format!(" {now}"), ""), + }; + format!("## Summary\nOne Title Size setting for every venue block.\n\n{section}") +} + +fn facts(body: &str) -> Facts { + Facts { + draft: true, + title: "Add a Title Size setting to the venue page blocks".into(), + body: body.to_string(), + ci: Ci { + green: true, + why: String::new(), + }, + approved: true, + ..Default::default() + } +} + +/// What the checks write when they run again: the Open items replaced by +/// what they find now (`pr::apply_checks`). +fn rewritten(body: &str, found: &[proof::Finding]) -> String { + let (mut owned, rest) = completeness::take_owned(body); + owned.set(Section::OpenItems, proof::gaps_section(found)); + completeness::assemble(&rest, &owned) +} + +#[test] +fn a_hold_older_checks_wrote_is_checked_again_and_clears() { + let now = proof::checks_version(); + assert!(!now.is_empty()); + for body in [held_description(None), held_description(Some(OLD_VERSION))] { + assert!(body.contains(proof::BLOCKED_MARK), "{body}"); + let f = facts(&body); + let d = ready::decide(&f); + assert!(matches!(d, Decision::Held { .. }), "{d:?}"); + assert!(ready::recheck_due(&f, &d, now), "{body}"); + } + // The checks run again with the fixed rule and find nothing: the line + // goes and the pull request is ready. + let after = rewritten(&held_description(None), &[]); + assert!(!after.contains(STALE), "{after}"); + assert!(after.contains("One Title Size setting"), "{after}"); + let f = facts(&after); + assert_eq!(ready::decide(&f), Decision::Ready { open: vec![] }); +} + +#[test] +fn a_line_the_running_checks_wrote_never_starts_another_check() { + let now = proof::checks_version(); + // The check still fails on the new code: it holds, as a check the change + // didn't pass, and is not checked again. + let body = held_description(Some(now)); + assert!(body.contains(&proof::checked_by(now)), "{body}"); + assert_eq!(proof::checked_by_of(&body), Some(now)); + let f = facts(&body); + let d = ready::decide(&f); + assert!(matches!(d, Decision::Held { .. })); + assert!(!ready::recheck_due(&f, &d, now)); + + // A person's draft and a closed pull request are never checked again. + let old = held_description(None); + let mine = Facts { + put_back_by: Some("someone".into()), + ..facts(&old) + }; + assert!(!ready::recheck_due(&mine, &ready::decide(&mine), now)); + let closed = Facts { + closed: true, + ..facts(&old) + }; + assert!(!ready::recheck_due(&closed, &ready::decide(&closed), now)); +} + +#[test] +fn once_per_run_and_version_recorded_in_the_claim() { + // The claim and its record are one conditional write: a second decider, + // or the next sweep on the same code, finds the version taken. + let src = include_str!("../recheck.rs"); + let claim = fn_src(src, "\nasync fn claim("); + assert!(claim.contains("SET recheck_version = :v")); + assert!(claim.contains("recheck_version <> :v")); + assert!(claim.contains("attribute_not_exists(guard_open)")); + // `settle` checks again only when it is due and the claim was won. + let ready_src = include_str!("../ready.rs"); + let settle = fn_src(ready_src, "\npub async fn settle("); + let at = settle.find("recheck_due(").expect("settle asks"); + assert!(settle[at..].contains("recheck::start(")); + // The step resumes at the checks, and their results from other code + // don't stand on an unchanged head. + let m = include_str!("../mod.rs"); + let re = fn_src(m, "\npub(crate) async fn recheck_at_checks("); + assert!(re.contains("steps::Gate::Checks")); + let rp = fn_src(m, "\nasync fn run_passes("); + assert!(rp.contains("for_checks_version(proof::checks_version())")); +} + +#[test] +fn results_other_code_wrote_run_again_once_and_keep_their_rounds() { + let mut l = Ledger::default(); + for r in [&mut l.rules, &mut l.links, &mut l.test_fix, &mut l.proof] { + r.head = "eeeb43e".into(); + r.rounds = 2; + } + assert!(l.for_checks_version("v2")); + assert!(!l.rules.unchanged("eeeb43e")); + assert!(!l.links.unchanged("eeeb43e")); + assert!(!l.test_fix.unchanged("eeeb43e")); + assert_eq!(l.rules.rounds, 2, "the rounds a run had still count"); + // The proof check's gaps are never a check the change didn't pass. + assert!(l.proof.unchanged("eeeb43e")); + // The same code again: its results stand. + l.rules.head = "eeeb43e".into(); + assert!(!l.for_checks_version("v2")); + assert!(l.rules.unchanged("eeeb43e")); +} + +#[test] +fn the_step_is_rebuilt_from_the_run_record() { + let s = |v: &str| AttributeValue::S(v.into()); + let n = |v: u64| AttributeValue::N(v.to_string()); + let item: HashMap = [ + ("team_id", s("TEAM#t")), + ("run_id", s("R1")), + ("repo", s("o/web")), + ("branch", s("coderhelm/gh-41")), + ("base_branch", s("coderhelm/gh-40")), + ("installation_id", n(7)), + ("ticket_source", s("jira")), + ("ticket_id", s("GH-41")), + ("ticket_body", s("Add a Title Size setting.")), + ("title", s("Title Size")), + ("run_step", n(5)), + ("requester_key", s("email:a@example.com")), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(); + let (msg, branch) = recheck::message_of(&item).expect("a step"); + assert_eq!(branch, "coderhelm/gh-41"); + assert_eq!( + (msg.repo_owner.as_str(), msg.repo_name.as_str()), + ("o", "web") + ); + assert_eq!( + msg.base_branch, "coderhelm/gh-40", + "the stacked base is kept" + ); + assert_eq!(msg.continuation_run_id.as_deref(), Some("R1")); + // The run's last step was 5: the next message is step 6, the same run. + let next = crate::passes::steps::next_message(&msg, "R1", 1); + assert_eq!(crate::passes::steps::step_number(next.continuation), 6); + assert!(next.same_run()); + + // No branch: nothing to check again. + let mut none = item.clone(); + none.remove("branch"); + assert!(recheck::message_of(&none).is_none()); + + // Security: an audit that passed needs no second run; one with items does. + assert!(recheck::carry_of("## Summary\nx").is_some()); + assert!(recheck::carry_of(&format!("- x {}", proof::SECURITY_MARK)).is_none()); +} + +#[test] +fn a_dip_coderhelm_caused_and_its_return_are_not_progress() { + // The incident's counts: 37 at the end of a step, 23 after the rebuild + // at the start of the next, 37 again with nothing written. + let mut g = GuardState::default(); + assert!(g.apply(&Progress::TasksDone(37))); + for _ in 0..8 { + g.on_continuation(1.0); + assert!(!g.apply(&Progress::TasksDone(23))); + assert!( + !g.apply(&Progress::TasksDone(37)), + "a return with nothing written is not progress" + ); + } + assert_eq!(g.trip(), Some(Trip::Continuations)); + + // Someone else moved the base and the run's coder redoes the work: that + // is progress, still a bounded number of times. + let mut g = GuardState::default(); + assert!(g.apply(&Progress::TasksDone(37))); + g.on_continuation(1.0); + assert!(!g.apply(&Progress::TasksDone(23))); + g.on_own_code(); + assert!(g.apply(&Progress::TasksDone(30))); + assert_eq!(g.continuations, 0); + + // The coder writing is reported from the one place every round writes, + // and the plan check at a step's start measures with the stacked base. + let imp = include_str!("../implement.rs"); + assert!(imp.contains("run_guard::wrote_code(")); + let m = include_str!("../mod.rs"); + let cf = fn_src(m, "\nasync fn continuation_feedback("); + assert!(cf.contains("plan_coverage::plan_changes(")); + assert!(!cf.contains("plan_coverage::coverage(")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 2f5137c2b..6b868f5cb 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1118,6 +1118,7 @@ mod proof; pub mod quarantine; /// Whether a finished run's pull request leaves draft, decided in one place. pub mod ready; +pub mod recheck; pub mod relay_retry; pub mod release_notes; pub mod release_plan; @@ -3530,6 +3531,13 @@ async fn run_passes( run_guard::LedgerCell::new(&checks_scope, Default::default()) }; ledger.update(|l| l.on_step_start()); + // Results another version of the checks wrote run again on this head. + if ledger.update(|l| l.for_checks_version(proof::checks_version())) { + info!( + run_id, + "The checks' code changed since their last results: they run again" + ); + } if let Some((remembered, _)) = &continue_in { ledger.update(|l| l.covering = Some(remembered.clone())); } @@ -6527,6 +6535,70 @@ async fn hand_off_at( } } +/// A finished run's checks, again, in a fresh step of the run that resumes +/// at [`steps::Gate::Checks`] on its open pull request (see `recheck`): +/// the checks run on the head and the Open items are written from what they +/// find now. `msg` is the run's last step's message. It is not a +/// continuation of work that stalled, so the step guard starts fresh and +/// the run guard doesn't count it; the team's usage limit and the runaway +/// ceiling still stop it. +pub(crate) async fn recheck_at_checks( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + branch: &str, + carry: Option<&steps::Carry>, + why: &str, +) -> Handoff { + if branch.is_empty() { + return Handoff::Stopped("the run has no branch".into()); + } + if state.config.ticket_queue_url.is_empty() { + return Handoff::Stopped("no queue to continue on".into()); + } + if let Some(reason) = check_budget_exceeded(state, &msg.team_id).await { + return Handoff::Stopped(reason); + } + if !steps::under_ceiling(msg.continuation) { + return Handoff::Stopped(format!( + "the run reached the safety ceiling of {} steps", + steps::MAX_RUN_STEPS + )); + } + save_checkpoint( + state, + &msg.team_id, + run_id, + "implement", + branch, + 0, + &TokenUsage::default(), + ) + .await; + steps::save_gate(state, &msg.team_id, run_id, steps::Gate::Checks, carry).await; + // New code checking the same head is not a step that made no progress. + steps::save_mark(state, &msg.team_id, run_id, "", 0, 0).await; + let now_ms = chrono::Utc::now().timestamp_millis().max(0) as u64; + let next = steps::next_message(msg, run_id, now_ms); + let step = steps::step_number(next.continuation); + if !send_ticket_after(state, &next, steps::STEP_DELAY_SECS as u64).await { + return Handoff::Stopped("the step couldn't be queued".into()); + } + info!( + run_id, + step, "Checking the pull request again in a fresh step" + ); + add_progress_note( + state, + &msg.team_id, + run_id, + &format!("{why}: checking it again in step {step}"), + ) + .await; + steps::mark_queued(state, &msg.team_id, run_id, step).await; + Handoff::Continued +} + /// For a step resuming at a gate: the optional tasks the plan check left /// out, read again from the branch (they go in the PR's Open items). async fn resumed_optional( @@ -6630,7 +6702,12 @@ async fn continuation_feedback( if tasks.is_empty() { return None; } - let changed = plan_coverage::changed_files( + // The same measure as every other plan check (`close_gaps`): a branch + // stacked on another pull request's branch has the files that branch + // changes done there. Measured on the branch's own diff alone, a stacked + // run read 23 of 38 tasks at the start of every step and 37 of 38 after + // it, and told its coder 14 tasks were missing that weren't. + let changes = plan_coverage::plan_changes( github, &msg.repo_owner, &msg.repo_name, @@ -6638,7 +6715,7 @@ async fn continuation_feedback( branch, ) .await?; - let cov = plan_coverage::coverage(&tasks, &changed); + let cov = changes.coverage(&tasks); run_guard::progress( state, &msg.team_id, @@ -7122,6 +7199,13 @@ async fn run_repo_pipeline( ) .await; ledger.update(|l| l.on_step_start()); + // Results another version of the checks wrote run again on this head. + if ledger.update(|l| l.for_checks_version(proof::checks_version())) { + info!( + run_id, + "The checks' code changed since their last results: they run again" + ); + } let already_open = ledger.update(|l| l.opened.clone()); // --- The draft pull request, before the checks (see the single-repository diff --git a/services/worker/src/passes/plan_coverage.rs b/services/worker/src/passes/plan_coverage.rs index 455bf77ea..ea9b89740 100644 --- a/services/worker/src/passes/plan_coverage.rs +++ b/services/worker/src/passes/plan_coverage.rs @@ -285,7 +285,10 @@ pub fn settle_generated(mut cov: Coverage, settled: &[String]) -> Coverage { /// Each planned task, done when the branch changes its file. Structural, not /// the coder's account: a task whose file the diff doesn't touch is not done -/// whatever the coder's summary says. +/// whatever the coder's summary says. Every plan check in the run measures +/// with [`plan_changes`] (a stacked base adds its changes); this is that +/// measure with no stacked base, kept for the tests. +#[cfg(test)] pub fn coverage(tasks: &[PlanTask], changed: &[String]) -> Coverage { stacked_coverage(tasks, changed, &[]) } diff --git a/services/worker/src/passes/proof.rs b/services/worker/src/passes/proof.rs index dc751d32e..edd82c297 100644 --- a/services/worker/src/passes/proof.rs +++ b/services/worker/src/passes/proof.rs @@ -1356,6 +1356,42 @@ pub fn holds_blocked_on(body: &str, ci_green: bool) -> bool { blocked_lines(body).any(|l| !blocked_line_settled(l, ci_green)) } +/// Around the version of the code that wrote a blocked line, on the line +/// itself: ``. +const CHECKED_BY_START: &str = ""; + +/// The version of the code that runs CoderHelm's checks now: a hash of the +/// worker's and the common crate's sources (see `build.rs`), the same on +/// every install that runs the same code. +pub fn checks_version() -> &'static str { + env!("CODERHELM_CHECKS_VERSION") +} + +/// The mark naming the code version that wrote a blocked line. +pub fn checked_by(version: &str) -> String { + format!("{CHECKED_BY_START}{version}{CHECKED_BY_END}") +} + +/// The code version a blocked line names; `None` for a line written before +/// lines carried one. +pub fn checked_by_of(line: &str) -> Option<&str> { + let at = line.find(CHECKED_BY_START)? + CHECKED_BY_START.len(); + let rest = &line[at..]; + let end = rest.find(CHECKED_BY_END)?; + Some(rest[..end].trim()).filter(|v| !v.is_empty()) +} + +/// Whether a check the change didn't pass still holds the pull request on a +/// line that code other than `version` wrote: the rule that wrote it may +/// have been fixed since, so the hold is checked again on the head (see +/// `ready::settle`). A line with no version was written before lines +/// carried one. +pub fn holds_on_other_version(body: &str, ci_green: bool, version: &str) -> bool { + blocked_lines(body) + .any(|l| !blocked_line_settled(l, ci_green) && checked_by_of(l) != Some(version)) +} + /// Whether the description has a blocked line CI green on the head would /// settle: the decision has to read CI for it. pub fn ci_settles_a_hold(body: &str) -> bool { @@ -1394,7 +1430,11 @@ fn item_line(f: &Finding) -> String { if is_security(f) { format!("{} {SECURITY_MARK}", f.line()) } else if f.point.trim() == "check_blocked" { - format!("{} {BLOCKED_MARK}", f.line()) + format!( + "{} {BLOCKED_MARK} {}", + f.line(), + checked_by(checks_version()) + ) } else { f.line() } diff --git a/services/worker/src/passes/ready.rs b/services/worker/src/passes/ready.rs index e5c713423..dec3964cd 100644 --- a/services/worker/src/passes/ready.rs +++ b/services/worker/src/passes/ready.rs @@ -39,6 +39,12 @@ //! no recorded reason, and decides again: it marks the pull request ready //! or records why not. A person's draft and a closed pull request are //! respected. +//! - A hold is only as current as the code that wrote it. When the pull +//! request is held on a check line other code than the code running now +//! wrote ([`recheck_due`]), the run checks it again on the head in a fresh +//! step (`recheck`), once per code version, and the pull request waits for +//! that instead of staying held on the old line. What the checks find then +//! decides, here, as always. use std::collections::HashMap; @@ -296,6 +302,21 @@ pub fn decide(f: &Facts) -> Decision { Decision::Ready { open } } +/// Whether a held pull request is checked again before its hold is +/// recorded: a check line written by code other than `version` holds it +/// (see `recheck`). Never for a pull request a person put back to draft, or +/// one that isn't held. +pub fn recheck_due(f: &Facts, d: &Decision, version: &str) -> bool { + matches!(d, Decision::Held { .. }) + && f.draft + && !f.closed + && f.put_back_by.is_none() + && super::proof::holds_on_other_version(&f.body, f.ci.green, version) +} + +/// What the description says while the checks run again. +pub const RECHECK_WHY: &str = "CoderHelm's checks run again on this head: the check listed under Open items was written by an earlier version of them"; + /// The description's draft status for a decision; empty when it is ready. pub fn status_section(d: &Decision) -> String { match d { @@ -466,6 +487,8 @@ pub enum Outcome { Ready, Held, Waiting, + /// Held on a check older code wrote: the run checks it again. + Rechecking, Closed, /// Sent again for later (GitHub refused for a while). Retrying, @@ -516,6 +539,34 @@ pub async fn settle(ctx: &Ctx<'_>) -> Outcome { record_settled(ctx.state, ctx.team_id, &run_id, "ready").await; Outcome::Ready } + Decision::Held { .. } + if recheck_due(&facts, &decision, super::proof::checks_version()) + && super::recheck::start( + ctx.state, + ctx.team_id, + &run_id, + ctx.pr, + &facts.body, + super::proof::checks_version(), + ) + .await => + { + info!(pr = ctx.pr, run_id = %run_id, "The PR's hold was written by older checks: checking it again"); + let wait = Decision::Wait { + why: RECHECK_WHY.to_string(), + until: None, + }; + write_body(ctx, &facts.body, &wait).await; + if let Some(h) = DraftHold::new( + Kind::Waiting, + vec![Reason::new(RECHECK_WHY, "")], + ctx.pr, + &pr_url, + ) { + record_hold(ctx.state, ctx.team_id, &run_id, h).await; + } + Outcome::Rechecking + } Decision::Held { reasons } => { let lines: Vec = reasons.iter().map(Reason::line).collect(); warn!(pr = ctx.pr, run_id = %run_id, reasons = ?lines, "The PR stays a draft"); diff --git a/services/worker/src/passes/recheck.rs b/services/worker/src/passes/recheck.rs new file mode 100644 index 000000000..452300a08 --- /dev/null +++ b/services/worker/src/passes/recheck.rs @@ -0,0 +1,226 @@ +//! A hold CoderHelm's own checks wrote is checked again when their code +//! changes. +//! +//! A run finished and its pull request stayed a draft: a line under Open +//! items said a check the change didn't pass, written by a rule that was +//! wrong. The rule was fixed, but the line was text in the description and +//! nothing ran the check again, so the pull request stayed held until a +//! person edited the description. +//! +//! The rules: +//! +//! - Every blocked line names the version of the code that wrote it +//! (`proof::checked_by`). A line with no version was written before lines +//! carried one. +//! - When `ready::settle` finds the pull request held on such a line written +//! by other code than the code running now, it queues a fresh step of the +//! run that resumes at the checks on the open pull request +//! (`recheck_at_checks`). The checks whose failure is a hold run again on +//! the head even if it didn't move (`run_guard::Ledger::for_checks_version`), +//! the Open items are written from what they find, and the run finishes as +//! any run does: `settle` marks the pull request ready or records the holds +//! that are still true. +//! - Once per run and code version, recorded on the run (`recheck_version`) +//! in the same write that claims it, so two deciders can't both start it +//! and a check that still fails on new code never loops. +//! - Not for a run the run guard stopped (a person has it), a pull request a +//! person put back to draft, or a closed one. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use tracing::{info, warn}; + +use super::{attr_s, steps}; +use crate::models::{TicketMessage, TicketSource}; +use crate::WorkerState; + +/// The run's last step's message, rebuilt from its record, with the branch +/// the run works on. `None` when the record lacks what a step needs. +pub fn message_of(item: &HashMap) -> Option<(TicketMessage, String)> { + let s = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let n = |k: &str| { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse::().ok()) + .unwrap_or(0) + }; + let (owner, name) = s("repo") + .split_once('/') + .map(|(a, b)| (a.to_string(), b.to_string()))?; + let branch = s("branch"); + let installation_id = n("installation_id"); + if owner.is_empty() || name.is_empty() || branch.is_empty() || installation_id == 0 { + return None; + } + let source = match s("ticket_source").as_str() { + "jira" => TicketSource::Jira, + "alert" => TicketSource::Alert, + _ => TicketSource::Github, + }; + let requester = Some(s("requester_key")) + .filter(|k| !k.is_empty()) + .map(|key| common::requester::Requester { + key, + name: s("requester_name"), + email: s("requester_email"), + }); + let base_branch = Some(s("base_branch")).filter(|b| !b.is_empty()); + // The step after the run's last one (`run_step`, from 1). + let last_step = n("run_step").max(1) as u32; + let mut msg = TicketMessage { + team_id: s("team_id"), + installation_id, + source, + ticket_id: s("ticket_id"), + title: s("title"), + body: s("ticket_body"), + repo_owner: owner, + repo_name: name, + issue_number: n("issue_number"), + sender: s("sender"), + requester, + image_attachments: item + .get("image_attachments") + .and_then(|v| v.as_s().ok()) + .and_then(|j| serde_json::from_str(j).ok()) + .unwrap_or_default(), + continuation: last_step - 1, + continuation_run_id: Some(s("run_id")).filter(|r| !r.is_empty()), + ..Default::default() + }; + if let Some(b) = base_branch { + msg.base_branch = b; + } + (!msg.team_id.is_empty() && msg.continuation_run_id.is_some()).then_some((msg, branch)) +} + +/// What the stages the step skips carried: a description with no security +/// item had its security audit pass (each finding, or an audit that didn't +/// run, is an item the pull request stays a draft on). With one, the audit +/// runs again in the step. +pub fn carry_of(body: &str) -> Option { + (!super::proof::holds_security_items(body)).then(|| steps::Carry { + security: super::security::Verdict::Passed, + security_round: None, + generated: Vec::new(), + }) +} + +/// Claims the check again for `version`: true for the one decider that may +/// start it. Never for a run the guard stopped or one not finished. +async fn claim(state: &WorkerState, team_id: &str, run_id: &str, version: &str) -> bool { + let res = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET recheck_version = :v, recheck_at = :t") + .condition_expression( + "attribute_exists(run_id) AND attribute_not_exists(guard_open) \ + AND #s IN (:done, :old_done, :held) \ + AND (attribute_not_exists(recheck_version) OR recheck_version <> :v)", + ) + .expression_attribute_names("#s", "status") + .expression_attribute_values(":v", attr_s(version)) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .expression_attribute_values(":done", attr_s(common::run_status::COMPLETED)) + .expression_attribute_values(":old_done", attr_s(common::run_status::SUCCESS)) + // A condition value only, never a status written here. + .expression_attribute_values( + ":held", + AttributeValue::S(common::run_status::NEEDS_INPUT.to_string()), + ) + .send() + .await; + match res { + Ok(_) => true, + Err(e) => { + if !format!("{e:?}").contains("ConditionalCheckFailed") { + warn!(run_id, error = %e, "Could not claim checking the pull request again"); + } + false + } + } +} + +/// The claim given back when the step couldn't be queued: the next decision +/// tries again. +async fn release(state: &WorkerState, team_id: &str, run_id: &str, version: &str) { + 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("REMOVE recheck_version, recheck_at") + .condition_expression("recheck_version = :v") + .expression_attribute_values(":v", attr_s(version)) + .send() + .await; +} + +/// Starts checking a held pull request again with the code running now +/// (see the module's rules). True when a step is queued: the pull request +/// waits for it instead of staying held on the old line. +pub async fn start( + state: &WorkerState, + team_id: &str, + run_id: &str, + pr: u64, + body: &str, + version: &str, +) -> bool { + if run_id.is_empty() || version.is_empty() { + return false; + } + 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)) + .consistent_read(true) + .send() + .await + { + Ok(o) => o.item.unwrap_or_default(), + Err(e) => { + warn!(run_id, error = %e, "Could not read the run to check its pull request again"); + return false; + } + }; + let Some((msg, branch)) = message_of(&item) else { + warn!( + run_id, + pr, "The run's record lacks what a fresh step needs: its hold stays as written" + ); + return false; + }; + if !claim(state, team_id, run_id, version).await { + return false; + } + let why = "The check that holds this pull request was written by an earlier version of \ + CoderHelm's checks"; + match super::recheck_at_checks(state, &msg, run_id, &branch, carry_of(body).as_ref(), why).await + { + super::Handoff::Continued => { + info!( + run_id, + pr, version, "Checking the held pull request again with the checks' new code" + ); + true + } + super::Handoff::Stopped(reason) => { + warn!(run_id, pr, reason = %reason, "Could not check the held pull request again"); + release(state, team_id, run_id, version).await; + false + } + } +} diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index e94377dae..7e20b08d6 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -203,6 +203,13 @@ pub struct GuardState { /// How many times the count fell below the one before it. #[serde(default)] pub task_drops: u32, + /// The run's coder wrote code since the count last fell. Only then is a + /// recovery the run's own work done again: a count that falls and comes + /// back with nothing written moved because of what CoderHelm did to the + /// branch or measured it against (a rebuild, a rebase, another base), not + /// because the run did anything. + #[serde(default)] + pub wrote_since_fall: bool, #[serde(default)] pub work_done: bool, #[serde(default)] @@ -239,15 +246,22 @@ impl GuardState { let prev = self.tasks_last.unwrap_or(self.tasks_done); if n < prev { self.task_drops = self.task_drops.saturating_add(1); + self.wrote_since_fall = false; } self.tasks_last = Some(n); let more = n > self.tasks_done; - // Work the count lost (the base moved, a rebuild, a revert) - // being done again is progress, not a repeat of old news: - // measured from the last count, a bounded number of times so - // a count that keeps falling and rising still ends. - let recovered = - !more && n > prev && self.task_drops > 0 && self.task_drops <= MAX_TASK_DROPS; + // Work the count lost (someone else moved the base, a revert) + // done again by the run is progress, not a repeat of old + // news: measured from the last count, only when the run wrote + // code since the fall (CoderHelm's own rebuild or rebase of + // the branch, undone by measuring again, is nothing the run + // did), and a bounded number of times so a count that keeps + // falling and rising still ends. + let recovered = !more + && n > prev + && self.wrote_since_fall + && self.task_drops > 0 + && self.task_drops <= MAX_TASK_DROPS; self.tasks_done = self.tasks_done.max(n); more || recovered } @@ -273,6 +287,12 @@ impl GuardState { real } + /// The run's coder wrote code (`implement::run` changed files). Not + /// progress by itself: a commit never is. + pub fn on_own_code(&mut self) { + self.wrote_since_fall = true; + } + fn reset(&mut self) { self.transitions = 0; self.continuations = 0; @@ -603,6 +623,19 @@ pub async fn progress(state: &WorkerState, team_id: &str, run_id: &str, p: Progr save(state, team_id, run_id, &l.guard, 0, 0, spent).await; } +/// The run's coder wrote code: a fall in the plan check's count after this +/// and its recovery can be the run's own work (see [`GuardState::apply`]). +pub async fn wrote_code(state: &WorkerState, team_id: &str, run_id: &str) { + let Some(mut l) = load(state, team_id, run_id).await else { + return; + }; + if l.guard.wrote_since_fall { + return; + } + l.guard.on_own_code(); + save(state, team_id, run_id, &l.guard, 0, 0, 0.0).await; +} + /// A person acted on the run (a comment, a review): the counts start over and /// an earlier stop no longer holds it. `loop_stop_reason` stays, for analytics. pub async fn person_acted(state: &WorkerState, team_id: &str, run_id: &str) { @@ -939,6 +972,11 @@ pub struct Ledger { /// (`covering`). #[serde(default)] pub covering: Option, + /// The version of the code whose checks wrote the results above + /// (`proof::checks_version`); empty for a ledger written before it was + /// kept. + #[serde(default)] + pub checks_version: String, } /// A record larger than this drops its longest text: DynamoDB's item limit is @@ -964,6 +1002,26 @@ impl Ledger { } } + /// The checks run by code at `version`. A result another version wrote + /// doesn't stand on an unchanged head for the checks whose failure is a + /// hold (the link and redirect check, the failing-test rules, the + /// new-feature rules): the rule that failed may be fixed now, so they run + /// again. Their fix rounds still count. The proof check's result stands: + /// what it leaves is never a check the change didn't pass. True when the + /// results were set aside. + pub fn for_checks_version(&mut self, version: &str) -> bool { + if self.checks_version == version { + return false; + } + self.checks_version = version.to_string(); + let mut set_aside = false; + for r in [&mut self.rules, &mut self.links, &mut self.test_fix] { + set_aside |= !r.head.is_empty(); + r.head.clear(); + } + set_aside + } + /// What is still open, for a run the guard stopped. Honest about both: /// what the checks found, and what they didn't get to. pub fn open_findings(&self) -> Vec {