diff --git a/docs/incidents.md b/docs/incidents.md index 8e39690db..0ffbe5dfb 100644 --- a/docs/incidents.md +++ b/docs/incidents.md @@ -41,6 +41,7 @@ pipeline still calls it there. | i. `i_finished_work_pr` | A run with one planned task left ended with no pull request. Later the run opened a draft but left the work to a person. | Finished work always ends with a pull request. Planned work that is still open puts a draft PR up with a "Not finished" section. CoderHelm then keeps working those tasks in rounds on the PR and marks it ready when the section is empty. It stops only after two rounds in a row without progress. It then names the tasks and why, and sets the run to `needs_input`, never `completed`. | | j. `j_post_merge_watch` | After an auto-merge, the health check gave up after about 22 minutes and posted "inconclusive" while the deploy was still running. It read the base branch, so later merges kept checks running and could put another commit's deploy in the verdict. | The check judges the merge commit's own check runs and push workflow runs, and waits as long as they run, each look a new queue message. It posts a verdict only: green after a 15-minute window that starts when the deploy completes, or red naming each new failing job with its link. Baseline failures are ignored, later commits never change the verdict, and a superseded deploy is followed to the run that includes the commit. One comment per merge, edited in place. A deploy held for an environment approval is not stuck: the comment reports what finished and names the job waiting for approval, in which environment, with a link, and is updated once the approved deploy finishes; the safety ceiling does not count the wait. A deploy cancelled with no later run is reported as cancelled (yellow), never as a failure. | | k. `k_own_review_findings` | CoderHelm's own review of its own PR posted three findings as notes and APPROVE. Three seconds later the PR was marked ready and the merge armed, with none of the three fixed and no thread resolved. | On its own PR, CoderHelm fixes every finding of its own review that isn't strictly optional (an inferred preference, or an optional improvement to correct code) before the PR is marked ready or the merge armed. The review requests changes and lists them at the top of the description. The run takes them in review-fix rounds, and the next review resolves the threads the new commit settled. It goes on while rounds make progress. Two rounds without progress stop it: the PR stays a draft with the findings listed, and the run is `needs_input`. A verdict is never APPROVE while a finding holds the merge. | +| l. `l_plan_time` | A schedule data fix failed in planning after about 14 minutes: "no work is committed to continue from". It planned, switched repository and planned again, was sent back by a release check that read a column it writes (`updated_at`) as removed and by a demand for production and staging proof its claims never needed, then re-planned a third time for one file tag and ran out of time. | Planning that runs out of time continues in a fresh step at the plan gate, from the repository it settled on, its last plan, its open gaps and its re-plans, and keeps going while each step makes a new plan revision or leaves fewer open gaps. The checks re-plan once in all: a switch plans once, with the file check in that plan's one send-back, and every check's gaps share that one send-back; what is still open stays on the decision. Writing a column is not removing it, and proof for an environment is asked only when the plan's claims rest on that environment's data. | ## Adding a case diff --git a/services/worker/src/passes/incidents/l_plan_time.rs b/services/worker/src/passes/incidents/l_plan_time.rs new file mode 100644 index 000000000..6e36b7bac --- /dev/null +++ b/services/worker/src/passes/incidents/l_plan_time.rs @@ -0,0 +1,239 @@ +//! k. A ticket about a wrong class time (a schedule data fix) failed in the +//! plan pass after about 14 minutes: "The step reached its time limit and +//! the run couldn't continue in a fresh step: no work is committed to +//! continue from." It planned (with two reviewers and a revision), switched +//! repository and planned again there, was told by the release check that +//! "the change removes `updated_at`, which deployed code reads" and by the +//! plan check that production and staging were unproven, and was sent to +//! plan a third time for one file tag that didn't match. The third plan ran +//! out of time, and planning had nothing on a branch to continue from. +//! +//! Guarantee: planning that runs out of time continues in a fresh step at +//! the plan gate, from how far it got (the repository it settled on, its +//! last plan, its open gaps and its re-plans), and keeps going while each +//! step makes a new plan revision or leaves fewer open gaps. The checks +//! re-plan once in all: a repository switch plans once, with the file check +//! in that plan's one send-back, and every check's gaps share that one +//! send-back. A data fix that writes a column (`SET updated_at = now()`) is +//! not a removal, and an environment the plan's claims don't rest on owes +//! no environment-only proof. + +use super::fixture::*; +use crate::models::TicketMessage; +use crate::passes::fix_location::{EnvCheck, FixDecision, FixEvidence}; +use crate::passes::plan::PlanResult; +use crate::passes::release_plan::{self, FieldChange, Mechanics, Release}; +use crate::passes::steps::{self, Gate, PlanState}; +use crate::passes::{plan_judge, ticket_history::TicketHistory}; + +const OLD: &str = "no work is committed to continue from"; + +/// The schedule data fix the planner wrote: one migration that sets the +/// right start time and bumps `updated_at`, with the release block the old +/// check pushed it to write, and both environments listed as unchecked. +fn schedule_fix() -> PlanResult { + PlanResult { + proposal: "Correct the Saturday Speed and Agility class from 9am to 8am.".into(), + design: "A data migration runs UPDATE class_schedule SET start_time = '08:00', \ + updated_at = now() WHERE class_id = 42. No schema change." + .into(), + tasks: "- [ ] src/database/migrations/1783400000000-FixClassTime.ts: [create] Set the \ + class's start time to 08:00 and bump updated_at\n" + .into(), + spec: "Given the class page, the Saturday time reads 8am.".into(), + repo_tasks: vec![], + fix: Some(FixDecision { + cause: "The class is stored with a 9am start; the ticket says 8am.".into(), + evidence: FixEvidence { + data_shows: "class_schedule row 42 has start_time 09:00".into(), + environments: vec![ + EnvCheck { + env: "production".into(), + proof: String::new(), + proven: false, + }, + EnvCheck { + env: "staging".into(), + proof: String::new(), + proven: false, + }, + ], + ..Default::default() + }, + release: Some(Release { + fields: vec![FieldChange { + old: vec!["updated_at".into()], + new: String::new(), + types: vec!["class_schedule".into()], + }], + ..Default::default() + }), + ..Default::default() + }), + } +} + +/// One run's planning steps. `revisions[i]` and `gaps[i]` are how far +/// planning got when step `i + 1` ran out of time (its plan revision and +/// open gaps); the last step finishes planning. +fn plan_steps(revisions: &[u32], gaps: &[usize]) -> (Ending, Vec) { + let mut end = Ending::default(); + let first = TicketMessage { + team_id: "TEAM#1".into(), + ticket_id: TICKET.into(), + repo_owner: OWNER.into(), + repo_name: "web".into(), + ..Default::default() + }; + let mut sent = vec![first.clone()]; + let mut msg = first; + let mut mark: Option = None; + let mut stalled = 0; + let mut ps = PlanState::new(OWNER, "web", BASE); + for (i, (&rev, &g)) in revisions.iter().zip(gaps).enumerate() { + let step = steps::step_number(msg.continuation); + // The step starts: it compares how far planning got with the mark + // of the step before (see `run_passes`). + if msg.continuation > 0 { + stalled = steps::plan_stalled_after(mark.as_deref(), &ps, stalled); + if steps::stops_for_stall(stalled) { + end.said(steps::plan_stall_reason(step, &ps)); + end.status = common::run_status::FAILED.into(); + return (end, sent); + } + mark = Some(ps.mark()); + } + // Step 1 plans in the first repository and switches; the plan made + // there is the switch's one re-plan. + if i == 0 { + ps.switched = true; + ps.replans = 1; + ps.repo = format!("{OWNER}/{REPO}"); + } + ps.revision = rev; + ps.open_gaps = (0..g).map(|n| format!("gap {n}")).collect(); + let last = i + 1 == revisions.len(); + if last { + ps.checked = true; + end.said("Plan generated"); + end.status = common::run_status::RUNNING.into(); + return (end, sent); + } + // Out of time while planning: the checkpoint holds the plan gate. + let st = steps::StepState { + gate: Some(Gate::Plan), + plan: Some(ps.clone()), + ..Default::default() + }; + let planning = st.planning().is_some(); + assert!(planning, "step {step} hands off at the plan gate"); + assert!(steps::under_ceiling(msg.continuation)); + msg = steps::next_message(&msg, "RUN1", 1); + // The next step resumes in the repository planning settled on. + let resumed = steps::StepState { + gate: Some(Gate::Plan), + plan: Some(PlanState::from_json(&ps.to_json()).unwrap()), + ..Default::default() + } + .planning() + .unwrap(); + let (owner, name) = resumed.owner_name().unwrap(); + msg.repo_owner = owner.into(); + msg.repo_name = name.into(); + sent.push(msg.clone()); + end.said(format!( + "This step reached its time limit while planning: continuing in step {} with its own \ + time budget", + steps::step_number(msg.continuation) + )); + } + (end, sent) +} + +#[test] +fn planning_that_runs_out_of_time_continues_at_the_plan_gate() { + // Step 1: two plans (first repository, then the switch) and out of + // time; step 2: the file re-plan's plan, final. + let (end, sent) = plan_steps(&[2, 3], &[2, 0]); + assert_eq!(end.status, common::run_status::RUNNING, "{:?}", end.words); + assert_eq!(sent.len(), 2); + assert_eq!(sent[1].continuation, 1); + assert_eq!(sent[1].continuation_run_id.as_deref(), Some("RUN1")); + assert_eq!( + sent[1].repo_name, REPO, + "resumes in the repository it switched to" + ); + assert!(end.says("while planning: continuing in step 2")); + end.never_says(OLD); + // Fewer open gaps with no new revision is progress too. + let (end, _) = plan_steps(&[2, 2, 2], &[3, 1, 1]); + assert_eq!(end.status, common::run_status::RUNNING, "{:?}", end.words); +} + +#[test] +fn two_planning_steps_without_progress_stop_saying_where() { + let (end, _) = plan_steps(&[2, 2, 2, 2], &[1, 1, 1, 1]); + assert_eq!(end.status, common::run_status::FAILED); + assert!(end.says("made no progress in planning"), "{:?}", end.words); + assert!(end.says(&format!("{OWNER}/{REPO}"))); + end.never_says(OLD); +} + +#[test] +fn the_pipeline_hands_planning_off_and_bounds_the_replans() { + let src = include_str!("../mod.rs"); + // The timeout continues a run at the plan gate with nothing committed. + let cont = fn_src(src, "\nasync fn try_auto_continue("); + assert!(cont.contains("let has_partial = planning")); + let orch = fn_src(src, "\npub async fn orchestrate_ticket("); + let timeout = orch + .find("Orchestration timed out — Lambda limit approaching") + .unwrap(); + let arm = &orch[timeout..]; + assert!(arm.contains(".planning()")); + assert!(arm.contains("This step reached its time limit while planning")); + // Planning saves how far it got, and resumes from it. + let rp = run_passes_src(); + assert!(rp.contains("steps::load(state, &msg.team_id, run_id).await")); + assert!(rp.contains("steps::plan_stalled_after(")); + assert!(rp.matches("steps::save_plan(").count() >= 5); + // A switch is refused once planning switched or used its re-plan; a + // file mismatch re-plans only while one is left; both later plans + // check their files in their one send-back. + assert!(rp.contains(".filter(|_| ps.switched || !ps.may_replan())")); + assert!(rp.contains("&& ps.may_replan()")); + assert_eq!(steps::MAX_PLAN_REPLANS, 1); + let mut p = PlanState::new(OWNER, REPO, BASE); + p.switched = true; + p.replans = 1; + assert!(!p.may_replan(), "the switch used the one re-plan"); + let plan = include_str!("../plan.rs"); + let run = fn_src(plan, "\npub async fn run("); + let files = run.find("super::plan_file_gaps(").unwrap(); + let send_back = run.find("super::fix_location::send_back(&back)").unwrap(); + assert!(files < send_back, "file gaps join the one send-back"); +} + +#[test] +fn a_schedule_data_fix_owes_no_release_split_and_no_environment_proof() { + let plan = schedule_fix(); + let g = release_plan::plan_gaps(&plan, &Mechanics::default()); + assert!( + !g.iter().any(|x| x.contains("removes `updated_at`")), + "{g:?}" + ); + assert!( + !g.iter().any(|x| x.contains("Plan two migrations")), + "{g:?}" + ); + // No release at all: a data migration that removes nothing needs none. + let mut bare = schedule_fix(); + bare.fix.as_mut().unwrap().release = None; + assert!(release_plan::plan_gaps(&bare, &Mechanics::default()).is_empty()); + // Its claims are about one stored row, not an environment. + let found = plan_judge::structural(&plan, &TicketHistory::default(), true); + assert!( + !found.iter().any(|f| f.point == "env_unproven"), + "{found:?}" + ); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs index 085924f84..6a19c45f1 100644 --- a/services/worker/src/passes/incidents/mod.rs +++ b/services/worker/src/passes/incidents/mod.rs @@ -26,3 +26,4 @@ mod h_pr_updates; mod i_finished_work_pr; mod j_post_merge_watch; mod k_own_review_findings; +mod l_plan_time; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 5a8d1576b..9725d4495 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -138,6 +138,7 @@ async fn try_auto_continue( run_id: &str, checkpoint: &Option<(String, String, u8)>, continuable_passes: &[&str], + planning: bool, why: &str, ) -> Handoff { // Gate on the checkpoint's pass IDENTITY, not just on there being a branch. @@ -146,7 +147,10 @@ async fn try_auto_continue( // ["implement_started"] so a step-limit raised by some OTHER pass sharing the // agent loop (security/test) can never resume from a stale implement // checkpoint. Callers own this invariant; don't widen it here. - let has_partial = matches!(checkpoint, Some((lp, br, _)) + // Planning commits nothing, so it continues from its own state on the + // checkpoint instead (`planning`: the run is at `steps::Gate::Plan`). + let has_partial = planning + || matches!(checkpoint, Some((lp, br, _)) if !br.is_empty() && continuable_passes.contains(&lp.as_str())); if !has_partial { return Handoff::Stopped("no work is committed to continue from".into()); @@ -1037,6 +1041,7 @@ pub async fn orchestrate_ticket( &run_id, &checkpoint, &["implement_started"], + false, "The coder used this step's turns with work left", ) .await @@ -1131,6 +1136,12 @@ pub async fn orchestrate_ticket( ); let checkpoint = load_checkpoint(state, &msg.team_id, &run_id).await; + // A step that ran out of time while planning continues planning + // in the next step from how far it got (see `steps::PlanState`). + let planning = steps::load(state, &msg.team_id, &run_id) + .await + .planning() + .is_some(); // Prefer AUTO-CONTINUATION over a partial PR: re-enqueue to resume // from the already-committed partial work (bounded — see helper). A @@ -1142,7 +1153,12 @@ pub async fn orchestrate_ticket( &run_id, &checkpoint, &["implement", "implement_started", "security"], - "This step reached its time limit with work left", + planning, + if planning { + "This step reached its time limit while planning" + } else { + "This step reached its time limit with work left" + }, ) .await; @@ -1259,6 +1275,49 @@ async fn run_passes( ); } + // --- Planning that ran out of time continues here --- + // A step that handed off while planning (see `steps::PlanState`) + // resumes in the repository planning settled on, from its last plan. It + // first checks that the step before made progress: a new plan revision + // or fewer open gaps; two steps in a row without stop the run. + let plan_resume = if msg.continuation > 0 || msg.model_retries > 0 { + let st = steps::load(state, &msg.team_id, run_id).await; + let resume = st.planning(); + let step = steps::step_number(msg.continuation); + if let Some(ps) = resume + .as_ref() + .filter(|_| msg.continuation > 0 && st.mark_step != step) + { + let stalled = steps::plan_stalled_after(st.mark.as_deref(), ps, st.stalled); + steps::save_mark(state, &msg.team_id, run_id, &ps.mark(), stalled, step).await; + if steps::stops_for_stall(stalled) { + return Err(steps::plan_stall_reason(step, ps).into()); + } + info!( + run_id, + step, + stalled, + revision = ps.revision, + gaps = ps.open_gaps.len(), + "Continuing planning in this step" + ); + } + resume + } else { + None + }; + if let Some(ps) = plan_resume.as_ref() { + if let Some((owner, name)) = ps.owner_name() { + if owner != msg.repo_owner || name != msg.repo_name { + msg.repo_owner = owner.to_string(); + msg.repo_name = name.to_string(); + if !ps.base_branch.is_empty() { + msg.base_branch = ps.base_branch.clone(); + } + } + } + } + // Load team's Anthropic API key (required). Every agent loop in the run // is gated for this run, its repository and the person who asked. let provider = crate::agent::provider::ModelProvider::load_for_team( @@ -1775,10 +1834,17 @@ async fn run_passes( None }; let resumed_plan = own_plan.is_some(); + // Planning that ran out of time before its first plan keeps this run's + // own triage (and what it resolved and recalled). + let own_triage = if own_plan.is_none() && plan_resume.is_some() { + load_run_triage(state, msg, run_id).await + } else { + None + }; let mut used_mcp_ids: Vec = Vec::new(); - let (mut triage_result, own_plan) = match own_plan { - Some(saved) => { + let (mut triage_result, own_plan) = match (own_plan, own_triage) { + (Some(saved), _) => { info!( run_id, "Continuation: reusing this run's own triage and plan" @@ -1793,7 +1859,22 @@ async fn run_passes( used_mcp_ids = saved.used_mcp_ids; (saved.triage, Some(saved.plan)) } - None => { + (None, Some(saved)) => { + info!( + run_id, + "Continuation: planning again from this run's own triage" + ); + add_progress_note( + state, + &msg.team_id, + run_id, + "Continued planning with this run's own triage", + ) + .await; + used_mcp_ids = saved.used_mcp_ids; + (saved.triage, None) + } + (None, None) => { // --- Pass 1: Triage --- check_cancelled(state, &msg.team_id, run_id).await?; update_pass(state, &msg.team_id, run_id, "triage").await?; @@ -1891,7 +1972,7 @@ async fn run_passes( } // --- Existing work: an open pull request (anyone's) that already fixes // this ends the run as covered by it, before any work starts --- - if !resumed_plan { + if !resumed_plan && plan_resume.is_none() { let (tests, specs, failure) = existing_work_inputs(test_ev.as_ref()); if let Some(covered) = stop_gate::existing_work( state, @@ -1919,6 +2000,20 @@ async fn run_passes( // --- Pass 2: Plan --- check_cancelled(state, &msg.team_id, run_id).await?; update_pass(state, &msg.team_id, run_id, "plan").await?; + // How far planning got: saved from here on, so a step that runs out of + // time while planning continues in a fresh step (see `steps::Gate::Plan`) + // instead of failing with nothing committed. A continuation past + // planning (its own plan, no planning state) has a final plan. + let plan_final = resumed_plan && plan_resume.as_ref().is_none_or(|p| p.checked); + let mut ps = plan_resume.clone().unwrap_or_else(|| { + steps::PlanState::new(&msg.repo_owner, &msg.repo_name, &msg.base_branch) + }); + if !plan_final { + steps::save_plan(state, &msg.team_id, run_id, &ps).await; + } + // A plan made in a repository that is already settled (after a switch) + // checks its files in its own one send-back. + let settled_repo = ps.switched; let pass_start = std::time::Instant::now(); let usage_before = usage.clone(); @@ -2056,6 +2151,7 @@ async fn run_passes( usage, run_id, &history, + settled_repo, ) .await? } @@ -2070,6 +2166,7 @@ async fn run_passes( usage, run_id, &history, + settled_repo, ) .await? }; @@ -2091,6 +2188,12 @@ async fn run_passes( save_checkpoint(state, &msg.team_id, run_id, "plan", "", 0, usage).await; add_progress_note(state, &msg.team_id, run_id, "Plan generated").await; } + if !plan_final { + if !plan_was_reused { + ps.planned(&open_gaps_of(&plan_result)); + } + steps::save_plan(state, &msg.team_id, run_id, &ps).await; + } info!(run_id, "Plan complete"); update_progress_comment( &github, @@ -2107,9 +2210,14 @@ async fn run_passes( // one) is planned again in the right repo before its decision counts or // a branch is made; a plan naming files that don't exist is planned // again once, and never implemented while they still don't. - // A continuation's plan passed this check when the run first made it. + // A continuation's plan passed this check when the run first made it + // (unless the run handed off while planning: then the checks it hadn't + // done yet run now). The checks re-plan at most once in all + // (`steps::MAX_PLAN_REPLANS`): a switch plans once in the new repository, + // with the file check in that plan's one send-back, and a file mismatch + // plans once more only when no switch did. let mut early_validation: Option = None; - if !resumed_plan && !plan_result.tasks.trim().is_empty() { + if !plan_final && !plan_result.tasks.trim().is_empty() { let team_repos = plan::fetch_team_repos(state, &msg.team_id).await; let mut v = validate_plan( &plan_result, @@ -2124,8 +2232,19 @@ async fn run_passes( usage, ) .await; - if let Some(better_repo) = v.switch_repo.take() { + let switch_to = v.switch_repo.take(); + if let Some(again) = switch_to + .as_ref() + .filter(|_| ps.switched || !ps.may_replan()) + { + warn!(run_id, suggested = %again, "Repo check suggests switching again — staying"); + } else if let Some(better_repo) = switch_to { if switch_run_repo(state, msg, run_id, &github, &better_repo, &v.switch_reason).await { + ps.switched = true; + ps.replans = ps.replans.saturating_add(1); + ps.repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + ps.base_branch = msg.base_branch.clone(); + steps::save_plan(state, &msg.team_id, run_id, &ps).await; plan_was_reused = false; // The repo the run uses now is the one CoderHelm picked; a // note naming the repo it left would point people at the @@ -2181,8 +2300,11 @@ async fn run_passes( usage, run_id, &history, + true, ) .await?; + ps.planned(&open_gaps_of(&plan_result)); + steps::save_plan(state, &msg.team_id, run_id, &ps).await; v = validate_plan( &plan_result, &github, @@ -2207,7 +2329,8 @@ async fn run_passes( fix_location::route_for_plan(plan_result.fix.as_ref(), &plan_result.tasks), fix_location::Route::Code | fix_location::Route::CodeAndOutside ); - if codes && (!v.missing_files.is_empty() || !v.file_problems.is_empty()) { + if codes && (!v.missing_files.is_empty() || !v.file_problems.is_empty()) && ps.may_replan() + { info!( run_id, missing = ?v.missing_files, @@ -2243,8 +2366,14 @@ async fn run_passes( usage, run_id, &history, + true, ) .await?; + // Counted once it finished: a step that runs out of time during + // it resumes by making this re-plan, not by skipping it. + ps.replans = ps.replans.saturating_add(1); + ps.planned(&open_gaps_of(&plan_result)); + steps::save_plan(state, &msg.team_id, run_id, &ps).await; restore_plan_hash(state, msg, &context_hash).await; v = validate_plan( &plan_result, @@ -2260,47 +2389,56 @@ async fn run_passes( ) .await; v.switch_repo = None; - if !v.missing_files.is_empty() || !v.file_problems.is_empty() { - warn!(run_id, missing = ?v.missing_files, tags = ?v.file_problems, "Plan still names files that don't match the repository — not implementing"); - let decision = fix_location::FixDecision { - fix_location: fix_location::FixLocation::Unknown, - cause: format!( - "The plan for this ticket names files that don't match {}/{} ({}), \ + } + // Files that still don't match after the one re-plan (this check's, + // or the switch's, whose one send-back carried the file check) are + // never implemented. + if codes && (!v.missing_files.is_empty() || !v.file_problems.is_empty()) { + warn!(run_id, missing = ?v.missing_files, tags = ?v.file_problems, "Plan still names files that don't match the repository — not implementing"); + let decision = fix_location::FixDecision { + fix_location: fix_location::FixLocation::Unknown, + cause: format!( + "The plan for this ticket names files that don't match {}/{} ({}), \ even after planning again, so I stopped before changing any code. \ The ticket may belong in another repository.", - msg.repo_owner, - msg.repo_name, - v.missing_files - .iter() - .cloned() - .chain( - v.file_problems - .iter() - .map(feature::plan_files::Problem::line) - ) - .collect::>() - .join(", ") - ), - ..Default::default() - }; - finish_without_code( - state, - msg, - run_id, - &github, - &decision, - fix_location::Route::Ask, - usage, - start, - &used_mcp_ids, - ) - .await; - close_memory(state, agent_memory.take()).await; - return Ok(()); - } + msg.repo_owner, + msg.repo_name, + v.missing_files + .iter() + .cloned() + .chain( + v.file_problems + .iter() + .map(feature::plan_files::Problem::line) + ) + .collect::>() + .join(", ") + ), + ..Default::default() + }; + finish_without_code( + state, + msg, + run_id, + &github, + &decision, + fix_location::Route::Ask, + usage, + start, + &used_mcp_ids, + ) + .await; + close_memory(state, agent_memory.take()).await; + return Ok(()); } early_validation = Some(v); } + if !plan_final { + // The plan is final: a step that runs out of time from here resumes + // from it without checking it again. + ps.checked = true; + steps::save_plan(state, &msg.team_id, run_id, &ps).await; + } // --- Guard: a malformed/truncated plan must not proceed to implement --- // parse_openspec_files returns empty strings for any fence the model @@ -4407,6 +4545,7 @@ async fn run_passes( run_id, &resume_from, &["implement_started"], + false, &format!( "{} planned task(s) not done yet", cov.required_missing().len() @@ -5381,7 +5520,7 @@ async fn hand_off_at( save_checkpoint(state, &msg.team_id, run_id, "implement", branch, 0, usage).await; steps::save_gate(state, &msg.team_id, run_id, gate, carry).await; let from = Some(("implement".to_string(), branch.to_string(), 0u8)); - match try_auto_continue(state, msg, run_id, &from, &["implement"], why).await { + match try_auto_continue(state, msg, run_id, &from, &["implement"], false, why).await { Handoff::Continued => Ok(()), Handoff::Stopped(reason) => { let kept = keep_wip_branch(github, &msg.repo_owner, &msg.repo_name, branch).await; @@ -9271,6 +9410,30 @@ fn plan_task_files(tasks: &str) -> Vec { .collect() } +/// The tasks whose create/modify/delete/replace tag doesn't match the +/// repository, as lines for the plan's one send-back (see `plan::run`). +pub(crate) async fn plan_file_gaps( + github: &GitHubClient, + owner: &str, + repo: &str, + tasks: &str, +) -> Vec { + let planned = feature::plan_files::planned_files(tasks); + let (existing, created) = feature::plan_files::paths_to_look_up(&planned, 10); + let mut exists: HashMap = HashMap::new(); + for path in existing.into_iter().chain(created) { + if exists.contains_key(&path) { + continue; + } + let there = github.read_file(owner, repo, &path, "HEAD").await.is_ok(); + exists.insert(path, there); + } + feature::plan_files::check(&planned, &exists) + .iter() + .map(|p| format!("[files] In {owner}/{repo}: {}", p.line())) + .collect() +} + /// Plan validation — catches bad plans before the expensive Implement pass. /// Uses deterministic checks (file existence, plan-text mentions, task tags) /// plus an LLM repo-fit check as a final safety net. How many files a plan @@ -10030,7 +10193,7 @@ pub(crate) async fn save_checkpoint( if keeps_gate { "" } else { - " REMOVE gate, gate_carry" + " REMOVE gate, gate_carry, plan_state" } ); if let Err(e) = state @@ -10475,14 +10638,31 @@ async fn save_run_triage( } } +/// The plan check's gaps still open on a plan's decision. +fn open_gaps_of(plan: &plan::PlanResult) -> Vec { + plan.fix + .as_ref() + .map(|d| d.open_gaps.clone()) + .unwrap_or_default() +} + +/// This run's own triage, as the run kept it for a continuation. +async fn load_run_triage( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, +) -> Option { + serde_json::from_str( + &read_s3_text(state, &run_triage_key(&msg.team_id, &msg.ticket_id, run_id)).await?, + ) + .ok() +} + /// This run's own triage and plan, when the cached plan files in the run's /// repo were written (or taken up) by this very run. None otherwise: the /// continuation then triages and plans as a fresh run would. async fn load_run_plan(state: &WorkerState, msg: &TicketMessage, run_id: &str) -> Option { - let saved: RunTriage = serde_json::from_str( - &read_s3_text(state, &run_triage_key(&msg.team_id, &msg.ticket_id, run_id)).await?, - ) - .ok()?; + let saved = load_run_triage(state, msg, run_id).await?; let prefix = openspec_prefix( &msg.team_id, &msg.ticket_id, diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 1bfc9be32..79f9472aa 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -152,6 +152,7 @@ pub async fn run( usage: &mut TokenUsage, run_id: &str, ticket_history: &super::ticket_history::TicketHistory, + check_files: bool, ) -> Result> { let intent = triage.intent; // Fetch all enabled repos for this team so the planner can explore cross-repo @@ -780,6 +781,16 @@ Then the ```fix_location.json block described above."#, // triggers, a fallback and its test, counts in every environment. let release_gaps = super::release_plan::plan_gaps(&draft, &abilities.release); back.extend(release_gaps.iter().cloned()); + // The repository's files, once the repository is settled (`check_files`: + // a re-plan after a switch or a file mismatch): a task whose tag doesn't + // match the repository goes back in this same send-back, never in a + // whole plan of its own (a run once planned three times and ran out of + // time, one re-plan per check). + if check_files && !draft.tasks.trim().is_empty() { + back.extend( + super::plan_file_gaps(github, &msg.repo_owner, &msg.repo_name, &draft.tasks).await, + ); + } if !back.is_empty() { info!( ticket_id = %msg.ticket_id, @@ -981,6 +992,12 @@ Then the ```fix_location.json block described above."#, } }); } + // Every check sent its gaps back in the one send-back above; what each + // still finds goes on the decision's open gaps (never another plan), and + // planning moves on. Only the checks' own findings count as open gaps. + if let Some(d) = files.fix.as_mut() { + d.open_gaps.clear(); + } if !note_gaps.is_empty() { let left = super::outside_work::plan_gaps(&files, &abilities); if !left.is_empty() { @@ -1037,6 +1054,9 @@ Then the ```fix_location.json block described above."#, &format!("Plan check (new-feature rules): {}", left.join(" ")), ) .await; + if let Some(d) = files.fix.as_mut() { + d.open_gaps.extend(left); + } } } // What the plan's own check still finds after the send-back stays on @@ -1062,7 +1082,7 @@ Then the ```fix_location.json block described above."#, ) .await; if let Some(d) = files.fix.as_mut() { - d.open_gaps = lines; + d.open_gaps.extend(lines); } } } diff --git a/services/worker/src/passes/plan_judge.rs b/services/worker/src/passes/plan_judge.rs index f2c319f9f..b12cc3e17 100644 --- a/services/worker/src/passes/plan_judge.rs +++ b/services/worker/src/passes/plan_judge.rs @@ -110,6 +110,14 @@ pub fn structural( }; for e in &d.evidence.environments { let env = e.env.trim(); + // Proof is asked for only where the plan's claims rest on that + // environment's data: a plan whose cause and data say nothing about + // `production` owes no production-only proof just because a source + // is connected (a schedule data fix was once sent back for proof + // in production and staging it never made a claim about). + if !rests_on_env(d, env) { + continue; + } if !e.proven && can_look_up { out.push(PlanFinding::new( "env_unproven", @@ -143,6 +151,39 @@ pub fn structural( out } +/// Whether the decision's claims rest on data from `env`: its cause, what +/// the data shows, the scope it counted or what it looked up name that +/// environment (`prod`, `production` and `live` are one; so are `staging` +/// and `stage`; any other name, an account or a cluster, by its own words). +pub fn rests_on_env(d: &FixDecision, env: &str) -> bool { + let claims = format!( + "{}\n{}\n{}\n{}", + d.cause, + d.evidence.data_shows, + d.evidence.scope, + d.evidence.looked_up.join("\n") + ) + .to_ascii_lowercase(); + let said: Vec<&str> = claims + .split(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '-') + .filter(|w| !w.is_empty()) + .collect(); + let env = env.trim().to_ascii_lowercase(); + if env.is_empty() { + return false; + } + let aliases: &[&str] = match env.as_str() { + "prod" | "production" | "prd" | "live" => &["prod", "production", "prd", "live"], + "staging" | "stage" | "stg" => &["staging", "stage", "stg"], + _ => &[], + }; + if aliases.is_empty() { + said.contains(&env.as_str()) + } else { + said.iter().any(|w| aliases.contains(w)) + } +} + /// Whether a model reading the plan could add anything: there is history to /// build on, or the plan rests on lookups (environments, near matches). pub fn worth_judging(history: &TicketHistory, lookups: usize) -> bool { @@ -158,10 +199,12 @@ pub const SYSTEM: &str = "You check an implementation plan before it is kept. Yo it reuses from them and what changes this time and why; when it says it couldn't find out \ why one was closed while the history lists who closed it and when; or when a review comment \ on one raised something the plan ignores.\n\ - 2. env_unproven: a miss when the plan or its evidence hedges about which environment a \ - lookup hit (it didn't confirm it was production, isn't sure which cluster or account) while \ + 2. env_unproven: only when the plan's claims (its cause, what the data shows, the scope it \ + counted) rest on data from a specific environment. A miss when the plan or its evidence \ + hedges about which environment a lookup hit (it didn't confirm it was production, isn't sure which cluster or account) while \ a connected source could have shown it with data only that environment has. Not a miss when \ - no connected source reaches it and the plan names the missing access.\n\ + no connected source reaches it and the plan names the missing access, and never a miss for a \ + plan whose claims don't depend on which environment the data came from.\n\ 3. near_match_unresolved: a miss when the evidence mentions an existing object close to what \ the ticket names (a similar name, the same purpose) without saying who owns it, what is in \ it and what created it, or without one decisive question for a person about using it \ @@ -368,6 +411,7 @@ mod tests { #[test] fn an_unproven_environment_is_a_gap_only_when_it_could_be_looked_up() { let d = FixDecision { + cause: "The grant exists in staging but not in prod.".into(), evidence: FixEvidence { environments: vec![ EnvCheck { @@ -394,6 +438,7 @@ mod tests { let g = structural(&files(d), &TicketHistory::default(), false); assert_eq!(g.len(), 1, "{g:?}"); let proven = FixDecision { + cause: "Production lacks the grant.".into(), evidence: FixEvidence { environments: vec![EnvCheck { env: "prod".into(), @@ -407,6 +452,55 @@ mod tests { assert!(structural(&files(proven), &TicketHistory::default(), true).is_empty()); } + /// A schedule data fix with a connected source: its claims are about + /// one class's stored time, in no particular environment. Listing + /// production and staging as unchecked owes no environment-only proof. + #[test] + fn an_environment_the_claims_dont_rest_on_needs_no_proof() { + let unproven = |env: &str| EnvCheck { + env: env.into(), + proof: "".into(), + proven: false, + }; + let d = FixDecision { + cause: "The Saturday class is stored with a 9am start; the ticket says 8am.".into(), + evidence: FixEvidence { + data_shows: "class_schedule row 42 has start_time 09:00".into(), + environments: vec![unproven("production"), unproven("staging")], + ..Default::default() + }, + ..Default::default() + }; + assert!( + structural(&files(d.clone()), &TicketHistory::default(), true).is_empty(), + "{:?}", + structural(&files(d), &TicketHistory::default(), true) + ); + // The same plan claiming what production holds owes production's + // proof (and only production's). + let d = FixDecision { + cause: "The Saturday class is stored with a 9am start in production.".into(), + evidence: FixEvidence { + environments: vec![unproven("production"), unproven("staging")], + ..Default::default() + }, + ..Default::default() + }; + let g = structural(&files(d), &TicketHistory::default(), true); + assert_eq!(g.len(), 1, "{g:?}"); + assert!(g[0].detail.contains("`production` unproven"), "{g:?}"); + // Aliases and other names. + let named = |cause: &str| FixDecision { + cause: cause.into(), + ..Default::default() + }; + assert!(rests_on_env(&named("the live site shows it"), "prod")); + assert!(rests_on_env(&named("on stage it differs"), "staging")); + assert!(rests_on_env(&named("cluster east-2 has it"), "east-2")); + assert!(!rests_on_env(&named("product page shows 9am"), "prod")); + assert!(!rests_on_env(&named("the class time is wrong"), "staging")); + } + #[test] fn a_near_match_must_be_followed_to_the_end() { let half = NearMatch { diff --git a/services/worker/src/passes/release_plan.rs b/services/worker/src/passes/release_plan.rs index 0fda8d13e..892dc5fcf 100644 --- a/services/worker/src/passes/release_plan.rs +++ b/services/worker/src/passes/release_plan.rs @@ -247,7 +247,9 @@ impl Mechanics { pub const RELEASE_GUIDANCE: &str = "\ When the change migrates data or content and removes, renames or changes the meaning of a field \ that deployed code reads, split it (expand, then contract), and write `release` in the \ -fix_location.json block: +fix_location.json block. A migration that only writes values (a data fix such as `UPDATE ... SET \ +start_time = ..., updated_at = now()`) or only adds a field runs any time and needs no `release`; \ +never list a column it writes as an old field: - `fields`: each change, `{\"old\": [\"oldA\", \"oldB\"], \"new\": \"newField\", \"types\": [...]}`. - `migrations`: an `expand` migration that only sets the new field where it is missing (old code \ ignores it; it can run any time), and a separate `contract` migration that removes the old fields. \ @@ -822,6 +824,13 @@ pub fn touches(text: &str) -> Touches { (r#"\bremove_column\s*\(?\s*:\w+\s*,\s*:(\w+)"#, 0), (r#"\badd_column\s*\(?\s*:\w+\s*,\s*:(\w+)"#, 1), (r#"\brename_column\s*\(?\s*:\w+\s*,\s*:(\w+)\s*,\s*:(\w+)"#, 2), + // Query-builder schema calls: `dropColumn("table", "col")`, + // `table.dropColumn("col")`, `renameColumn("table", "a", "b")`, + // `table.renameColumn("a", "b")`. + (r#"\bdropColumns?\(\s*["'`]?[\w.]+["'`]?\s*,\s*["'`](\w+)["'`]"#, 0), + (r#"\bdropColumns?\(\s*["'`](\w+)["'`]\s*\)"#, 0), + (r#"\brenameColumn\(\s*["'`]?[\w.]+["'`]?\s*,\s*["'`](\w+)["'`]\s*,\s*["'`](\w+)["'`]"#, 2), + (r#"\brenameColumn\(\s*["'`](\w+)["'`]\s*,\s*["'`](\w+)["'`]\s*\)"#, 2), ] .into_iter() .map(|(p, k)| (Regex::new(p).unwrap(), k)) @@ -1028,11 +1037,25 @@ fn says_no_look(t: &str) -> bool { /// What a plan's release lacks, as instructions to the planner (empty when /// it is complete or the plan migrates nothing). `task_paths`: the files /// the plan's tasks change. -pub fn gaps(release: Option<&Release>, task_paths: &[String], m: &Mechanics) -> Vec { +/// +/// Only a real removal or rename is split into expand and contract: a +/// migration that writes values (`UPDATE classes SET start_time = '08:00', +/// updated_at = now()`) or only adds a field runs any time and needs no +/// release. A field counts as removed when the plan's own words remove, +/// drop, rename or unset it (`text`: the plan's text, see +/// [`shows_removal`]) or the plan already planned the contract migration +/// that removes it; a field the planner lists as both old and new is +/// written, not removed. +pub fn gaps( + release: Option<&Release>, + task_paths: &[String], + text: &str, + m: &Mechanics, +) -> Vec { let migrates = task_paths.iter().any(|p| is_migration(p)); let r = match release { Some(r) if !r.is_empty() => r, - _ if migrates => { + _ if migrates && shows_removal(text, None) => { return vec![format!( "The plan migrates data ({}). Write `release` in the fix_location.json block: \ the fields it changes, an expand and a separate contract migration, the \ @@ -1049,7 +1072,7 @@ pub fn gaps(release: Option<&Release>, task_paths: &[String], m: &Mechanics) -> _ => return Vec::new(), }; let mut out = Vec::new(); - let removed = r.removed_fields(); + let removed = real_removals(r, text); let in_tasks = |f: &str| { let f = f.trim().trim_start_matches("./"); !f.is_empty() && task_paths.iter().any(|p| p == f || p.ends_with(f)) @@ -1172,7 +1195,7 @@ fn deploy_summary(m: &Mechanics) -> String { ) } -/// The release gaps of a plan, from its decision and tasks. +/// The release gaps of a plan, from its decision, tasks and words. pub fn plan_gaps(plan: &super::plan::PlanResult, m: &Mechanics) -> Vec { let paths: Vec = super::plan_coverage::plan_tasks(&plan.tasks) .into_iter() @@ -1181,10 +1204,118 @@ pub fn plan_gaps(plan: &super::plan::PlanResult, m: &Mechanics) -> Vec { gaps( plan.fix.as_ref().and_then(|d| d.release.as_ref()), &paths, + &super::plan_judge::plan_text(plan), m, ) } +/// Verbs that take a field away. `replace` is not one: a data fix replaces +/// values. +const REMOVAL_VERBS: &[&str] = &[ + "remov", "drop", "renam", "unset", "deprecat", "retir", "delet", +]; + +/// Words that say the object of a removal is a field. +const FIELD_NOUNS: &[&str] = &["column", "field", "property", "attribute"]; + +/// Whether `text` takes a field away: a migration statement that removes or +/// renames one (see [`touches`]), or words that remove, drop, rename or +/// unset it. With `field`, that field must be the one named next to the +/// verb (within the same clause); without, any column or field. Writing a +/// value is never a removal: `UPDATE t SET updated_at = now()`, `set({...})` +/// and `DELETE FROM t WHERE ...` (rows, not a field) all say no. +pub fn shows_removal(text: &str, field: Option<&str>) -> bool { + let t = touches(text); + match field { + Some(f) if t.removes.contains(f) => return true, + None if !t.removes.is_empty() => return true, + _ => {} + } + for clause in text.split(['.', '\n', ';', '!', '?']) { + let lower = clause.to_ascii_lowercase(); + let words: Vec<(usize, &str)> = word_spans(&lower); + let verbs: Vec = words + .iter() + .enumerate() + .filter(|(i, (_, w))| { + REMOVAL_VERBS.iter().any(|v| w.starts_with(v)) + // `delete from t` deletes rows; `deleted_at` is a column. + && !(w.starts_with("delet") + && (words.get(i + 1).is_some_and(|(_, n)| *n == "from") + || w.contains('_'))) + }) + .map(|(i, _)| i) + .collect(); + if verbs.is_empty() { + continue; + } + let near = |pred: &dyn Fn(&str) -> bool| { + verbs.iter().any(|&v| { + let lo = v.saturating_sub(6); + let hi = (v + 7).min(words.len()); + words[lo..hi].iter().any(|(_, w)| pred(w)) + }) + }; + let hit = match field { + Some(f) => { + let f = f.to_ascii_lowercase(); + near(&|w: &str| w == f) + } + None => near(&|w: &str| { + FIELD_NOUNS + .iter() + .any(|n| w == *n || w.strip_suffix('s') == Some(n)) + }), + }; + if hit { + return true; + } + } + false +} + +/// The identifier-like words of `text` (letters, digits, `_`), with where +/// each starts. +fn word_spans(text: &str) -> Vec<(usize, &str)> { + let mut out = Vec::new(); + let mut start: Option = None; + for (i, c) in text.char_indices() { + let ident = c.is_ascii_alphanumeric() || c == '_'; + match (ident, start) { + (true, None) => start = Some(i), + (false, Some(s)) => { + out.push((s, &text[s..i])); + start = None; + } + _ => {} + } + } + if let Some(s) = start { + out.push((s, &text[s..])); + } + out +} + +/// The fields a plan's release really removes: each old field that is not +/// also the change's new field (written, not removed), and that the plan's +/// words take away or its planned contract migration removes. +pub fn real_removals(r: &Release, text: &str) -> Vec { + let contract = r.contract().is_some(); + let mut out: Vec = Vec::new(); + for f in &r.fields { + for o in &f.old { + let o = o.trim(); + if o.is_empty() || o == f.new.trim() || out.iter().any(|x| x == o) { + continue; + } + if contract || shows_removal(text, Some(o)) { + out.push(o.to_string()); + } + } + } + out +} + // ── The release steps ─────────────────────────────────────────────────────── /// What a release step does. @@ -2009,6 +2140,100 @@ jobs: ); } + /// A schedule data fix: one migration writes the right class time and + /// bumps `updated_at`. Writing a column is not removing it, so the plan + /// needs no expand and contract (a run once was sent back to split a + /// data fix because its release listed `updated_at`). + #[test] + fn writing_a_column_is_not_a_removal() { + let sql = "UPDATE class_schedule SET start_time = '08:00', updated_at = now() \ + WHERE class_id = 42;"; + let t = touches(sql); + assert!(t.removes.is_empty(), "{t:?}"); + assert!(!shows_removal(sql, None)); + assert!(!shows_removal(sql, Some("updated_at"))); + let rows = "DELETE FROM class_schedule WHERE updated_at < now() - interval '1 year';"; + assert!( + !shows_removal(rows, Some("updated_at")), + "rows, not a field" + ); + let soft = "Set deleted_at on the duplicate row and update updated_at."; + assert!(!shows_removal(soft, Some("updated_at"))); + + let files = vec![( + "src/database/migrations/1783400000000-FixClassTime.ts".to_string(), + "added".to_string(), + format!("+await queryRunner.query(`{sql}`);"), + )]; + assert!(diff_gaps(&files).is_empty(), "{:?}", diff_gaps(&files)); + + let plan_text = "Correct the Saturday class time from 9am to 8am with a data \ + migration that runs UPDATE class_schedule SET start_time = '08:00', \ + updated_at = now() for the one class."; + let paths = vec!["src/database/migrations/1783400000000-FixClassTime.ts".to_string()]; + assert!(gaps(None, &paths, plan_text, &repo()).is_empty()); + // The planner listed the column it writes as a changed field: still + // no removal. + let written = Release { + fields: vec![FieldChange { + old: vec!["updated_at".into()], + new: String::new(), + types: vec![], + }], + ..Default::default() + }; + let g = gaps(Some(&written), &paths, plan_text, &repo()).join("\n"); + assert!(!g.contains("removes `updated_at`"), "{g}"); + assert!(!g.contains("Plan two migrations"), "{g}"); + let same = Release { + fields: vec![FieldChange { + old: vec!["start_time".into()], + new: "start_time".into(), + types: vec![], + }], + ..Default::default() + }; + assert!(real_removals(&same, "Drop the start_time column").is_empty()); + } + + #[test] + fn a_real_removal_or_rename_is_still_split() { + let paths = vec!["db/migrations/0042_drop_legacy.sql".to_string()]; + // No release yet: words or a statement that drop a column ask for one. + for text in [ + "Drop the legacy_flag column once the new code reads is_featured.", + "ALTER TABLE pages DROP COLUMN legacy_flag;", + "Rename the `title` field to `headline`.", + "await queryRunner.dropColumn(\"pages\", \"legacy_flag\");", + "table.renameColumn('title', 'headline')", + ] { + let g = gaps(None, &paths, text, &repo()); + assert_eq!(g.len(), 1, "{text}: {g:?}"); + assert!(g[0].contains("Write `release`"), "{g:?}"); + } + // A release whose old field the words remove: split it. + let r = Release { + fields: vec![FieldChange { + old: vec!["legacy_flag".into()], + new: "is_featured".into(), + types: vec![], + }], + ..Default::default() + }; + let text = "Replace legacy_flag with is_featured, then remove legacy_flag."; + let g = gaps(Some(&r), &paths, text, &repo()).join("\n"); + assert!(g.contains("removes `legacy_flag`"), "{g}"); + assert!(g.contains("Plan two migrations"), "{g}"); + // Query-builder schema calls are read as what they are. + let t = touches("await queryRunner.renameColumn(\"pages\", \"title\", \"headline\")"); + assert!( + t.removes.contains("title") && t.sets.contains("headline"), + "{t:?}" + ); + let t = touches("table.dropColumn('legacy_flag')"); + assert!(t.removes.contains("legacy_flag"), "{t:?}"); + } + #[test] fn sql_rename_is_expand_and_contract_at_once() { let t = touches("ALTER TABLE t RENAME COLUMN old_name TO new_name;"); @@ -2061,6 +2286,10 @@ jobs: } } + /// The words of a plan that replaces two fields with a new one. + const PLAN_TEXT: &str = "Replace the hero's oldA and oldB flags with newFlag. The contract \ + migration removes the oldA and oldB fields after the production deploy."; + fn tasks() -> Vec { vec![ "studio/migrations/expand.ts".into(), @@ -2073,15 +2302,15 @@ jobs: #[test] fn a_complete_release_passes_the_plan_check() { assert!( - gaps(Some(&release()), &tasks(), &repo()).is_empty(), + gaps(Some(&release()), &tasks(), PLAN_TEXT, &repo()).is_empty(), "{:?}", - gaps(Some(&release()), &tasks(), &repo()) + gaps(Some(&release()), &tasks(), PLAN_TEXT, &repo()) ); } #[test] fn a_plan_that_migrates_without_a_release_is_sent_back() { - let g = gaps(None, &tasks(), &repo()); + let g = gaps(None, &tasks(), PLAN_TEXT, &repo()); assert_eq!(g.len(), 1); assert!(g[0].contains("Production deploys on a `v*` tag"), "{g:?}"); } @@ -2093,7 +2322,7 @@ jobs: r.fallback.clear(); r.impact.truncate(1); r.impact[0].result = "Direct dataset queries were not possible".into(); - let g = gaps(Some(&r), &tasks(), &repo()).join("\n"); + let g = gaps(Some(&r), &tasks(), PLAN_TEXT, &repo()).join("\n"); assert!(g.contains("Plan two migrations"), "{g}"); assert!(g.contains("release.fallback"), "{g}"); assert!(g.contains("Count the affected items in production"), "{g}"); @@ -2109,14 +2338,14 @@ jobs: r.impact[1].result.clear(); r.impact[1].error = "the read API returned 401 Unauthorized".into(); r.live_items.clear(); - assert!(gaps(Some(&r), &tasks(), &repo()).is_empty()); + assert!(gaps(Some(&r), &tasks(), PLAN_TEXT, &repo()).is_empty()); } #[test] fn production_items_must_be_named() { let mut r = release(); r.live_items.clear(); - let g = gaps(Some(&r), &tasks(), &repo()); + let g = gaps(Some(&r), &tasks(), PLAN_TEXT, &repo()); assert!(g.iter().any(|x| x.contains("release.live_items")), "{g:?}"); } diff --git a/services/worker/src/passes/steps.rs b/services/worker/src/passes/steps.rs index 17592dfc3..a48a5ffe5 100644 --- a/services/worker/src/passes/steps.rs +++ b/services/worker/src/passes/steps.rs @@ -8,9 +8,20 @@ //! //! Now every place that lacks time hands off instead: the run continues in a //! fresh step (a NEW queue message with its own receive count and its own 15 -//! minutes) that resumes exactly where this one stopped: the implement work, -//! the generator check ([`Gate::Generators`]) or the checks before the pull -//! request ([`Gate::Checks`]), with the branch as it is. +//! minutes) that resumes exactly where this one stopped: planning +//! ([`Gate::Plan`]), the implement work, the generator check +//! ([`Gate::Generators`]) or the checks before the pull request +//! ([`Gate::Checks`]), with the branch as it is. +//! +//! Planning commits nothing to a branch, so it keeps its own state on the +//! checkpoint ([`PlanState`]): the repository it settled on, how far it got +//! (plan revisions, re-plans, whether the repository and file checks are +//! done) and the plan check's open gaps; the plan files themselves are the +//! run's own cached plan. A run once planned, switched repository, planned +//! again, re-planned for one file and ran out of time with nothing committed: +//! it failed "no work is committed to continue from". Planning now continues +//! in the next step from its last plan, and a new plan revision or fewer +//! open gaps counts as progress ([`plan_stalled_after`]). //! //! A run keeps going as long as its steps make progress ([`stalled_after`]): //! the branch head moved, or the run reached a later gate. It stops when two @@ -113,15 +124,20 @@ fn where_label(at: &str) -> &str { "checks" => "the checks before the pull request", "implement_started" | "implement" => "the implement work (planned tasks)", "security" => "the security audit", + "plan" => "planning (the plan and its repository and file checks)", other => other, } } // ── Resume points ────────────────────────────────────────────────────────── -/// A point after implement where a fresh step can pick the run up. +/// A point where a fresh step can pick the run up: planning, or a point +/// after implement. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Gate { + /// Planning, before any branch: the next step resumes from the run's own + /// plan and the [`PlanState`] on the checkpoint. + Plan, /// Everything after the implement work and its plan check: the /// generators run with the work, the adversarial test, the security /// audit, then the gates below. @@ -136,6 +152,7 @@ pub enum Gate { impl Gate { pub fn as_str(self) -> &'static str { match self { + Gate::Plan => "plan", Gate::Verify => "verify", Gate::Generators => "generators", Gate::Checks => "checks", @@ -144,6 +161,7 @@ impl Gate { pub fn parse(s: &str) -> Option { match s { + "plan" => Some(Gate::Plan), "verify" => Some(Gate::Verify), "generators" => Some(Gate::Generators), "checks" => Some(Gate::Checks), @@ -210,6 +228,117 @@ impl Carry { } } +/// Re-plans the repository and file checks may ask for in one run: a +/// repository switch plans once in the new repository, and a plan whose +/// files don't match plans once more only when no switch did. Each re-plan +/// carries every gap the plan check found in ONE send-back; what is still +/// open after it stays on the decision and planning moves on. +pub const MAX_PLAN_REPLANS: u32 = 1; + +/// How far planning got, kept on the checkpoint so a step that runs out of +/// time while planning hands off to the next one instead of failing. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct PlanState { + /// The repository the plan is for (`owner/name`), after any switch. + #[serde(default)] + pub repo: String, + /// Its base branch. + #[serde(default)] + pub base_branch: String, + /// Plans made so far (each `plan::run` that finished). + #[serde(default)] + pub revision: u32, + /// Re-plans the repository and file checks asked for (see + /// [`MAX_PLAN_REPLANS`]). + #[serde(default)] + pub replans: u32, + /// The run switched repository (it never switches twice). + #[serde(default)] + pub switched: bool, + /// The repository and file checks are done: the plan is final. + #[serde(default)] + pub checked: bool, + /// The plan check's gaps still open on the latest plan. + #[serde(default)] + pub open_gaps: Vec, +} + +impl PlanState { + /// A fresh planning state for the run's repository. + pub fn new(owner: &str, name: &str, base_branch: &str) -> Self { + Self { + repo: format!("{owner}/{name}"), + base_branch: base_branch.to_string(), + ..Default::default() + } + } + + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_default() + } + + pub fn from_json(s: &str) -> Option { + serde_json::from_str(s).ok() + } + + /// One more finished plan, with its open gaps. + pub fn planned(&mut self, open_gaps: &[String]) { + self.revision = self.revision.saturating_add(1); + self.open_gaps = open_gaps.to_vec(); + } + + /// Whether the checks may ask for another re-plan. + pub fn may_replan(&self) -> bool { + self.replans < MAX_PLAN_REPLANS + } + + /// The repository as `(owner, name)`, when it is one. + pub fn owner_name(&self) -> Option<(&str, &str)> { + self.repo + .split_once('/') + .filter(|(o, n)| !o.is_empty() && !n.is_empty()) + } + + /// This state's progress mark (see [`plan_stalled_after`]). + pub fn mark(&self) -> String { + progress_mark( + "", + &format!("plan:r{}:g{}", self.revision, self.open_gaps.len()), + ) + } +} + +/// Planning steps in a row without progress, after the step that just +/// ended: zero when planning made a new plan revision or has fewer open +/// gaps than the last step's mark (or there is no planning mark), else one +/// more. +pub fn plan_stalled_after(prev: Option<&str>, now: &PlanState, stalled: u32) -> u32 { + let parse = |m: &str| -> Option<(u32, usize)> { + let at = m.split_once('|')?.1.strip_prefix("plan:r")?; + let (r, g) = at.split_once(":g")?; + Some((r.parse().ok()?, g.parse().ok()?)) + }; + match prev.and_then(parse) { + Some((rev, gaps)) if now.revision <= rev && now.open_gaps.len() >= gaps => { + stalled.saturating_add(1) + } + _ => 0, + } +} + +/// Why a stalled planning run stops, in a sentence. +pub fn plan_stall_reason(step: u32, now: &PlanState) -> String { + format!( + "Stopped: steps {} and {} made no progress in planning. The plan stayed at revision {} \ + with {} open gaps in {}.", + step.saturating_sub(2).max(1), + step.saturating_sub(1).max(1), + now.revision, + now.open_gaps.len(), + now.repo + ) +} + /// What the run's checkpoint says about steps: the gate to resume at (with /// what it carries), and the progress mark and stalled count of the last /// step. @@ -217,6 +346,8 @@ impl Carry { pub struct StepState { pub gate: Option, pub carry: Option, + /// How far planning got, when the run resumes at [`Gate::Plan`]. + pub plan: Option, pub mark: Option, /// The step that saved `mark`. pub mark_step: u32, @@ -249,6 +380,7 @@ pub async fn load(state: &WorkerState, team_id: &str, run_id: &str) -> StepState StepState { gate: s("gate").as_deref().and_then(Gate::parse), carry: s("gate_carry").as_deref().and_then(Carry::from_json), + plan: s("plan_state").as_deref().and_then(PlanState::from_json), mark: s("step_mark"), mark_step: item .get("step_mark_step") @@ -293,6 +425,39 @@ pub async fn save_gate( } } +impl StepState { + /// The planning state to resume from, when the run handed off while + /// planning. + pub fn planning(&self) -> Option { + (self.gate == Some(Gate::Plan)) + .then(|| self.plan.clone()) + .flatten() + } +} + +/// The run resumes planning at [`Gate::Plan`], from `plan`, in its next step +/// (or after a redelivery). Saved at the start of planning and after every +/// plan, switch and re-plan; the implement checkpoint clears it. +pub async fn save_plan(state: &WorkerState, team_id: &str, run_id: &str, plan: &PlanState) { + if state.config.checkpoints_table_name.is_empty() { + return; + } + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.checkpoints_table_name) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("sk", key(run_id)) + .update_expression("SET gate = :g, plan_state = :p REMOVE gate_carry") + .expression_attribute_values(":g", AttributeValue::S(Gate::Plan.as_str().to_string())) + .expression_attribute_values(":p", AttributeValue::S(plan.to_json())) + .send() + .await + { + warn!(run_id, error = %e, "Could not save how far planning got"); + } +} + /// This step's progress mark and the stalled count so far. pub async fn save_mark( state: &WorkerState, @@ -431,14 +596,76 @@ mod tests { const { assert!(MAX_RUN_STEPS >= 50) }; } + #[test] + fn planning_resumes_while_it_makes_progress() { + let mut p = PlanState::new("acme", "web", "main"); + p.planned(&["[env_unproven] a".into(), "b".into()]); + let first = p.mark(); + // Same revision, same gaps: no progress. + assert_eq!(plan_stalled_after(Some(&first), &p, 0), 1); + // A new plan revision is progress. + let mut next = p.clone(); + next.planned(&["a".into(), "b".into(), "c".into()]); + assert_eq!(plan_stalled_after(Some(&first), &next, 1), 0); + // Fewer open gaps is progress. + let mut fewer = p.clone(); + fewer.open_gaps.pop(); + assert_eq!(plan_stalled_after(Some(&first), &fewer, 1), 0); + // A mark from before planning (a branch mark) is not compared. + assert_eq!(plan_stalled_after(Some("abc|implement"), &p, 1), 0); + assert_eq!(plan_stalled_after(None, &p, 1), 0); + // Two stalled planning steps stop, saying where. + let s = plan_stalled_after(Some(&first), &p, 1); + assert!(stops_for_stall(s)); + let why = plan_stall_reason(4, &p); + assert!( + why.contains("steps 2 and 3 made no progress in planning"), + "{why}" + ); + assert!( + why.contains("revision 1 with 2 open gaps in acme/web"), + "{why}" + ); + } + + #[test] + fn plan_state_round_trips_and_bounds_replans() { + let mut p = PlanState::new("acme", "api", "develop"); + assert!(p.may_replan()); + p.switched = true; + p.replans = 1; + p.planned(&["[release] x".into()]); + assert!(!p.may_replan(), "one re-plan per run"); + assert_eq!(PlanState::from_json(&p.to_json()), Some(p.clone())); + assert_eq!(p.owner_name(), Some(("acme", "api"))); + // Older checkpoints without some fields still read. + let old = PlanState::from_json(r#"{"repo":"a/b","revision":2}"#).unwrap(); + assert_eq!(old.revision, 2); + assert!(!old.checked); + let st = StepState { + gate: Some(Gate::Plan), + plan: Some(p.clone()), + ..Default::default() + }; + assert_eq!(st.planning(), Some(p.clone())); + let after = StepState { + gate: Some(Gate::Generators), + plan: Some(p), + ..Default::default() + }; + assert_eq!(after.planning(), None, "a later gate is not planning"); + } + #[test] fn gates_order_the_resume() { + assert!(Gate::Plan < Gate::Verify); + assert!(Gate::Verify.runs_from(Some(Gate::Plan))); assert!(Gate::Generators.runs_from(None)); assert!(Gate::Checks.runs_from(Some(Gate::Generators))); assert!(!Gate::Generators.runs_from(Some(Gate::Checks))); assert!(Gate::Verify.runs_from(Some(Gate::Verify))); assert!(!Gate::Verify.runs_from(Some(Gate::Generators))); - for g in [Gate::Verify, Gate::Generators, Gate::Checks] { + for g in [Gate::Plan, Gate::Verify, Gate::Generators, Gate::Checks] { assert_eq!(Gate::parse(g.as_str()), Some(g)); } }