diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f1c2365a1..bf7eed8b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,6 +67,23 @@ jobs: # review histories replayed through the real decision code, no model. - run: cargo test --workspace + # Every run failure that reached a person, replayed through the pipeline's + # decision code with fakes only at the edges (docs/incidents.md). + incidents: + name: Incident regressions + runs-on: ubuntu-latest + defaults: + run: + working-directory: services + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + workspaces: services + cache-on-failure: true + - run: cargo test -p worker 'incidents::' + lambda-tests: name: Lambda (Python) runs-on: ubuntu-latest diff --git a/docs/incidents.md b/docs/incidents.md new file mode 100644 index 000000000..51d93c2d3 --- /dev/null +++ b/docs/incidents.md @@ -0,0 +1,53 @@ +# Incident regression suite + +Every run failure that reached a person is a case in +`services/worker/src/passes/incidents/`, so it can't come back without a +failing test. CI runs the suite as its own job, **Incident regressions** +(`cargo test -p worker incidents::`), on every pull request. + +Each case replays the failure on one invented monorepo: + +- `apps/studio`: the CMS studio, its schema, and a `typegen` script. The + script writes `apps/studio/schema.json`, and writes the site's types + through a `../web/...` path. +- `apps/web`: the site. +- `e2e/`: end-to-end specs, with a map of which spec tests which page. + +The case runs the pipeline's own decision code. Only the edges are faked: + +- GitHub: branches, compares and pull requests, in the shapes GitHub returns. +- The model: recorded judge replies, read by the real parser. +- The sandbox: a real tar.gz archive and a CodeBuild-shaped log, read by the + real `codegen_outcome`. +- DynamoDB: run records as the table holds them. + +Each case checks three things: the run's final status, the pull request and +notes the run leaves, and that the old failure message never appears. When a +decision is made inside the pipeline itself, the case also checks that the +pipeline still calls it there. + +## Cases + +| Case | What happened | The guarantee | +|---|---|---| +| a. `a_whole_branch` | The plan check said 5 of 7 tasks were done. The last step wrote nothing, and the run ended "I ran but produced no file changes". | A step that writes nothing is judged on the whole branch. Work on the branch goes on to the checks and the pull request. With nothing on the branch, the run names the planned tasks that weren't built and never asks generic questions. | +| b. `b_open_pr_retry` | A retry started over on a branch whose earlier run was still fixing CI. | A retry continues the earlier run's open pull request and opens no other. While the earlier run still works on the branch, the retry stops before writing anything and says why. That covers a run that is running, waiting on CI, holding a writer slot, or has a round under way or parked. | +| c. `c_codegen_egress` | The sandbox's network allowlist refused the CMS host. The run blamed the change: "its generated files were not regenerated". | Builds that run a generator may reach the hosts it needs. A host that is still refused is a tooling failure that names the host. | +| d. `d_echoed_markers` | The echoed buildspec holds the upload markers, so every build read as "could not be uploaded". | A marker counts only on a line of its own. The exit code is the last one printed. A failed generator's reason quotes what the generator printed, not the echoed buildspec. | +| e. `e_large_generated_output` | A types file over 5 MB, written through `../`, was dropped silently. The run said "regenerated 1 file(s)" and opened no pull request. | Every changed file is committed, or named as a tooling failure. Paths have one spelling. A generated task its generator settled counts as done in the plan check and the proof check. | +| f. `f_steps` | The generator check ran out of time and the run failed "not enough time left". | A gate that lacks time continues in a fresh step at that gate, as a new queue message. A run that keeps making progress continues past 20 steps. Two steps in a row without progress stop it, and it says where it was stuck. | +| g. `g_large_plan` | A 40-file ticket was capped and narrowed. | A plan holds every file the ticket needs. Nothing caps or narrows it, and every later round is told every task. | +| h. `h_pr_updates` | A PR updated over several runs went stale. Its description was out of date, a ticket comment was posted twice, a question was asked on every update, an e2e test skipped itself when content was missing, and a note said "could not look up" content that was readable. | Each one is caught by its own check. The description is rewritten when a round lands. A notice is posted once per ticket, and so is a question. A spec that skips on missing content fails the checklist. A note that didn't look, when it could have, goes back to the planner. | +| 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`. | + +## Adding a case + +When a fix lands for a new failure: + +1. Add `services/worker/src/passes/incidents/_.rs`. Start it with + what happened and the guarantee, in plain words, with no customer names. +2. Build the scenario on the fixture monorepo (`fixture.rs`). Add any new edge + to the fixture as a fake, never as a mock of the pipeline's own code. +3. Check the final status, what the run leaves, and that the old message never + appears (`Ending::never_says`). +4. Add a row to the table above. diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index 79c4fb741..5123592b0 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -63,6 +63,7 @@ "feedback": "feedback round", "security_fix": "security fix round", "conflict_fix": "conflict round", + "planned_work": "planned-work round", } _dynamodb = None @@ -167,7 +168,7 @@ def round_kind(run, pass_name): return "ci_fix" if p == "feedback": return "feedback" - if p in ("security_fix", "conflict_fix"): + if p in ("security_fix", "conflict_fix", "planned_work"): return p return "review_fix" diff --git a/services/common/src/run_round.rs b/services/common/src/run_round.rs index 86f50fd59..8662e153a 100644 --- a/services/common/src/run_round.rs +++ b/services/common/src/run_round.rs @@ -82,6 +82,11 @@ pub enum Kind { /// it: CoderHelm merges the base into its own pull request's branch, /// once (`await_merge`). Conflict, + /// Planned work the check before the pull request still found not done + /// after its fix round: the pull request opened as a draft with it + /// listed under "Not finished", and CoderHelm keeps working it in + /// rounds of its own while each round makes progress. + PlannedWork, } impl Kind { @@ -92,6 +97,7 @@ impl Kind { Kind::Feedback => "feedback", Kind::SecurityFix => "security_fix", Kind::Conflict => "conflict_fix", + Kind::PlannedWork => "planned_work", } } @@ -102,6 +108,7 @@ impl Kind { "feedback" => Some(Kind::Feedback), "security_fix" => Some(Kind::SecurityFix), "conflict_fix" => Some(Kind::Conflict), + "planned_work" => Some(Kind::PlannedWork), _ => None, } } @@ -114,6 +121,7 @@ impl Kind { "feedback" => Kind::Feedback, "security_fix" => Kind::SecurityFix, "conflict_fix" => Kind::Conflict, + "planned_work" => Kind::PlannedWork, _ => Kind::ReviewFix, } } @@ -126,6 +134,7 @@ impl Kind { Kind::Feedback => "feedback round", Kind::SecurityFix => "security fix round", Kind::Conflict => "conflict round", + Kind::PlannedWork => "planned-work round", } } } @@ -171,6 +180,9 @@ pub struct Round { /// The branch the round writes its checkpoints to (empty until it /// starts working). pub wip_branch: String, + /// Planned-work rounds in a row, before this one, that made no progress + /// (no task finished and nothing pushed). Two stop the work. + pub stalled: u32, } /// The branch a round on `pr_branch` keeps its checkpoints on: a branch of @@ -227,6 +239,7 @@ impl Round { feedback: cut(feedback, MAX_FEEDBACK_CHARS), scoped, wip_branch: String::new(), + stalled: 0, } } @@ -267,6 +280,7 @@ impl Round { ("feedback".to_string(), s(&self.feedback)), ("scoped".to_string(), AttributeValue::Bool(self.scoped)), ("wip_branch".to_string(), s(&self.wip_branch)), + ("stalled".to_string(), n(self.stalled)), ])) } @@ -291,6 +305,7 @@ impl Round { .copied() .unwrap_or(true), wip_branch: get_s(m, "wip_branch"), + stalled: get_n(m, "stalled"), }) } @@ -678,11 +693,14 @@ mod tests { assert_eq!(Kind::of_pass("feedback"), Kind::Feedback); assert_eq!(Kind::of_pass("implement"), Kind::ReviewFix); assert_eq!(Kind::of_pass("security_fix:1"), Kind::SecurityFix); + assert_eq!(Kind::of_pass("planned_work:2"), Kind::PlannedWork); for k in [ Kind::CiFix, Kind::ReviewFix, Kind::Feedback, Kind::SecurityFix, + Kind::Conflict, + Kind::PlannedWork, ] { assert_eq!(Kind::parse(k.as_str()), Some(k)); } @@ -702,5 +720,19 @@ mod tests { assert!(sweep.contains(&format!("ROUND_SWEEP_GRACE_SECONDS = {SWEEP_GRACE_SECS}"))); assert!(sweep.contains(&format!("ROUND_BUDGET_SECONDS = {BUDGET_SECS}"))); assert!(sweep.contains("Pull request open; the last fix round didn't finish")); + for k in [ + Kind::CiFix, + Kind::ReviewFix, + Kind::Feedback, + Kind::SecurityFix, + Kind::Conflict, + Kind::PlannedWork, + ] { + assert!( + sweep.contains(&format!("\"{}\": \"{}\"", k.as_str(), k.label())), + "the sweep names the {}", + k.label() + ); + } } } diff --git a/services/worker/src/clients/sandbox.rs b/services/worker/src/clients/sandbox.rs index 667c31a07..9e1208135 100644 --- a/services/worker/src/clients/sandbox.rs +++ b/services/worker/src/clients/sandbox.rs @@ -345,6 +345,11 @@ pub fn read_changed_tar( Ok(out) } +/// A codegen build's changed-files archive, read with the worker's caps. +pub fn read_archive(bytes: &[u8]) -> Result> { + read_changed_tar(bytes, MAX_CODEGEN_FILES, MAX_CODEGEN_FILE_BYTES) +} + /// Thin driver over CodeBuild + S3 + CloudWatch Logs. Holds only borrows from /// `WorkerState`; construct it per pass. pub struct SandboxClient<'a> { @@ -708,88 +713,7 @@ impl<'a> SandboxClient<'a> { out_key: &str, build_succeeded: bool, ) -> Result> { - // Source of truth for "codegen produced changes" is the S3 artifact the - // build uploads on success — NOT the CloudWatch log marker. The build - // uploads out.tgz mid-run (before it finishes) and S3 is read-after-write - // consistent, so the artifact is reliably there the moment the build is - // done. The log marker, by contrast, lags CloudWatch delivery by several - // seconds; reading it too early made the worker report "no result marker" - // for builds that had ALREADY succeeded and uploaded the regenerated - // files, so the agent re-ran the (expensive, always-succeeding) codegen - // build over and over until the pass timed out. Check S3 first. - let captured = self.download_changed(out_key).await.unwrap_or_default(); - if !captured.files.is_empty() || !captured.dropped.is_empty() { - let output = self - .fetch_log(group, stream) - .await - .map(|l| common::tail_str(&l, MAX_OUTPUT_CHARS).to_string()) - .unwrap_or_default(); - return Ok(CodegenOutcome { - ran: true, - passed: true, - changed: captured.files, - dropped: captured.dropped, - output, - }); - } - - // No artifact => codegen either passed with nothing to regenerate, or - // failed. Read the log for the end marker, briefly retrying to let - // CloudWatch flush; fall back to the CodeBuild build status if the marker - // never lands (so a delivery lag is never mistaken for a codegen failure). - if group.is_empty() { - return Ok(CodegenOutcome::not_run( - "codegen produced no logs (infra fault)", - )); - } - let mut full = String::new(); - let mut code = None; - for attempt in 0..4 { - full = self.fetch_log(group, stream).await.unwrap_or_default(); - code = parse_marker_exit(&full, MARKER_CODEGEN_END); - if code.is_some() { - break; - } - if attempt < 3 { - tokio::time::sleep(Duration::from_secs(3)).await; - } - } - let output = common::tail_str(&full, MAX_OUTPUT_CHARS).to_string(); - // Codegen changed files but could not hand them back: that is not - // "nothing to regenerate", and must not be reported as a clean pass. - if printed(&full, MARKER_CODEGEN_UPLOAD_FAILED) { - return Ok(CodegenOutcome::not_run(format!( - "codegen ran but its changed files could not be uploaded\n{output}" - ))); - } - // If the build logged an upload but the first artifact read came back empty - // (a transient S3 read), try once more — those changes are real and must - // not be dropped as "nothing to regenerate". - if printed(&full, MARKER_CODEGEN_UPLOADED) { - let retry = self.download_changed(out_key).await.unwrap_or_default(); - if !retry.files.is_empty() || !retry.dropped.is_empty() { - return Ok(CodegenOutcome { - ran: true, - passed: true, - changed: retry.files, - dropped: retry.dropped, - output, - }); - } - } - // Marker exit code is authoritative for pass/fail when present; otherwise - // trust the build status. Either way `changed` is empty here. - let passed = match code { - Some(c) => c == 0, - None => build_succeeded, - }; - Ok(CodegenOutcome { - ran: true, - passed, - changed: Vec::new(), - dropped: Vec::new(), - output, - }) + Ok(codegen_outcome(self, group, stream, out_key, build_succeeded).await) } /// Download the captured tar.gz of changed files and read them into @@ -808,7 +732,7 @@ impl<'a> SandboxClient<'a> { .await .map_err(|e| format!("codegen output download failed: {e}"))?; let bytes = obj.body.collect().await?.into_bytes(); - read_changed_tar(&bytes, MAX_CODEGEN_FILES, MAX_CODEGEN_FILE_BYTES) + read_archive(&bytes) } async fn build_and_read( @@ -1053,6 +977,119 @@ fn parse_marker_exit(log: &str, marker: &str) -> Option { }) } +/// Where a finished codegen build's result is read from: the archive of +/// changed files it uploaded (S3) and its log (CloudWatch). The sandbox +/// client reads the real ones; the incident suite hands in recorded ones. +#[async_trait::async_trait] +pub trait CodegenSource: Sync { + /// The changed-files archive, read (empty when there is none). + async fn changed_files(&self, out_key: &str) -> Captured; + /// The build's whole log (empty when unreadable). + async fn build_log(&self, group: &str, stream: &str) -> String; + /// How long to wait for a log that hasn't arrived yet. + fn log_retry_delay(&self) -> Duration { + Duration::from_secs(3) + } +} + +#[async_trait::async_trait] +impl CodegenSource for SandboxClient<'_> { + async fn changed_files(&self, out_key: &str) -> Captured { + self.download_changed(out_key).await.unwrap_or_default() + } + + async fn build_log(&self, group: &str, stream: &str) -> String { + self.fetch_log(group, stream).await.unwrap_or_default() + } +} + +/// What a finished codegen build came to, read from its archive and log. +pub async fn codegen_outcome( + src: &S, + group: &str, + stream: &str, + out_key: &str, + build_succeeded: bool, +) -> CodegenOutcome { + // Source of truth for "codegen produced changes" is the S3 artifact the + // build uploads on success — NOT the CloudWatch log marker. The build + // uploads out.tgz mid-run (before it finishes) and S3 is read-after-write + // consistent, so the artifact is reliably there the moment the build is + // done. The log marker, by contrast, lags CloudWatch delivery by several + // seconds; reading it too early made the worker report "no result marker" + // for builds that had ALREADY succeeded and uploaded the regenerated + // files, so the agent re-ran the (expensive, always-succeeding) codegen + // build over and over until the pass timed out. Check S3 first. + let captured = src.changed_files(out_key).await; + if !captured.files.is_empty() || !captured.dropped.is_empty() { + let output = + common::tail_str(&src.build_log(group, stream).await, MAX_OUTPUT_CHARS).to_string(); + return CodegenOutcome { + ran: true, + passed: true, + changed: captured.files, + dropped: captured.dropped, + output, + }; + } + + // No artifact => codegen either passed with nothing to regenerate, or + // failed. Read the log for the end marker, briefly retrying to let + // CloudWatch flush; fall back to the CodeBuild build status if the marker + // never lands (so a delivery lag is never mistaken for a codegen failure). + if group.is_empty() { + return CodegenOutcome::not_run("codegen produced no logs (infra fault)"); + } + let mut full = String::new(); + let mut code = None; + for attempt in 0..4 { + full = src.build_log(group, stream).await; + code = parse_marker_exit(&full, MARKER_CODEGEN_END); + if code.is_some() { + break; + } + if attempt < 3 { + tokio::time::sleep(src.log_retry_delay()).await; + } + } + let output = common::tail_str(&full, MAX_OUTPUT_CHARS).to_string(); + // Codegen changed files but could not hand them back: that is not + // "nothing to regenerate", and must not be reported as a clean pass. + if printed(&full, MARKER_CODEGEN_UPLOAD_FAILED) { + return CodegenOutcome::not_run(format!( + "codegen ran but its changed files could not be uploaded\n{output}" + )); + } + // If the build logged an upload but the first artifact read came back empty + // (a transient S3 read), try once more — those changes are real and must + // not be dropped as "nothing to regenerate". + if printed(&full, MARKER_CODEGEN_UPLOADED) { + let retry = src.changed_files(out_key).await; + if !retry.files.is_empty() || !retry.dropped.is_empty() { + return CodegenOutcome { + ran: true, + passed: true, + changed: retry.files, + dropped: retry.dropped, + output, + }; + } + } + // Marker exit code is authoritative for pass/fail when present; otherwise + // trust the build status. Either way `changed` is empty here. + let passed = match code { + Some(c) => c == 0, + None => build_succeeded, + }; + CodegenOutcome { + ran: true, + passed, + changed: Vec::new(), + dropped: Vec::new(), + output, + } +} + /// Parse the exit code from the checks end marker. fn parse_exit(log: &str) -> Option { parse_marker_exit(log, MARKER_END) diff --git a/services/worker/src/passes/finish_planned.rs b/services/worker/src/passes/finish_planned.rs new file mode 100644 index 000000000..242f24151 --- /dev/null +++ b/services/worker/src/passes/finish_planned.rs @@ -0,0 +1,274 @@ +//! Planned work left after the pull request opens is finished by CoderHelm. +//! +//! When the check before the pull request still finds planned work not done +//! after its fix round, the pull request opens as a draft with that work +//! listed at the top under "Not finished" (`proof::unfinished_section`). It +//! used to stay there for a person to pick up. +//! +//! Now the run keeps working it, in planned-work rounds on the pull request +//! (`run_round::Kind::PlannedWork`), each in a fresh invocation with its own +//! budget, the same as every other round: +//! +//! - A round is told the tasks still listed ([`round_feedback`]), builds +//! them on its own WIP branch and lands them on the pull request as one +//! commit. +//! - The check judges the branch again. The "Not finished" section is +//! rewritten to what is still not done, or removed when nothing is. +//! - Nothing left: the pull request is marked ready ([`Next::Ready`]). +//! - Progress (a task finished, or the round pushed changes): another round +//! ([`Next::Again`]). The runaway ceiling is the same as a run's steps. +//! - Two rounds in a row with no progress stop the work ([`Next::Stop`]): +//! the run says which tasks are still not done and why, its status is +//! `needs_input` (never `completed`), and the pull request stays a draft. +//! +//! The progress rule is the one ticket runs use between steps +//! (`steps::stalled_after`, `steps::MAX_STALLED_STEPS`). + +use common::run_round::{Kind, Round}; + +use super::proof::{UNFINISHED_END, UNFINISHED_START}; +use super::steps; + +/// The planned tasks a description still lists under "Not finished": one +/// per item line, without the bullet. Empty when the section isn't there. +pub fn listed(body: &str) -> Vec { + let Some(start) = body.find(UNFINISHED_START) else { + return Vec::new(); + }; + let rest = &body[start + UNFINISHED_START.len()..]; + let inner = rest.find(UNFINISHED_END).map_or(rest, |end| &rest[..end]); + inner + .lines() + .map(str::trim) + .filter_map(|l| l.strip_prefix("- ").or_else(|| l.strip_prefix("* "))) + .map(|l| l.trim().to_string()) + .filter(|l| !l.is_empty()) + .collect() +} + +/// What a planned-work round is told: every task still listed, built now, +/// in full. +pub fn round_feedback(items: &[String]) -> String { + let todo: Vec = items.iter().map(|i| format!("- [ ] {i}")).collect(); + format!( + "This pull request is open as a draft because planned work is still not done. The \ + check before it listed the tasks below under \"Not finished\". Build every one of \ + them now on this branch, in full, following the plan and the code already on the \ + branch. Write each file as soon as it is done. Change the other files only where a \ + task needs it.\n\n{}", + todo.join("\n") + ) +} + +/// The first planned-work round, parked for a fresh invocation after the +/// pull request opens. `None` when nothing is listed. +pub fn first_round(section: &str, now: chrono::DateTime) -> Option { + let items = listed(section); + if items.is_empty() { + return None; + } + // Not scoped: planned work may need files the branch doesn't change yet. + Some( + Round::start( + Kind::PlannedWork, + 1, + "", + &round_feedback(&items), + false, + now, + ) + .parked(false), + ) +} + +/// The round after `prev`, for the tasks still listed. +pub fn next_round( + prev: &Round, + items: &[String], + stalled: u32, + now: chrono::DateTime, +) -> Round { + let mut r = Round::start( + Kind::PlannedWork, + prev.number.saturating_add(1), + "", + &round_feedback(items), + false, + now, + ) + .parked(false); + r.stalled = stalled; + r +} + +/// What follows a planned-work round. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Next { + /// Nothing is listed any more: the pull request may be marked ready. + Ready, + /// Another round, with this many stalled rounds before it. + Again { stalled: u32 }, + /// The work stops: this reason names the tasks and why. + Stop(String), +} + +/// What follows a round. `before`: the tasks listed when it started; +/// `after`: the tasks the check lists now (`None` when the check couldn't +/// answer: nothing is claimed done then); `pushed_files`: the files the +/// round's commit changed. +pub fn next( + before: &[String], + after: Option<&[String]>, + pushed_files: usize, + round: &Round, +) -> Next { + let after = after.unwrap_or(before); + if after.is_empty() { + return Next::Ready; + } + let progress = after.len() < before.len() || pushed_files > 0; + if progress { + // The same runaway ceiling as a ticket run's steps: never reached by + // real work, but no loop runs forever. + if round.number >= steps::MAX_RUN_STEPS { + return Next::Stop(stop_reason( + after, + &format!( + "the work reached the safety ceiling of {} planned-work rounds", + steps::MAX_RUN_STEPS + ), + )); + } + return Next::Again { stalled: 0 }; + } + let stalled = round.stalled.saturating_add(1); + if steps::stops_for_stall(stalled) { + let last = round.number.max(2); + return Next::Stop(stop_reason( + after, + &format!( + "planned-work rounds {} and {last} made no progress: no task was finished and \ + nothing was pushed", + last - 1 + ), + )); + } + Next::Again { stalled } +} + +/// The run's status after a round: waiting on CI while there are new +/// commits or another round is parked, completed once nothing is left and +/// nothing new was pushed, and `needs_input` when the work stopped (never +/// `completed`: the tasks are still not done). +pub fn run_status(next: &Next, pushed_files: usize) -> &'static str { + use common::run_status::{AWAITING_CI, COMPLETED, NEEDS_INPUT}; + match next { + Next::Ready if pushed_files > 0 => AWAITING_CI, + Next::Ready => COMPLETED, + Next::Again { .. } => AWAITING_CI, + Next::Stop(_) => NEEDS_INPUT, + } +} + +/// Why the work stopped, with the exact tasks still not done. +pub fn stop_reason(items: &[String], why: &str) -> String { + let list: Vec = items.iter().map(|i| format!("- {i}")).collect(); + format!( + "Stopped with planned work not done: {why}. Still not done:\n{}\nThe pull request \ + stays a draft with these listed under \"Not finished\".", + list.join("\n") + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::passes::proof::{unfinished_section, Finding}; + + fn planned(detail: &str) -> Finding { + Finding { + point: "planned_work".into(), + detail: detail.into(), + settle: String::new(), + ..Default::default() + } + } + + fn now() -> chrono::DateTime { + chrono::DateTime::parse_from_rfc3339("2026-10-28T12:00:00Z") + .unwrap() + .with_timezone(&chrono::Utc) + } + + #[test] + fn the_listed_tasks_come_from_the_section_only() { + let section = unfinished_section(&[ + planned("`apps/web/src/blocks/card.tsx` is not written."), + planned("The card block is not registered in `apps/studio/schema/index.ts`."), + ]); + let body = format!("{section}\n\n## Summary\n- not a task\n"); + let items = listed(&body); + assert_eq!(items.len(), 2, "{items:?}"); + assert!(items[0].contains("card.tsx")); + assert!(listed("## Summary\n- a line\n").is_empty()); + } + + #[test] + fn the_first_round_is_parked_unscoped_with_every_task() { + let section = + unfinished_section(&[planned("`apps/web/src/blocks/card.tsx` is not written.")]); + let r = first_round(§ion, now()).unwrap(); + assert_eq!(r.kind, Kind::PlannedWork); + assert_eq!(r.number, 1); + assert_eq!(r.state, common::run_round::State::Pending); + assert!(!r.scoped); + assert!(r.feedback.contains("card.tsx")); + assert!(first_round("", now()).is_none()); + } + + #[test] + fn rounds_go_on_while_they_make_progress_and_stop_after_two_stalled() { + let three: Vec = ["a", "b", "c"].iter().map(|s| s.to_string()).collect(); + let two = three[..2].to_vec(); + let mut r = first_round( + &unfinished_section(&[planned("a"), planned("b"), planned("c")]), + now(), + ) + .unwrap(); + // A task finished: progress. + assert_eq!(next(&three, Some(&two), 0, &r), Next::Again { stalled: 0 }); + // Pushed changes, nothing finished yet: progress (the head moved). + assert_eq!(next(&two, Some(&two), 3, &r), Next::Again { stalled: 0 }); + // No change at all: one stalled round, then the second stops. + assert_eq!(next(&two, Some(&two), 0, &r), Next::Again { stalled: 1 }); + r = next_round(&r, &two, 1, now()); + match next(&two, Some(&two), 0, &r) { + Next::Stop(why) => { + assert!(why.contains("rounds 1 and 2 made no progress"), "{why}"); + assert!(why.contains("- a\n- b"), "{why}"); + } + other => panic!("{other:?}"), + } + // A check that couldn't answer claims nothing done. + assert_eq!( + next(&two, None, 0, &r).clone(), + next(&two, Some(&two), 0, &r) + ); + // Nothing left: ready. + assert_eq!(next(&two, Some(&[]), 0, &r), Next::Ready); + } + + #[test] + fn a_progressing_round_continues_up_to_the_runaway_ceiling_only() { + let items = vec!["a".to_string(), "b".to_string()]; + let mut r = first_round(&unfinished_section(&[planned("a"), planned("b")]), now()).unwrap(); + for _ in 1..steps::MAX_RUN_STEPS { + assert_eq!( + next(&items, Some(&items), 1, &r), + Next::Again { stalled: 0 } + ); + r = next_round(&r, &items, 0, now()); + } + assert!(matches!(next(&items, Some(&items), 1, &r), Next::Stop(_))); + } +} diff --git a/services/worker/src/passes/generators.rs b/services/worker/src/passes/generators.rs index 31aa9aa00..c51c4fddc 100644 --- a/services/worker/src/passes/generators.rs +++ b/services/worker/src/passes/generators.rs @@ -27,7 +27,7 @@ use tracing::{info, warn}; use common::stop_rules::tooling::{self, ToolingFailure}; use crate::clients::github::{FileOp, GitHubClient}; -use crate::clients::sandbox::EgressBlocks; +use crate::clients::sandbox::{CodegenOutcome, EgressBlocks}; use crate::passes::plan_coverage::Work; /// The tool a generator runs (a package script counts as the tool it runs). @@ -1293,74 +1293,130 @@ async fn run_in_sandbox( ) .await { - Ok(o) - if !o.passed && tooling::egress_failure("the generator", cmd, &o.output).is_some() => - { - let f = tooling::egress_failure("the generator", cmd, &o.output).unwrap_or_default(); - EgressBlocks::record(w.run_id, &f); - Ran::Blocked(f) - } - Ok(o) if o.ran && o.passed => { - EgressBlocks::clear(w.run_id); - // A changed file the sandbox couldn't hand back is a tooling - // failure, named: never "regenerated" with a file missing. - let dropped = (!o.dropped.is_empty()).then(|| dropped_reason(&o.dropped)); - if o.changed.is_empty() { - return match dropped { - Some(why) => Ran::Blocked(ToolingFailure::new(cmd, &why)), - None => Ran::Regenerated(Vec::new()), - }; + Ok(o) => match read_outcome(o, cmd, || sandbox.has_time(w.deadline)) { + Read::Refused(f) => { + EgressBlocks::record(w.run_id, &f); + Ran::Blocked(f) } - let paths: Vec = o.changed.iter().map(|(p, _)| p.clone()).collect(); - let ops: Vec = o - .changed - .into_iter() - .map(|(path, content)| FileOp::Write { path, content }) - .collect(); - let conventions = - super::load_git_conventions(state, &w.msg.team_id, &w.msg.ticket_id).await; - let message = conventions.commit_message( - &super::ticket_tokens(w.msg), - &format!("Regenerate generated files ({})", g.name), - ); - match w - .github - .batch_write(owner, name, w.branch, &message, &ops) - .await - { - Ok(_) => match dropped { - Some(why) => Ran::Blocked(ToolingFailure::new(cmd, &why)), - None => Ran::Regenerated(paths), - }, - Err(e) => Ran::Failed( - format!("its output couldn't be committed ({e})"), - String::new(), - ), + Read::Commit { changed, dropped } => { + EgressBlocks::clear(w.run_id); + if changed.is_empty() { + return match dropped { + Some(why) => Ran::Blocked(ToolingFailure::new(cmd, &why)), + None => Ran::Regenerated(Vec::new()), + }; + } + let paths: Vec = changed.iter().map(|(p, _)| p.clone()).collect(); + let ops: Vec = changed + .into_iter() + .map(|(path, content)| FileOp::Write { path, content }) + .collect(); + let conventions = + super::load_git_conventions(state, &w.msg.team_id, &w.msg.ticket_id).await; + let message = conventions.commit_message( + &super::ticket_tokens(w.msg), + &format!("Regenerate generated files ({})", g.name), + ); + match w + .github + .batch_write(owner, name, w.branch, &message, &ops) + .await + { + Ok(_) => match dropped { + Some(why) => Ran::Blocked(ToolingFailure::new(cmd, &why)), + None => Ran::Regenerated(paths), + }, + Err(e) => Ran::Failed( + format!("its output couldn't be committed ({e})"), + String::new(), + ), + } } + Read::Blocked(f) => Ran::Blocked(f), + Read::Failed(why, output) => Ran::Failed(why, output), + Read::OutOfTime => Ran::OutOfTime, + Read::NotRun(why) => Ran::NotRun(why), + }, + Err(e) => Ran::NotRun(e.to_string()), + } +} + +/// What a finished codegen build means for its generator, before anything +/// is committed. +#[derive(Debug)] +pub(crate) enum Read { + /// The sandbox's network allowlist refused a host the generator needs. + Refused(ToolingFailure), + /// It ran and passed: these files changed (to commit), and the ones the + /// sandbox couldn't hand back, named (a tooling failure when any). + Commit { + changed: Vec<(String, String)>, + dropped: Option, + }, + /// The run's tooling stopped it (CodeBuild timed the build out). + Blocked(ToolingFailure), + /// It ran and failed: why, and its output. + Failed(String, String), + /// It stopped at the step's deadline: a fresh step runs it. + OutOfTime, + /// It didn't run, with why. + NotRun(String), +} + +/// What a failed codegen build printed last, for its reason: the +/// generator's own lines, never CodeBuild's echo of the buildspec (which +/// starts every log) or the build's markers. +fn failure_excerpt(output: &str) -> String { + let lines: Vec<&str> = output + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .filter(|l| !l.starts_with("[Container]")) + .filter(|l| !l.starts_with("CODERHELM_") && !l.starts_with("===CODERHELM_")) + .collect(); + common::tail_str(lines.join("\n").trim(), 300) + .trim() + .to_string() +} + +/// Reads a finished codegen build (`has_time`: whether this step still has +/// time for a build). +pub(crate) fn read_outcome(o: CodegenOutcome, cmd: &str, has_time: impl Fn() -> bool) -> Read { + if !o.passed { + if let Some(f) = tooling::egress_failure("the generator", cmd, &o.output) { + return Read::Refused(f); } - Ok(o) if o.ran => Ran::Failed( - format!( - "running it failed: {}", - common::truncate_str(o.output.trim(), 300) - ), + } + if o.ran && o.passed { + // A changed file the sandbox couldn't hand back is a tooling + // failure, named: never "regenerated" with a file missing. + let dropped = (!o.dropped.is_empty()).then(|| dropped_reason(&o.dropped)); + return Read::Commit { + changed: o.changed, + dropped, + }; + } + if o.ran { + return Read::Failed( + format!("running it failed: {}", failure_excerpt(&o.output)), o.output, - ), - // CodeBuild timed the build out: the run's tooling, not the change. - Ok(o) - if o.output - .contains(crate::clients::sandbox::CODEGEN_TIMED_OUT) => - { - Ran::Blocked(ToolingFailure::new( - cmd, - crate::clients::sandbox::CODEGEN_TIMED_OUT, - )) - } - // A build that stopped at the step's deadline didn't fail: it needs - // a step with time for it. - Ok(o) if out_of_time(&o.output, || sandbox.has_time(w.deadline)) => Ran::OutOfTime, - Ok(o) => Ran::NotRun(o.output), - Err(e) => Ran::NotRun(e.to_string()), + ); + } + // CodeBuild timed the build out: the run's tooling, not the change. + if o.output + .contains(crate::clients::sandbox::CODEGEN_TIMED_OUT) + { + return Read::Blocked(ToolingFailure::new( + cmd, + crate::clients::sandbox::CODEGEN_TIMED_OUT, + )); + } + // A build that stopped at the step's deadline didn't fail: it needs a + // step with time for it. + if out_of_time(&o.output, has_time) { + return Read::OutOfTime; } + Read::NotRun(o.output) } /// Why a generator run that changed files the sandbox couldn't hand back @@ -1386,7 +1442,7 @@ fn out_of_time(output: &str, has_time: impl Fn() -> bool) -> bool { } /// What one pass over the affected generators found. -enum Pass { +pub(crate) enum Pass { /// Generators still out of date (empty: all up to date). Problems(Vec<(Generator, Vec, String)>), /// A generator failed for public values the codegen environment lacks: @@ -1623,7 +1679,7 @@ pub enum GateStop { NeedsTime, } -fn stop_of(p: Pass) -> Result, String)>, GateStop> { +pub(crate) fn stop_of(p: Pass) -> Result, String)>, GateStop> { match p { Pass::MissingEnv(why) => Err(GateStop::Blocked(why)), Pass::Blocked(f) => Err(GateStop::Blocked(f.reason())), diff --git a/services/worker/src/passes/incidents/a_whole_branch.rs b/services/worker/src/passes/incidents/a_whole_branch.rs new file mode 100644 index 000000000..96fdfa43e --- /dev/null +++ b/services/worker/src/passes/incidents/a_whole_branch.rs @@ -0,0 +1,134 @@ +//! a. A run built most of its plan over several steps; the plan check said +//! 5 of 7 tasks done; its last step found nothing left to write and the run +//! ended "I ran but produced no file changes" with generic questions, +//! although the branch held all the work. +//! +//! Guarantee: a step that writes nothing is judged on the whole branch (its +//! diff against the base, every step summed). With work on the branch the +//! run goes on to the checks and the pull request. + +use super::fixture::*; +use crate::passes::plan_coverage; +use crate::passes::run_end::{self, Empty}; + +const OLD: &str = "I ran but produced no file changes"; + +/// The pipeline's ending for a step whose implement wrote nothing, as +/// `run_passes` reads it: the branch's work files, the plan's tasks, the +/// coder's own questions, whether the ticket names a file. +fn last_step_writes_nothing(gh: &FakeGitHub, coder_notes: &str, ticket: &str) -> Ending { + let mut end = Ending::default(); + let tasks = plan_coverage::plan_tasks(&plan_tasks_md()); + let changed = gh.changed(BRANCH); + let cov = plan_coverage::coverage(&tasks, &changed); + end.said(plan_coverage::progress_note(&cov)); + let work = run_end::work_files(&changed, TICKET); + match run_end::judge( + Some(&work), + &tasks, + &run_end::coder_questions(coder_notes), + run_end::ticket_names_files(ticket), + ) { + Empty::Carry(files) => { + end.said(format!( + "This step wrote no new file; the branch holds the run's work on {} file(s): checking it against the plan", + files.len() + )); + // The run goes on: the plan check, the generator check, the + // proof check and the pull request. + end.status = "checks".into(); + } + Empty::Ask(qs) => { + end.said(qs.join("\n")); + end.status = common::run_status::NEEDS_INPUT.into(); + } + Empty::Unbuilt(reason) => { + end.said(reason); + end.status = common::run_status::FAILED.into(); + } + Empty::Generic => { + end.said(format!("{OLD} for this issue.")); + end.status = common::run_status::NEEDS_INPUT.into(); + } + } + end +} + +#[test] +fn a_last_step_that_writes_nothing_is_judged_on_the_whole_branch() { + let mut gh = FakeGitHub::new(); + // Steps 1 to 3 built five of the planned files; the plan files sit + // beside them. + gh.commit( + "step-1", + BRANCH, + &[ + ( + "apps/studio/schemaTypes/blocks/card.ts", + "export const card = {}", + ), + ( + "apps/studio/schemaTypes/index.ts", + "export * from './blocks/card'", + ), + ("openspec/specs/gh-41/tasks.md", "- [x] ..."), + ], + ); + gh.commit( + "step-2", + BRANCH, + &[ + ("apps/web/src/blocks/card.tsx", "export function Card() {}"), + ("apps/web/src/blocks/index.ts", "card: Card"), + ], + ); + gh.commit( + "step-3", + BRANCH, + &[("apps/web/src/lib/sanity/queries.ts", "card { title }")], + ); + let end = last_step_writes_nothing( + &gh, + "Everything in the plan is on the branch.", + "Add a card block", + ); + assert!( + end.says("Plan check: 5 of 7 planned tasks done"), + "{:?}", + end.words + ); + assert_eq!(end.status, "checks", "{:?}", end.words); + assert!(end.says("the branch holds the run's work on 5 file(s)")); + end.never_says(OLD); + end.never_says("Which files or components should change?"); +} + +#[test] +fn a_branch_with_only_the_plan_files_is_unbuilt_work_named_not_a_generic_question() { + let mut gh = FakeGitHub::new(); + gh.commit( + "step-1", + BRANCH, + &[("openspec/specs/gh-41/tasks.md", "- [ ] ...")], + ); + let end = last_step_writes_nothing(&gh, "", "Add a card block"); + assert_eq!(end.status, common::run_status::FAILED); + assert!(end.says("apps/web/src/blocks/card.tsx"), "{:?}", end.words); + assert!(end.says("That is CoderHelm's miss")); + end.never_says(OLD); +} + +#[test] +fn the_pipeline_reads_the_branch_before_it_judges_an_empty_step() { + let rp = run_passes_src(); + let judge = rp.find("let mut verdict = run_end::judge(").unwrap(); + let work = rp.find("run_end::work_files(&c, &msg.ticket_id)").unwrap(); + assert!( + work < judge, + "the branch's work is read before the judgment" + ); + let changed = &rp[..work]; + assert!(changed.rfind("plan_coverage::changed_files(").is_some()); + // The generic ending is only for a verdict that found nothing anywhere. + assert!(rp.contains("run_end::Empty::Generic => {}")); +} diff --git a/services/worker/src/passes/incidents/b_open_pr_retry.rs b/services/worker/src/passes/incidents/b_open_pr_retry.rs new file mode 100644 index 000000000..85544af9b --- /dev/null +++ b/services/worker/src/passes/incidents/b_open_pr_retry.rs @@ -0,0 +1,147 @@ +//! b. A person retried a ticket whose earlier run had an open pull request. +//! The retry started over on the same branch while the earlier run was +//! still fixing CI on it: two writers on one branch, and a second PR. +//! +//! Guarantee: a retry continues the earlier run's open pull request as its +//! update, on its branch, and opens no other. While the earlier run still +//! works on it (running, waiting on CI, a writer slot held, a round under +//! way or parked), the retry stops before writing anything and says why. + +use super::fixture::*; +use crate::passes::pr_holder::{self, Holder}; +use crate::passes::ticket_history::{PriorRun, TicketHistory}; + +const RUN_1: &str = "01JRUNEARLIER0000000000000"; +const RUN_2: &str = "01JRUNRETRY000000000000000"; +const PR: u64 = 12; + +fn history() -> TicketHistory { + TicketHistory { + runs: vec![PriorRun { + run_id: RUN_1.into(), + status: "completed".into(), + repo: format!("{OWNER}/{REPO}"), + pr_number: PR, + ..Default::default() + }], + ..Default::default() + } +} + +/// The retry, as `run_passes` runs it on a branch with an open pull +/// request: find the earlier runs that opened it, read each one's record, +/// and continue or stop. `record` is the earlier run's DynamoDB item. +fn retry( + gh: &mut FakeGitHub, + record: std::collections::HashMap, + now: chrono::DateTime, +) -> Ending { + let mut end = Ending::default(); + let pr = gh.open_pr_for_branch(BRANCH).expect("the earlier run's PR"); + let number = pr["number"].as_u64().unwrap(); + let earlier = pr_holder::holder_runs(&history(), &format!("{OWNER}/{REPO}"), number); + assert_eq!(earlier, vec![RUN_1.to_string()]); + let me = pr_holder::holder_name(RUN_2); + for run in &earlier { + let h = Holder::from_item(run, &record); + if let Some(why) = pr_holder::busy(&h, now, &me) { + end.said(pr_holder::busy_note(number, run, &why)); + end.status = common::run_status::COVERED_BY_PR.into(); + end.pr = Some(number); + return end; + } + } + end.said(pr_holder::continue_note(number, &earlier)); + gh.commit(&me, BRANCH, &[("apps/web/src/blocks/card.tsx", "v2")]); + end.status = common::run_status::AWAITING_CI.into(); + end.pr = Some(number); + end +} + +fn with_open_pr() -> FakeGitHub { + let mut gh = FakeGitHub::new(); + gh.commit(RUN_1, BRANCH, &[("apps/web/src/blocks/card.tsx", "v1")]); + gh.prs.push(FakePr { + number: PR, + branch: BRANCH.into(), + body: "## Summary\nAdds the card block.".into(), + draft: false, + }); + gh +} + +fn now() -> chrono::DateTime { + chrono::DateTime::parse_from_rfc3339("2026-10-28T15:00:00Z") + .unwrap() + .with_timezone(&chrono::Utc) +} + +#[test] +fn a_retry_continues_the_earlier_runs_pull_request() { + let mut gh = with_open_pr(); + let end = retry(&mut gh, run_item(&[("status", s("completed"))]), now()); + assert_eq!(end.status, common::run_status::AWAITING_CI); + assert_eq!(end.pr, Some(PR)); + assert!(end.says("continues it as its update, on its branch, and opens no other")); + assert_eq!(gh.prs.len(), 1, "no second pull request"); + assert_eq!(gh.writes.last().unwrap().1, pr_holder::holder_name(RUN_2)); +} + +#[test] +fn a_retry_never_writes_while_the_earlier_run_works_on_the_branch() { + let later = now().timestamp() + 600; + let busy_records = [ + run_item(&[("status", s("awaiting_ci"))]), + run_item(&[("status", s("running"))]), + run_item(&[ + ("status", s("completed")), + ("writer_until", n(later)), + ("writer_holder", s("feedback#01JFEEDBACK")), + ]), + // A planned-work round parked on the earlier run's PR. + run_item(&[ + ("status", s("awaiting_ci")), + ( + common::run_round::FIELD, + crate::passes::finish_planned::first_round( + &crate::passes::proof::unfinished_section(&[crate::passes::proof::Finding { + point: "planned_work".into(), + detail: "The card component is not written.".into(), + ..Default::default() + }]), + now(), + ) + .unwrap() + .to_attr(), + ), + ]), + ]; + for record in busy_records { + let mut gh = with_open_pr(); + let writes_before = gh.writes.len(); + let end = retry(&mut gh, record.clone(), now()); + assert_eq!(end.status, common::run_status::COVERED_BY_PR, "{record:?}"); + assert!( + end.says("Stopped before writing anything"), + "{:?}", + end.words + ); + assert!(end.says("Two runs never write the same branch")); + assert_eq!( + gh.writes.len(), + writes_before, + "nothing written: {record:?}" + ); + assert_eq!(gh.prs.len(), 1); + } +} + +#[test] +fn the_pipeline_claims_the_earlier_runs_before_it_writes() { + let rp = run_passes_src(); + let claim = rp.find("pr_holder::claim(").unwrap(); + let implement = rp.find("implement::run(").unwrap(); + assert!(claim < implement, "the claim comes before any write"); + assert!(rp.contains("pr_holder::stop_busy(")); + assert!(rp.contains("pr_holder::continue_note(")); +} diff --git a/services/worker/src/passes/incidents/c_codegen_egress.rs b/services/worker/src/passes/incidents/c_codegen_egress.rs new file mode 100644 index 000000000..3ce7dd5fd --- /dev/null +++ b/services/worker/src/passes/incidents/c_codegen_egress.rs @@ -0,0 +1,117 @@ +//! c. The studio's typegen ran in the sandbox with the team's network +//! allowlist on. It needed the CMS API, which wasn't on the list; the proxy +//! printed `CODERHELM_EGRESS_BLOCKED `, the generator failed, and the +//! run ended "its generated files were not regenerated", blaming the change. +//! +//! Guarantee: a build that runs a generator may reach the hosts that +//! generator needs. If a host is still refused, the run stops as a tooling +//! failure that names the host, never as the change's failure. + +use super::fixture::*; +use crate::clients::sandbox::{self, EgressBlocks}; +use crate::passes::generators::{self, GateStop, Pass, Read}; + +const OLD: &str = "its generated files were not regenerated"; + +#[test] +fn a_generator_build_may_reach_the_hosts_its_generator_needs() { + let repo = monorepo(); + let hosts = generators::required_hosts(&repo, &codegen_env()); + assert!( + common::agent_policy::sandbox::domain_allowed(&hosts, CMS_HOST), + "{hosts:?}" + ); + let cmds = generators::generator_commands(&repo); + // The team limits the network to the package registries. + let team = "registry.npmjs.org,github.com"; + let codegen = sandbox::build_allowlist(Some(team), &hosts, true).unwrap(); + let allowed: Vec = codegen.split(',').map(str::to_string).collect(); + assert!(common::agent_policy::sandbox::domain_allowed( + &allowed, CMS_HOST + )); + // A check build that runs the typegen gets them too; one that doesn't, + // doesn't: a limited network stays limited. + assert!(sandbox::runs_generator( + &format!("cd apps/studio && {} && pnpm run lint", cmds[0]), + &cmds + )); + let lint = sandbox::build_allowlist( + Some(team), + &hosts, + sandbox::runs_generator("pnpm run lint", &cmds), + ); + assert_eq!(lint.as_deref(), Some(team)); +} + +/// The generator gate's ending for one codegen build: the sandbox's +/// archive and log read by the real `codegen_outcome`, the real +/// `read_outcome`, and the pipeline's stop. +async fn gate_ending(run_id: &str, sb: &FakeSandbox) -> Ending { + let mut end = Ending::default(); + let cmd = "cd apps/studio && pnpm run typegen"; + let o = sandbox::codegen_outcome(sb, "/aws/codebuild/sandbox", "s1", "out.tgz", false).await; + let pass = match generators::read_outcome(o, cmd, || true) { + Read::Refused(f) => { + EgressBlocks::record(run_id, &f); + Pass::Blocked(f) + } + other => panic!("not read as refused: {other:?}"), + }; + match generators::stop_of(pass) { + Err(GateStop::Blocked(why)) => { + end.said(super::super::stopped_keeping(&why, BRANCH)); + end.status = common::run_status::FAILED.into(); + } + Err(GateStop::NeedsTime) => end.status = "continues".into(), + Ok(_) => end.status = "checks".into(), + } + end +} + +#[tokio::test] +async fn a_refused_host_is_a_tooling_failure_naming_it() { + let run_id = "01JRUNEGRESS00000000000000"; + let log = codebuild_log(&[ + "Error: getaddrinfo ENOTFOUND proj9.api.sanity.io", + &format!("CODERHELM_EGRESS_BLOCKED {CMS_HOST}"), + "CODERHELM_CODEGEN_END exit=1", + ]); + let end = gate_ending(run_id, &FakeSandbox::new(vec![], log)).await; + assert_eq!(end.status, common::run_status::FAILED); + assert!(end.says(CMS_HOST), "{:?}", end.words); + assert!(end.says("The work so far is kept on branch")); + end.never_says(OLD); + end.never_says("the change failed"); + // A later step of the run that can't build still reports the host. + let kept = EgressBlocks::last(run_id).expect("the refusal is kept for the run"); + assert!(kept.reason().contains(CMS_HOST)); + EgressBlocks::clear(run_id); +} + +#[tokio::test] +async fn the_echoed_grep_of_the_egress_log_is_not_a_refusal() { + // The buildspec's own `grep CODERHELM_EGRESS_BLOCKED` line is echoed in + // every log; only the proxy's line of its own names a refused host. + let log = codebuild_log(&["CODERHELM_CODEGEN_END exit=1"]); + let o = sandbox::codegen_outcome( + &FakeSandbox::new(vec![], log), + "/aws/codebuild/sandbox", + "s1", + "out.tgz", + false, + ) + .await; + assert!(matches!( + generators::read_outcome(o, "pnpm run typegen", || true), + Read::Failed(..) + )); +} + +#[test] +fn the_pipeline_stops_a_blocked_gate_with_the_gates_reason() { + let rp = run_passes_src(); + let at = rp + .find("Err(generators::GateStop::Blocked(why)) => {") + .unwrap(); + assert!(rp[at..at + 400].contains("stopped_keeping(&why, &kept)")); +} diff --git a/services/worker/src/passes/incidents/d_echoed_markers.rs b/services/worker/src/passes/incidents/d_echoed_markers.rs new file mode 100644 index 000000000..ed9ff5344 --- /dev/null +++ b/services/worker/src/passes/incidents/d_echoed_markers.rs @@ -0,0 +1,76 @@ +//! d. CodeBuild echoes every buildspec command into the log before running +//! it, and the codegen command holds the upload markers inside `echo "..."`. +//! The worker read the echoed text as the build's result: every build +//! without an archive "could not be uploaded", and the generator's own +//! failure (or its upload) was never seen. +//! +//! Guarantee: a marker counts only on a line of its own, printed by the +//! build; the exit code is the last one the build printed. + +use super::fixture::*; +use crate::clients::sandbox; +use crate::passes::generators::{self, Read}; + +const OLD: &str = "could not be uploaded"; + +async fn outcome(sb: FakeSandbox) -> sandbox::CodegenOutcome { + sandbox::codegen_outcome(&sb, "/aws/codebuild/sandbox", "s1", "out.tgz", true).await +} + +#[tokio::test] +async fn a_failed_generator_is_read_as_its_failure_not_an_upload_problem() { + let log = codebuild_log(&[ + "Error: Unknown type \"cardBlock\" in schemaTypes/index.ts", + "CODERHELM_CODEGEN_END exit=1", + ]); + assert!( + log.contains("===CODERHELM_CODEGEN_UPLOAD_FAILED==="), + "the echo holds it" + ); + let o = outcome(FakeSandbox::new(vec![], log)).await; + assert!(o.ran && !o.passed, "{}", o.output); + let mut end = Ending::default(); + match generators::read_outcome(o, "pnpm run typegen", || true) { + Read::Failed(why, _) => end.said(why), + other => panic!("{other:?}"), + } + assert!(end.says("Unknown type \"cardBlock\""), "{:?}", end.words); + end.never_says(OLD); +} + +#[tokio::test] +async fn an_upload_the_build_printed_is_read_again_when_the_first_read_was_empty() { + let archive = tarball(&[(SCHEMA_JSON, b"{\"types\":[]}".to_vec())]); + let log = codebuild_log(&[ + "CODERHELM_CODEGEN_END exit=0", + "===CODERHELM_CODEGEN_UPLOADED===", + ]); + // The first archive read comes back empty (a transient S3 read). + let o = outcome(FakeSandbox::new(vec![Vec::new(), archive], log)).await; + assert!(o.ran && o.passed); + assert_eq!(o.changed.len(), 1, "{}", o.output); + assert_eq!(o.changed[0].0, SCHEMA_JSON); +} + +#[tokio::test] +async fn a_printed_upload_failure_is_one() { + let log = codebuild_log(&[ + "CODERHELM_CODEGEN_END exit=0", + "upload failed: AccessDenied", + "===CODERHELM_CODEGEN_UPLOAD_FAILED===", + ]); + let o = outcome(FakeSandbox::new(vec![], log)).await; + assert!(!o.ran); + assert!(o.output.contains(OLD), "{}", o.output); +} + +#[tokio::test] +async fn a_clean_build_with_nothing_to_regenerate_is_up_to_date() { + let log = codebuild_log(&["CODERHELM_CODEGEN_END exit=0"]); + let o = outcome(FakeSandbox::new(vec![], log)).await; + assert!(o.ran && o.passed && o.changed.is_empty()); + assert!(matches!( + generators::read_outcome(o, "pnpm run typegen", || true), + Read::Commit { ref changed, dropped: None } if changed.is_empty() + )); +} diff --git a/services/worker/src/passes/incidents/e_large_generated_output.rs b/services/worker/src/passes/incidents/e_large_generated_output.rs new file mode 100644 index 000000000..3b9791955 --- /dev/null +++ b/services/worker/src/passes/incidents/e_large_generated_output.rs @@ -0,0 +1,118 @@ +//! e. The studio's typegen changed two files: `apps/studio/schema.json` and +//! the site's types, written through `../web/...` and over 5 MB. The sandbox +//! dropped the large one without a word; the run said "regenerated 1 +//! file(s)", the plan check found the types task not done, and the run +//! ended with no pull request. +//! +//! Guarantee: every file a generator changes is committed (or named as a +//! tooling failure when it can't be); paths are spelled one way; and a +//! generated task its generator settled is done in every check. + +use super::fixture::*; +use crate::clients::sandbox; +use crate::passes::generators::{self, Read}; +use crate::passes::plan_coverage; +use crate::passes::proof; + +const OLD: &str = "regenerated 1 file(s)"; + +fn large_types() -> Vec { + let line = "export type CardBlock = { _type: 'cardBlock'; title?: string };\n"; + line.repeat(7 * 1024 * 1024 / line.len() + 1).into_bytes() +} + +#[tokio::test] +async fn a_large_generated_file_written_through_a_parent_path_is_committed_and_counted_done() { + // The generator, as detection reads it from the studio's config. + let repo = monorepo(); + let gens = generators::detect(&repo); + let typegen = gens + .iter() + .find(|g| g.outputs.iter().any(|o| o == TYPES)) + .unwrap_or_else(|| panic!("the studio typegen writes {TYPES}: {gens:?}")); + assert!(typegen.outputs.iter().all(|o| !o.contains(".."))); + + // The build packs both changed files from the repository root. + let types = large_types(); + assert!(types.len() > 5 * 1024 * 1024); + let archive = tarball(&[ + (SCHEMA_JSON, b"{\"types\":[\"cardBlock\"]}".to_vec()), + (TYPES, types), + ]); + let log = codebuild_log(&[ + "CODERHELM_CODEGEN_END exit=0", + "===CODERHELM_CODEGEN_UPLOADED===", + ]); + let o = sandbox::codegen_outcome( + &FakeSandbox::new(vec![archive], log), + "/aws/codebuild/sandbox", + "s1", + "out.tgz", + true, + ) + .await; + let mut end = Ending::default(); + let committed = match generators::read_outcome(o, "pnpm run typegen", || true) { + Read::Commit { + changed, + dropped: None, + } => changed.into_iter().map(|(p, _)| p).collect::>(), + other => panic!("both files come back: {other:?}"), + }; + assert_eq!(committed, vec![SCHEMA_JSON.to_string(), TYPES.to_string()]); + let mut gh = FakeGitHub::new(); + gh.commit("generator", BRANCH, &[(SCHEMA_JSON, "new"), (TYPES, "new")]); + gh.commit( + "coder", + BRANCH, + &[ + ("apps/studio/schemaTypes/blocks/card.ts", "x"), + ("apps/studio/schemaTypes/index.ts", "x"), + ("apps/web/src/blocks/card.tsx", "x"), + ("apps/web/src/blocks/index.ts", "x"), + ("apps/web/src/lib/sanity/queries.ts", "x"), + ("e2e/events.spec.ts", "x"), + ], + ); + end.said(format!("Regenerated {} file(s)", committed.len())); + + // The plan spells the task `apps/studio/../web/...`; it is done. + let tasks = plan_coverage::plan_tasks(&plan_tasks_md()); + assert!(tasks.iter().any(|t| t.path == TYPES), "{tasks:?}"); + let settled = typegen.outputs.clone(); + let cov = plan_coverage::settle_generated( + plan_coverage::coverage(&tasks, &gh.changed(BRANCH)), + &settled, + ); + end.said(plan_coverage::progress_note(&cov)); + assert!( + end.says("Plan check: 7 of 7 planned tasks done"), + "{:?}", + end.words + ); + + // The proof judge flags the types file anyway: dropped, in either + // spelling, and nothing holds the pull request. + for spelled in [TYPES, &format!("apps/studio/{TYPES_FROM_STUDIO}")] { + let reply = judge_reply(&[( + "planned_work", + &format!("`{spelled}` is not regenerated with the card block."), + )]); + let findings = proof::parse_findings(&reply).unwrap(); + let left = proof::drop_settled_generated(findings, &settled); + assert!(proof::planned_work(&left).is_empty(), "{spelled}: {left:?}"); + assert!(proof::unfinished_section(&left).is_empty()); + } + end.status = common::run_status::AWAITING_CI.into(); + end.never_says(OLD); +} + +#[test] +fn a_file_past_the_cap_is_named_never_dropped_silently() { + let big = vec![b'a'; 2048]; + let captured = sandbox::read_changed_tar(&tarball(&[(TYPES, big)]), 200, 1024).unwrap(); + assert!(captured.files.is_empty()); + assert_eq!(captured.dropped.len(), 1); + let why = generators::dropped_reason(&captured.dropped); + assert!(why.contains(TYPES), "{why}"); +} diff --git a/services/worker/src/passes/incidents/f_steps.rs b/services/worker/src/passes/incidents/f_steps.rs new file mode 100644 index 000000000..f58338025 --- /dev/null +++ b/services/worker/src/passes/incidents/f_steps.rs @@ -0,0 +1,135 @@ +//! f. A new-feature run triaged, planned, built eight files and reached the +//! generator check with 30 seconds of its 15-minute step left. The check +//! declined to start a build and the run failed "not enough time left", +//! with the work done. Other runs stopped at a fixed step count while still +//! making progress. +//! +//! Guarantee: a gate that lacks time (the generator check, the checks, the +//! pull request) continues the run in a fresh step at that gate, as a new +//! queue message; a run whose steps make progress keeps going (20 steps and +//! more); two steps in a row without progress stop it, saying where. + +use super::fixture::*; +use crate::clients::sandbox::CodegenOutcome; +use crate::models::TicketMessage; +use crate::passes::generators::{self, GateStop, Pass, Read}; +use crate::passes::steps::{self, Gate}; + +const OLD: &str = "not enough time left"; + +#[test] +fn a_generator_build_without_time_needs_a_step_not_a_failure() { + // The sandbox declined the build at the step's deadline. + let o = CodegenOutcome { + ran: false, + passed: false, + changed: Vec::new(), + dropped: Vec::new(), + output: "codegen not run: not enough time left in this step for a sandbox build".into(), + }; + let pass = match generators::read_outcome(o, "pnpm run typegen", || false) { + Read::OutOfTime => Pass::OutOfTime, + other => panic!("{other:?}"), + }; + assert!(matches!( + generators::stop_of(pass), + Err(GateStop::NeedsTime) + )); +} + +/// One run's steps, as the queue and the run record carry them: each step +/// is a new message; each starts by comparing its progress mark with the +/// last step's. `heads[i]` is the branch head step `i + 1` starts at. +fn run_steps(heads: &[&str], at: Gate) -> (Ending, Vec) { + let mut end = Ending::default(); + let first = TicketMessage { + team_id: "TEAM#1".into(), + ticket_id: TICKET.into(), + ..Default::default() + }; + let mut sent = vec![first.clone()]; + let mut msg = first; + let mut mark: Option = None; + let mut stalled = 0; + for head in heads { + let step = steps::step_number(msg.continuation); + let now = steps::progress_mark(head, at.as_str()); + if msg.continuation > 0 { + stalled = steps::stalled_after(mark.as_deref(), &now, stalled); + if steps::stops_for_stall(stalled) { + end.said(steps::stall_reason(step, head, at.as_str(), BRANCH)); + end.status = common::run_status::FAILED.into(); + return (end, sent); + } + } + mark = Some(now); + // The step runs out of time at the gate: the next step is queued. + assert!(steps::under_ceiling(msg.continuation), "step {step}"); + msg = steps::next_message(&msg, "RUN1", 1); + sent.push(msg.clone()); + end.said(format!( + "The checks need more time than this step has left: continuing in step {} with its own time budget", + steps::step_number(msg.continuation) + )); + } + end.status = common::run_status::RUNNING.into(); + (end, sent) +} + +#[test] +fn a_run_making_progress_continues_for_twenty_steps_each_a_new_message() { + let heads: Vec = (0..20).map(|i| format!("{i:07x}aa")).collect(); + let heads: Vec<&str> = heads.iter().map(String::as_str).collect(); + let (end, sent) = run_steps(&heads, Gate::Checks); + assert_eq!(end.status, common::run_status::RUNNING, "{:?}", end.words); + assert_eq!(sent.len(), 21); + // Every step is its own message (its own receive count), one run. + for (i, m) in sent.iter().enumerate() { + assert_eq!(m.continuation as usize, i); + if i > 0 { + assert_eq!(m.continuation_run_id.as_deref(), Some("RUN1")); + } + } + let bodies: std::collections::HashSet = sent + .iter() + .map(|m| serde_json::to_string(m).unwrap()) + .collect(); + assert_eq!(bodies.len(), sent.len(), "no message is sent twice"); + end.never_says(OLD); +} + +#[test] +fn two_steps_without_progress_stop_the_run_saying_where() { + let (end, _) = run_steps( + &["aaa1111", "bbb2222", "bbb2222", "bbb2222"], + Gate::Generators, + ); + assert_eq!(end.status, common::run_status::FAILED); + assert!(end.says("made no progress"), "{:?}", end.words); + assert!(end.says("the generator check")); + assert!(end.says(&format!("kept on branch `{BRANCH}`"))); + end.never_says(OLD); +} + +#[test] +fn every_gate_that_lacks_time_hands_off_at_that_gate() { + let rp = run_passes_src(); + let needs = rp + .find("Err(generators::GateStop::NeedsTime) => {") + .unwrap(); + let after = &rp[needs..needs + 600]; + assert!(after.contains("hand_off_at(")); + assert!(after.contains("steps::Gate::Generators")); + let pr = rp + .find("opening the pull request needs more time than this step has left") + .unwrap(); + assert!(rp[pr - 400..pr].contains("steps::Gate::Checks")); + assert!(!rp.contains(OLD)); + // A hand-off is a new message on the queue, never a retry of this one. + let src = include_str!("../mod.rs"); + let hand_off = fn_src(src, "\nasync fn hand_off_at("); + assert!(hand_off.contains("try_auto_continue(")); + let cont = fn_src(src, "\nasync fn try_auto_continue("); + assert!(cont.contains("steps::next_message(")); + assert!(cont.contains(".send_message()")); +} diff --git a/services/worker/src/passes/incidents/fixture.rs b/services/worker/src/passes/incidents/fixture.rs new file mode 100644 index 000000000..fc3c954d1 --- /dev/null +++ b/services/worker/src/passes/incidents/fixture.rs @@ -0,0 +1,390 @@ +//! The suite's monorepo and the fakes at its edges. +//! +//! The repository every case works on is invented and generic: +//! +//! - `apps/studio`: the CMS studio, its schema, and a `typegen` script that +//! writes `apps/studio/schema.json` and, through a `../` path, +//! `apps/web/src/lib/sanity/sanity.types.ts`; +//! - `apps/web`: the site that reads the CMS; +//! - `e2e/`: end-to-end specs and the map of which spec tests which page. +//! +//! The edges are faked, nothing else: +//! +//! - GitHub: [`FakeGitHub`] holds the base branch, the run's branch and the +//! open pull requests, and answers in the shapes GitHub returns (a compare +//! with `files[].filename`, a pull request with `number`, `head`, `body`). +//! - The model: [`judge_reply`] writes a reply the way the proof judge +//! answers, read by the real parser. +//! - The sandbox: [`FakeSandbox`] is a `CodegenSource` with a real tar.gz +//! archive and a CodeBuild-shaped log ([`codebuild_log`]), read by the +//! real `codegen_outcome`. +//! - DynamoDB: [`run_item`] is a run record as the table holds it. + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::io::Write; +use std::sync::Mutex; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde_json::{json, Value}; + +use crate::clients::sandbox::{self, Captured, CodegenSource}; +use crate::passes::generators::RepoFiles; + +pub const OWNER: &str = "acme"; +pub const REPO: &str = "site"; +pub const BASE: &str = "main"; +pub const BRANCH: &str = "coderhelm/gh-41-card-block"; +pub const TICKET: &str = "GH-41"; +/// Where the studio's typegen writes the site's types, as its config +/// spells it (from `apps/studio`). +pub const TYPES_FROM_STUDIO: &str = "../web/src/lib/sanity/sanity.types.ts"; +/// The same file from the repository root. +pub const TYPES: &str = "apps/web/src/lib/sanity/sanity.types.ts"; +pub const SCHEMA_JSON: &str = "apps/studio/schema.json"; +/// The CMS project's read API host. +pub const CMS_HOST: &str = "proj9.api.sanity.io"; + +/// The monorepo's files that detection reads, and its tree. +pub fn monorepo() -> RepoFiles { + let files: Vec<(&str, String)> = vec![ + ("package.json", r#"{"private":true,"scripts":{"dev":"turbo dev"}}"#.into()), + ( + "apps/studio/package.json", + r#"{"scripts":{"typegen":"sanity schema extract && sanity typegen generate","deploy":"sanity deploy"}}"#.into(), + ), + ( + "apps/studio/sanity-typegen.json", + format!( + r#"{{"path":"../web/src/**/*.{{ts,tsx}}","schema":"schema.json","generates":"{TYPES_FROM_STUDIO}"}}"# + ), + ), + ( + "apps/studio/sanity.config.ts", + "export default defineConfig({ projectId: process.env.SANITY_STUDIO_PROJECT_ID!, dataset: 'staging' })".into(), + ), + ("apps/web/package.json", r#"{"scripts":{"build":"next build"}}"#.into()), + ( + "e2e/test-map.json", + r#"{"apps/web/src/app/events/page.tsx":["e2e/events.spec.ts"]}"#.into(), + ), + ]; + let mut tree: Vec = files.iter().map(|(p, _)| p.to_string()).collect(); + tree.extend( + [ + "pnpm-lock.yaml", + "apps/studio/schemaTypes/index.ts", + "apps/studio/schemaTypes/blocks/hero.ts", + SCHEMA_JSON, + TYPES, + "apps/web/src/app/events/page.tsx", + "apps/web/src/blocks/hero.tsx", + "e2e/events.spec.ts", + ] + .iter() + .map(|p| p.to_string()), + ); + RepoFiles { + tree, + files: files.into_iter().map(|(p, t)| (p.to_string(), t)).collect(), + } +} + +/// The studio's public codegen environment. +pub fn codegen_env() -> Vec<(String, String)> { + vec![ + ("SANITY_STUDIO_PROJECT_ID".into(), "proj9".into()), + ("SANITY_STUDIO_DATASET".into(), "staging".into()), + ] +} + +/// The plan for the card-block ticket: one task per file, the generated +/// types among them. +pub fn plan_tasks_md() -> String { + [ + "- [ ] apps/studio/schemaTypes/blocks/card.ts: [create] Create the card block schema", + "- [ ] apps/studio/schemaTypes/index.ts: [modify] Register the card block", + "- [ ] apps/web/src/blocks/card.tsx: [create] Create the card component", + "- [ ] apps/web/src/blocks/index.ts: [modify] Map the card block to its component", + "- [ ] apps/web/src/lib/sanity/queries.ts: [modify] Fetch the card fields", + "- [ ] e2e/events.spec.ts: [modify] Cover the card on the events page", + &format!("- [ ] apps/studio/{TYPES_FROM_STUDIO}: Regenerate the types (generated)"), + ] + .join("\n") +} + +// ── GitHub ───────────────────────────────────────────────────────────────── + +/// An open pull request as the fake holds it. +#[derive(Debug, Clone)] +pub struct FakePr { + pub number: u64, + pub branch: String, + pub body: String, + pub draft: bool, +} + +/// GitHub, in memory: the base branch, the run's branch and the open pull +/// requests. Every write names who made it, so a case can see whether two +/// writers touched one branch. +#[derive(Debug, Default)] +pub struct FakeGitHub { + pub base: BTreeMap, + pub branches: HashMap>, + pub prs: Vec, + pub writes: Vec<(String, String)>, +} + +impl FakeGitHub { + /// The monorepo on `main`, and the run's branch cut from it. + pub fn new() -> FakeGitHub { + let base: BTreeMap = monorepo() + .tree + .iter() + .map(|p| (p.clone(), format!("// {p}\n"))) + .collect(); + let mut branches = HashMap::new(); + branches.insert(BRANCH.to_string(), base.clone()); + FakeGitHub { + base, + branches, + ..Default::default() + } + } + + /// One commit by `writer` on `branch`. + pub fn commit(&mut self, writer: &str, branch: &str, files: &[(&str, &str)]) { + let b = self.branches.entry(branch.to_string()).or_default(); + for (p, c) in files { + b.insert(p.to_string(), c.to_string()); + } + self.writes.push((branch.to_string(), writer.to_string())); + } + + /// `GET /repos/{o}/{r}/compare/{base}...{branch}`: the files the branch + /// changes. + pub fn compare(&self, branch: &str) -> Value { + let empty = BTreeMap::new(); + let head = self.branches.get(branch).unwrap_or(&empty); + let files: Vec = head + .iter() + .filter(|(p, c)| self.base.get(*p) != Some(*c)) + .map(|(p, _)| { + json!({ + "filename": p, + "status": if self.base.contains_key(p) { "modified" } else { "added" }, + }) + }) + .collect(); + json!({ "files": files, "commits": [] }) + } + + /// The branch's changed paths, as `plan_coverage::changed_files` reads + /// the compare. + pub fn changed(&self, branch: &str) -> Vec { + self.compare(branch)["files"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|f| f["filename"].as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default() + } + + /// `GET /repos/{o}/{r}/pulls?head={o}:{branch}&state=open`, first item. + pub fn open_pr_for_branch(&self, branch: &str) -> Option { + self.prs.iter().find(|p| p.branch == branch).map(|p| { + json!({ + "number": p.number, + "html_url": format!("https://github.com/{OWNER}/{REPO}/pull/{}", p.number), + "title": "Add the card block", + "draft": p.draft, + "state": "open", + "body": p.body, + "head": { "ref": p.branch, "sha": "f00d" }, + "base": { "ref": BASE, "sha": "ba5e" }, + }) + }) + } + + pub fn pr(&self, number: u64) -> &FakePr { + self.prs.iter().find(|p| p.number == number).unwrap() + } + + pub fn pr_mut(&mut self, number: u64) -> &mut FakePr { + self.prs.iter_mut().find(|p| p.number == number).unwrap() + } +} + +// ── The model ────────────────────────────────────────────────────────────── + +/// A proof judge reply, as the model writes it: some prose, then the +/// findings in a fenced JSON block. +pub fn judge_reply(findings: &[(&str, &str)]) -> String { + let list: Vec = findings + .iter() + .map(|(point, detail)| json!({"point": point, "detail": detail, "settle": ""})) + .collect(); + format!( + "I read the diff against the plan.\n\n```json\n{}\n```\n", + json!({ "findings": list }) + ) +} + +// ── The sandbox ──────────────────────────────────────────────────────────── + +/// A real tar.gz of changed files, paths from the repository root, as the +/// codegen build packs them. +pub fn tarball(files: &[(&str, Vec)]) -> Vec { + let gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + let mut ar = tar::Builder::new(gz); + for (path, data) in files { + let mut h = tar::Header::new_gnu(); + h.set_size(data.len() as u64); + h.set_mode(0o644); + h.set_entry_type(tar::EntryType::Regular); + h.set_cksum(); + ar.append_data(&mut h, format!("./{path}"), data.as_slice()) + .unwrap(); + } + let gz = ar.into_inner().unwrap(); + let mut out = gz.finish().unwrap(); + out.flush().unwrap(); + out +} + +/// A CodeBuild log of a codegen build: CodeBuild echoes each buildspec +/// command before it runs it (the echo holds the marker text inside an +/// `echo "..."`), then the commands' own output follows. +pub fn codebuild_log(printed: &[&str]) -> String { + let mut log = String::from( + "[Container] 2026/10/28 03:21:02 Running command cd \"$SRC\" && sh -c \"$CODEGEN_CMD\"; CODE=$?; \ + echo \"CODERHELM_CODEGEN_END exit=$CODE\"; if [ $CODE -eq 0 ]; then \ + if aws s3 cp out.tgz \"$OUT\"; then echo \"===CODERHELM_CODEGEN_UPLOADED===\"; \ + else echo \"===CODERHELM_CODEGEN_UPLOAD_FAILED===\"; fi; fi\n\ + [Container] 2026/10/28 03:21:03 Running command if [ -f /tmp/egress.log ]; then grep \ + CODERHELM_EGRESS_BLOCKED /tmp/egress.log; fi\n\ + > studio@ typegen /codebuild/src/apps/studio\n\ + > sanity schema extract && sanity typegen generate\n", + ); + for l in printed { + log.push_str(l); + log.push('\n'); + } + log +} + +/// The sandbox's codegen build, recorded: the archives it hands back, in +/// the order they are read (a retry reads the next), and its log. +pub struct FakeSandbox { + archives: Mutex>>, + pub log: String, +} + +impl FakeSandbox { + pub fn new(archives: Vec>, log: String) -> FakeSandbox { + FakeSandbox { + archives: Mutex::new(archives.into()), + log, + } + } +} + +#[async_trait::async_trait] +impl CodegenSource for FakeSandbox { + async fn changed_files(&self, _out_key: &str) -> Captured { + let next = self.archives.lock().unwrap().pop_front(); + match next { + Some(bytes) if !bytes.is_empty() => sandbox::read_archive(&bytes).unwrap(), + _ => Captured::default(), + } + } + + async fn build_log(&self, _group: &str, _stream: &str) -> String { + self.log.clone() + } + + fn log_retry_delay(&self) -> std::time::Duration { + std::time::Duration::ZERO + } +} + +// ── DynamoDB ─────────────────────────────────────────────────────────────── + +/// A run record as the runs table holds it. +pub fn run_item(fields: &[(&str, AttributeValue)]) -> HashMap { + fields + .iter() + .map(|(k, v)| (k.to_string(), v.clone())) + .collect() +} + +pub fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +pub fn n(v: i64) -> AttributeValue { + AttributeValue::N(v.to_string()) +} + +// ── The run's end ────────────────────────────────────────────────────────── + +/// How a run ended, as a person sees it: its status, its pull request (if +/// any), and every word it wrote (progress notes, the stop reason, the PR +/// description, ticket comments). +#[derive(Debug, Default, Clone)] +pub struct Ending { + pub status: String, + pub pr: Option, + pub draft: bool, + pub words: Vec, +} + +impl Ending { + pub fn said(&mut self, text: impl Into) { + self.words.push(text.into()); + } + + /// The old failure never appears in anything the run wrote. + pub fn never_says(&self, old: &str) { + let old_l = old.to_lowercase(); + for w in &self.words { + assert!( + !w.to_lowercase().contains(&old_l), + "the old failure is back: {old:?} in {w:?}" + ); + } + } + + pub fn says(&self, part: &str) -> bool { + self.words.iter().any(|w| w.contains(part)) + } +} + +/// `run_passes` (the single-repository pipeline) as source text, for the +/// checks that the pipeline still calls a decision at its place. +pub fn run_passes_src() -> &'static str { + let src = include_str!("../mod.rs"); + let start = src.find("\nasync fn run_passes(").unwrap(); + let end = start + src[start + 1..].find("\nasync fn ").unwrap(); + &src[start..end] +} + +/// One function of `src`, from its `fn` line to the next top-level item. +pub fn fn_src<'a>(src: &'a str, head: &str) -> &'a str { + let start = src.find(head).unwrap_or_else(|| panic!("{head} is gone")); + let rest = &src[start + head.len()..]; + let end = [ + "\nasync fn ", + "\nfn ", + "\npub(crate) ", + "\npub fn ", + "\n#[", + "\n///", + ] + .iter() + .filter_map(|m| rest.find(m)) + .min() + .unwrap_or(rest.len()); + &src[start..start + head.len() + end] +} diff --git a/services/worker/src/passes/incidents/g_large_plan.rs b/services/worker/src/passes/incidents/g_large_plan.rs new file mode 100644 index 000000000..105b5438d --- /dev/null +++ b/services/worker/src/passes/incidents/g_large_plan.rs @@ -0,0 +1,69 @@ +//! g. A mechanical ticket needed 40 files. The planner was capped, the plan +//! was narrowed to fewer files with a "split the ticket" note, and the run +//! built only part of what the ticket asked. +//! +//! Guarantee: a plan holds every file the ticket needs, however many; no +//! check caps, trims or narrows it by count, and every later round is told +//! every task. + +use super::fixture::*; +use crate::passes::plan_coverage; + +fn forty() -> String { + (0..40) + .map(|i| format!("- [ ] apps/web/src/blocks/block_{i:02}.tsx: [modify] Read the new `variant` field\n")) + .collect() +} + +#[test] +fn a_forty_file_plan_is_kept_whole_through_every_check() { + let md = forty(); + assert_eq!(super::super::plan_task_files(&md).len(), 40); + let tasks = plan_coverage::plan_tasks(&md); + assert_eq!(tasks.len(), 40); + // The first step built 39 of them: the plan check names the last one. + let mut gh = FakeGitHub::new(); + let built: Vec<(String, &str)> = tasks[..39].iter().map(|t| (t.path.clone(), "x")).collect(); + let refs: Vec<(&str, &str)> = built.iter().map(|(p, c)| (p.as_str(), *c)).collect(); + gh.commit("step-1", BRANCH, &refs); + let cov = plan_coverage::coverage(&tasks, &gh.changed(BRANCH)); + let mut end = Ending::default(); + end.said(plan_coverage::progress_note(&cov)); + assert!(end.says("Plan check: 39 of 40 planned tasks done")); + let feedback = plan_coverage::round_feedback(&cov); + assert!(feedback.contains("block_39.tsx"), "{feedback}"); + // A build round told every task lists all 40. + let all = crate::passes::run_end::build_round_feedback(&tasks); + assert_eq!(all.matches("- [ ] `apps/web/src/blocks/block_").count(), 40); + // A planned-work round on the pull request lists every task left. + let items: Vec = tasks + .iter() + .map(|t| format!("`{}` is not changed.", t.path)) + .collect(); + let round = crate::passes::finish_planned::round_feedback(&items); + assert_eq!( + round.matches("- [ ] `apps/web/src/blocks/block_").count(), + 40 + ); + for old in [ + "smaller tickets", + "Plan scope too large", + "split the ticket", + ] { + end.never_says(old); + assert!(!feedback.contains(old) && !all.contains(old)); + } +} + +#[test] +fn nothing_in_the_pipeline_caps_a_plan_by_count() { + let src = include_str!("../mod.rs"); + for gone in [ + ["max_plan", "_files"].concat(), + ["narrow_scope", "_note"].concat(), + ["Plan scope", " too large"].concat(), + ] { + assert!(!src.contains(&gone), "{gone} is back"); + } + assert!(!include_str!("../plan.rs").contains(&["tasks", " maximum"].concat())); +} diff --git a/services/worker/src/passes/incidents/h_pr_updates.rs b/services/worker/src/passes/incidents/h_pr_updates.rs new file mode 100644 index 000000000..d7193e579 --- /dev/null +++ b/services/worker/src/passes/incidents/h_pr_updates.rs @@ -0,0 +1,107 @@ +//! h. A new-feature PR that CoderHelm updated over several runs: its +//! description kept describing an earlier state (a failed suite from an +//! older commit), the same ticket comment was posted twice, one question was +//! asked on every update, an e2e spec skipped itself when the CMS content +//! was missing, and a content note said it "could not look up" the content +//! while the CMS read API was public. +//! +//! Guarantee: each is caught by its own check. The description is rewritten +//! when a round lands (older rounds keep their headline only); a notice is +//! posted once per ticket; a question is asked once per ticket; a spec that +//! skips on missing content fails the feature checklist; a note that didn't +//! look while it could goes back to the planner. + +use super::fixture::*; +use crate::passes::feature::checklist; +use crate::passes::outside_work::{self, PlanFacts}; +use crate::passes::review_fix::evidence; +use common::ticket_state::{self, Notice, NoticeAction}; + +#[test] +fn the_description_drops_an_older_rounds_failure_when_a_newer_round_lands() { + let failed = evidence::Round { + date: "2026-10-26".into(), + commit: "aaa1111".into(), + headline: "Register the card block".into(), + lines: vec!["Full test suite FAILED (exit 1): `pnpm test` (12 passed, 1 failed)".into()], + }; + let passed = evidence::Round { + date: "2026-10-27".into(), + commit: "bbb2222".into(), + headline: "Map the card block to its component".into(), + lines: vec!["Full test suite passed: `pnpm test` (13 passed)".into()], + }; + let section = evidence::section(&evidence::section("", &failed), &passed); + let body = format!("## Summary\nAdds the card block.\n\n{section}\n\n## Risk\nLow"); + let mut end = Ending::default(); + end.said(evidence::current(&body)); + assert!(end.says("Register the card block")); + assert!(end.says("Full test suite passed")); + end.never_says("FAILED (exit 1)"); + // A round that lands rewrites the description from the whole diff. + let resume = include_str!("../resume.rs"); + let round = fn_src(resume, "\nasync fn run_fix_round("); + let pushed = round.find("Landed::Pushed { files }").unwrap(); + assert!(round[pushed..].contains("pr::refresh_description(")); +} + +#[test] +fn the_same_ticket_comment_from_two_runs_is_posted_once() { + let key = "outside_note"; + let first = "**Content:** add the card block on `/events` (run https://app.example.com/runs/01JA, 2026-10-27T10:00:00Z)"; + let second = "**Content:** add the card block on `/events` (run https://app.example.com/runs/01JB, 2026-10-27T10:04:00Z)"; + let posted = vec![Notice { + key: key.into(), + text_hash: ticket_state::notice_hash(key, first), + ..Default::default() + }]; + assert!(matches!( + ticket_state::notice_action(&posted, key, &ticket_state::notice_hash(key, second)), + NoticeAction::Skip(_) + )); +} + +#[test] +fn a_question_is_asked_on_the_ticket_once() { + let asked = vec![Notice { + key: super::super::question_key("Should the card link open in a new tab?"), + ..Default::default() + }]; + let next_update = vec![ + "Should the card link open in a **new tab**?".to_string(), + "Which image ratio should the card use on mobile?".to_string(), + ]; + let fresh = super::super::new_questions(&next_update, &asked); + assert_eq!(fresh, vec![&next_update[1]]); +} + +#[test] +fn an_e2e_spec_that_skips_on_missing_content_is_caught() { + let patch = "@@ -1,3 +1,9 @@\n test('card on events', async ({ page }) => {\n+ const card = await page.locator('[data-block=card]').count();\n+ if (!card) test.skip(true, 'no card content on staging');\n+ await expect(page.locator('[data-block=card]')).toBeVisible();\n });\n"; + let skips = checklist::data_skips("e2e/events.spec.ts", patch); + assert_eq!(skips.len(), 1, "{skips:?}"); + assert!(skips[0].starts_with("e2e/events.spec.ts")); + // A skip for a browser is not about content. + let platform = "@@ -1 +1,2 @@\n+ test.skip(browserName === 'webkit', 'no hover');\n"; + assert!(checklist::data_skips("e2e/events.spec.ts", platform).is_empty()); +} + +#[test] +fn a_note_that_could_not_look_up_readable_content_goes_back() { + let tree: Vec = monorepo().tree; + let files = vec![( + ".env.staging".to_string(), + "NEXT_PUBLIC_SANITY_PROJECT_ID=proj9\nNEXT_PUBLIC_SANITY_DATASET=staging\n".to_string(), + )]; + let a = outside_work::abilities(&tree, &files, &[], false); + assert!(a.source.is_some(), "the CMS read API is known"); + let note = crate::passes::fix_location::OutsideChange { + system: "the CMS".into(), + change: "Add a card block to the events page".into(), + existing: "I could not look up existing content; this assumes none exists.".into(), + ..Default::default() + }; + let gaps = outside_work::gaps(¬e, &a, PlanFacts::default()).join("\n"); + assert!(gaps.contains("the CMS read API is public"), "{gaps}"); + assert!(gaps.contains("query_content")); +} diff --git a/services/worker/src/passes/incidents/i_finished_work_pr.rs b/services/worker/src/passes/incidents/i_finished_work_pr.rs new file mode 100644 index 000000000..9444e5404 --- /dev/null +++ b/services/worker/src/passes/incidents/i_finished_work_pr.rs @@ -0,0 +1,224 @@ +//! i. A run finished 32 of 33 planned tasks, the check before the pull +//! request still found one not done after its fix round, and the run ended +//! with no pull request: the work stayed on a branch nobody looked at. Once +//! it opened a draft instead, the planned work was left for a person. +//! +//! Guarantee: finished work always ends with a pull request. Planned work +//! still not done opens it as a draft with a "Not finished" section at the +//! top; CoderHelm then keeps working those tasks in rounds on the pull +//! request while each round makes progress, rewrites the section after each, +//! and marks the pull request ready when it is empty. Only two rounds in a +//! row without progress stop it, naming the tasks and why, with the run's +//! status `needs_input`, never `completed`. + +use super::fixture::*; +use crate::passes::completeness::{self, Section}; +use crate::passes::finish_planned::{self, Next}; +use crate::passes::proof; +use crate::passes::resume::draft_hold; +use common::run_round::{Kind, Round}; + +const OLD: &str = "The work so far is kept on branch"; + +const CARD: &str = + "`apps/web/src/blocks/card.tsx` is not written: the card block has no component."; +const MAP: &str = "The card block is not mapped in `apps/web/src/blocks/index.ts`."; + +fn now() -> chrono::DateTime { + chrono::DateTime::parse_from_rfc3339("2026-10-28T16:00:00Z") + .unwrap() + .with_timezone(&chrono::Utc) +} + +/// The run reaches the pull request: the proof judge (a recorded reply) +/// still finds two planned tasks not done after its fix round. Returns the +/// draft's description and the round parked for after it opens. +fn open_the_pull_request(gh: &mut FakeGitHub, end: &mut Ending) -> Option { + let reply = judge_reply(&[ + ("planned_work", CARD), + ("planned_work", MAP), + ("ci_pending", "The site's build runs in CI."), + ]); + let gaps = proof::parse_findings(&reply).unwrap(); + let unfinished = proof::unfinished_section(&gaps); + assert!(!unfinished.is_empty()); + let body = completeness::with_section( + "## Summary\nAdds the card block.\n\n## Changes\n- The schema and query.\n", + Section::Unfinished, + unfinished.clone(), + ); + gh.prs.push(FakePr { + number: 21, + branch: BRANCH.into(), + body: body.clone(), + draft: true, + }); + end.pr = Some(21); + end.draft = true; + end.said(body); + end.status = common::run_status::AWAITING_CI.into(); + finish_planned::first_round(&unfinished, now()) +} + +/// One planned-work round as the resume runs it: the round's commit lands +/// (`pushed` files), the judge (a recorded reply) reads the branch again, +/// the section is rewritten, and the next step is decided. +fn planned_round( + gh: &mut FakeGitHub, + end: &mut Ending, + round: &Round, + pushed: &[(&str, &str)], + still_not_done: &[&str], +) -> Option { + assert_eq!(round.kind, Kind::PlannedWork); + assert!(!round.scoped, "planned work may add files"); + if !pushed.is_empty() { + gh.commit("planned_work", BRANCH, pushed); + } + let body = gh.pr(21).body.clone(); + let before = finish_planned::listed(&body); + for item in &before { + assert!( + round.feedback.contains(item.as_str()), + "the round is told every task" + ); + } + let reply = judge_reply( + &still_not_done + .iter() + .map(|d| ("planned_work", *d)) + .collect::>(), + ); + let section = proof::unfinished_section(&proof::parse_findings(&reply).unwrap()); + let after = finish_planned::listed(§ion); + gh.pr_mut(21).body = completeness::with_section(&body, Section::Unfinished, section); + let next = finish_planned::next(&before, Some(&after), pushed.len(), round); + end.status = finish_planned::run_status(&next, pushed.len()).into(); + match next { + Next::Ready => { + if draft_hold(&gh.pr(21).body, "Add the card block", false).is_none() { + gh.pr_mut(21).draft = false; + end.draft = false; + } + None + } + Next::Again { stalled } => Some(finish_planned::next_round(round, &after, stalled, now())), + Next::Stop(why) => { + end.said(why); + None + } + } +} + +#[test] +fn planned_work_left_opens_a_draft_then_coderhelm_finishes_it() { + let mut gh = FakeGitHub::new(); + let mut end = Ending::default(); + let first = open_the_pull_request(&mut gh, &mut end).expect("a planned-work round is parked"); + assert_eq!( + end.pr, + Some(21), + "finished work always ends with a pull request" + ); + assert!(gh.pr(21).draft); + assert_eq!( + draft_hold(&gh.pr(21).body, "Add the card block", false), + Some("planned work not done is listed in the description") + ); + assert!(gh + .pr(21) + .body + .contains("CoderHelm keeps working on it here")); + assert_eq!(finish_planned::listed(&gh.pr(21).body).len(), 2); + + // Round 1 writes the component: one task left. + let second = planned_round( + &mut gh, + &mut end, + &first, + &[("apps/web/src/blocks/card.tsx", "export function Card() {}")], + &[MAP], + ) + .expect("progress: another round"); + assert_eq!(second.number, 2); + assert_eq!(second.stalled, 0); + assert_eq!(end.status, common::run_status::AWAITING_CI); + assert_eq!(finish_planned::listed(&gh.pr(21).body).len(), 1); + assert!(gh.pr(21).draft); + + // Round 2 maps it: nothing left, the section goes, the PR is ready + // once CI passes on the new commit. + let none = planned_round( + &mut gh, + &mut end, + &second, + &[("apps/web/src/blocks/index.ts", "card: Card")], + &[], + ); + assert!(none.is_none()); + assert!(!proof::holds_unfinished(&gh.pr(21).body)); + assert!(!gh.pr(21).draft, "marked ready when nothing is left"); + assert_eq!(end.status, common::run_status::AWAITING_CI); + end.never_says(OLD); + end.never_says("Stopped with planned work not done"); +} + +#[test] +fn two_rounds_without_progress_stop_with_the_tasks_and_never_complete() { + let mut gh = FakeGitHub::new(); + let mut end = Ending::default(); + let first = open_the_pull_request(&mut gh, &mut end).unwrap(); + let second = planned_round(&mut gh, &mut end, &first, &[], &[CARD, MAP]) + .expect("one stalled round is not a stop"); + assert_eq!(second.stalled, 1); + let none = planned_round(&mut gh, &mut end, &second, &[], &[CARD, MAP]); + assert!(none.is_none()); + assert_eq!(end.status, common::run_status::NEEDS_INPUT); + assert_ne!(end.status, common::run_status::COMPLETED); + assert!( + end.says("planned-work rounds 1 and 2 made no progress"), + "{:?}", + end.words + ); + assert!(end.says("apps/web/src/blocks/card.tsx")); + assert!(end.says("apps/web/src/blocks/index.ts")); + assert!(gh.pr(21).draft, "the pull request stays a draft"); + assert!(proof::holds_unfinished(&gh.pr(21).body)); +} + +#[test] +fn a_round_whose_check_cannot_answer_claims_nothing_done() { + let mut gh = FakeGitHub::new(); + let mut end = Ending::default(); + let round = open_the_pull_request(&mut gh, &mut end).unwrap(); + let before = finish_planned::listed(&gh.pr(21).body); + assert_eq!( + finish_planned::next(&before, None, 0, &round), + Next::Again { stalled: 1 } + ); +} + +#[test] +fn the_pipeline_parks_the_round_and_the_resume_runs_it() { + let src = include_str!("../mod.rs"); + let rp = run_passes_src(); + assert!(rp.contains("let unfinished = proof::unfinished_section(&gaps);")); + assert!(rp.contains("finish_planned::first_round(&unfinished, chrono::Utc::now())")); + assert!(rp.contains("round::record(state, &msg.team_id, run_id, round).await;")); + // The multi-repository pipeline opens its drafts the same way. + let multi = fn_src(src, "\nasync fn run_repo_pipeline("); + assert!(multi.contains("let unfinished = proof::unfinished_section(&gaps);")); + // The resume runs a parked planned-work round, judges again, and stops + // with the status `finish_planned` gives (never a literal `completed` + // for stopped work). + let resume = include_str!("../resume.rs"); + let pending = fn_src(resume, "\nasync fn run_pending_round("); + assert!(pending.contains("after_planned_round(")); + let after = fn_src(resume, "\nasync fn after_planned_round("); + assert!(after.contains("recheck_planned_work(")); + assert!(after.contains("finish_planned::run_status(&next, files)")); + assert!(after.contains("Section::Unfinished")); + assert!(after.contains("mark_pr_ready(")); + let stop = &after[after.find("Next::Stop(reason) => {").unwrap()..]; + assert!(!stop.contains("\"completed\"")); +} diff --git a/services/worker/src/passes/incidents/mod.rs b/services/worker/src/passes/incidents/mod.rs new file mode 100644 index 000000000..c8ad44bdd --- /dev/null +++ b/services/worker/src/passes/incidents/mod.rs @@ -0,0 +1,26 @@ +//! The incident regression suite: every run failure that reached a person +//! is a case here, so it can never come back silently. +//! +//! Each case replays the failure as a scenario on one invented monorepo +//! (`fixture`), through the pipeline's own decision code, with fakes only at +//! the edges: GitHub, the model's replies, the sandbox's archive and log, +//! and DynamoDB records. Each asserts how the run ends (its status), what it +//! leaves (the pull request, the notes), and that the old failure message +//! never appears. Where a decision lives inside the pipeline itself, the +//! case also checks that the pipeline still calls it at that place. +//! +//! CI runs the suite as its own job (`cargo test -p worker incidents::`), +//! and `docs/incidents.md` lists each case with the guarantee it protects. +//! A fix for a new failure adds a case here and a line there. + +mod fixture; + +mod a_whole_branch; +mod b_open_pr_retry; +mod c_codegen_egress; +mod d_echoed_markers; +mod e_large_generated_output; +mod f_steps; +mod g_large_plan; +mod h_pr_updates; +mod i_finished_work_pr; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 5fbda1488..818ec7c4e 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -785,6 +785,7 @@ pub mod e2e_setup; pub mod email_events; pub mod feature; pub mod feedback; +mod finish_planned; pub mod fix_location; pub mod formatter; pub(crate) mod generators; @@ -792,6 +793,8 @@ pub mod github_history; pub mod health_check; pub mod hidden_suggest; mod implement; +#[cfg(test)] +mod incidents; pub mod infra_analyze; mod infra_repo; pub mod jira_comment; @@ -4849,7 +4852,7 @@ async fn run_passes( let kept = keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; close_memory(state, agent_memory.take()).await; - return Err(format!("{why} The work so far is kept on branch `{kept}`.").into()); + return Err(stopped_keeping(&why, &kept).into()); } } } @@ -5189,6 +5192,29 @@ async fn run_passes( ) .await; + // Planned work still not done is finished by CoderHelm, in rounds of its + // own on the pull request (`finish_planned`): the first is parked for + // the resume that follows. A parked security round goes first; the + // planned-work round starts after it. + let planned_round = if security_round.is_none() { + finish_planned::first_round(&unfinished, chrono::Utc::now()) + } else { + None + }; + if let Some(round) = &planned_round { + round::record(state, &msg.team_id, run_id, round).await; + add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "{} planned task(s) are still not done: CoderHelm keeps working them on the pull request in rounds of its own", + finish_planned::listed(&unfinished).len() + ), + ) + .await; + } + // The security fix there wasn't time for: a round of its own on the PR, // parked for the resume that follows (a fresh invocation, its own budget). if let Some(feedback) = &security_round { @@ -5294,8 +5320,13 @@ async fn run_passes( .send_message() .queue_url(&state.config.ci_fix_queue_url) .message_body(resume_body.to_string()) - // A parked security fix starts as soon as this invocation ends. - .delay_seconds(if security_round.is_some() { 5 } else { 120 }) + // A parked round (a security fix, planned work) starts as soon + // as this invocation ends. + .delay_seconds(if security_round.is_some() || planned_round.is_some() { + 5 + } else { + 120 + }) .send() .await; } @@ -5320,6 +5351,12 @@ async fn run_passes( Ok(()) } +/// The run's error when a gate stops it (a tooling failure, a value only a +/// person can set): the gate's own reason, and where the work is kept. +fn stopped_keeping(why: &str, kept: &str) -> String { + format!("{why} The work so far is kept on branch `{kept}`.") +} + /// Continue the run in a fresh step at `gate`, with the branch as it is: /// the checkpoint names the gate (and what the skipped stages carry), and a /// new message starts the next step. Only a run that can't continue (the @@ -5884,7 +5921,7 @@ async fn run_repo_pipeline( } Err(generators::GateStop::Blocked(why)) => { let kept = keep_wip_branch(github, repo_owner, repo_name, branch_name).await; - return Err(format!("{why} The work so far is kept on branch `{kept}`.").into()); + return Err(stopped_keeping(&why, &kept).into()); } Err(generators::GateStop::NeedsTime) => { // A multi-repo run has no fresh steps yet: say exactly that. @@ -10474,6 +10511,23 @@ async fn switch_run_repo( true } +/// The plan files cached for a run's ticket and repository (for a round on +/// its pull request, which judges the branch against the plan again). +pub(crate) async fn run_plan_files( + state: &WorkerState, + msg: &TicketMessage, +) -> Option { + let prefix = openspec_prefix( + &msg.team_id, + &msg.ticket_id, + &msg.repo_owner, + &msg.repo_name, + ); + load_cached_plan_files(state, &prefix) + .await + .filter(|p| !p.tasks.trim().is_empty()) +} + async fn load_cached_plan_files(state: &WorkerState, prefix: &str) -> Option { let mut files = std::collections::HashMap::new(); for name in &["proposal.md", "design.md", "tasks.md", "spec.md"] { diff --git a/services/worker/src/passes/proof.rs b/services/worker/src/passes/proof.rs index 8f5cec68f..7edf559fc 100644 --- a/services/worker/src/passes/proof.rs +++ b/services/worker/src/passes/proof.rs @@ -1246,7 +1246,8 @@ pub fn unfinished_section(findings: &[Finding]) -> String { } format!( "{UNFINISHED_START}\n## Not finished\nThis pull request stays a draft: the check before \ - it found planned work still not done after its fix round.\n{}\n{UNFINISHED_END}", + it found planned work still not done after its fix round. CoderHelm keeps working on \ + it here and marks the pull request ready when nothing is left.\n{}\n{UNFINISHED_END}", items.join("\n") ) } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 005abeab0..575fe398c 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3218,11 +3218,21 @@ async fn run_pending_round( let round = pending.resumed(chrono::Utc::now()); let kind = round.kind; let number = round.number; + let planned = (kind == run_round::Kind::PlannedWork).then(|| round.clone()); let end = if kind == run_round::Kind::Conflict { run_conflict_round(state, msg, &mut ctx, &pr, &round).await } else { run_fix_round(state, msg, &mut ctx, &pr, round, created_at, start).await? }; + // Planned work: the check judges the branch again and decides the next + // round, the ready pull request, or the stop (`finish_planned`). + if let Some(planned) = planned { + if end != RoundEnd::Parked { + after_planned_round(state, msg, &mut ctx, &pr, &planned, end, created_at, start) + .await?; + } + return Ok(()); + } match end { RoundEnd::Parked => {} RoundEnd::Incomplete => { @@ -3242,6 +3252,10 @@ async fn run_pending_round( RoundEnd::Done { files: 0 } => { if kind == run_round::Kind::SecurityFix { recheck_security(state, msg, &mut ctx, &pr).await; + // Planned work still listed starts its rounds now. + if start_planned_work(state, msg, &ctx, &pr, created_at, start).await? { + return Ok(()); + } } if kind == run_round::Kind::CiFix { super::record_ci_outcome( @@ -3278,6 +3292,9 @@ async fn run_pending_round( } if kind == run_round::Kind::SecurityFix { recheck_security(state, msg, &mut ctx, &pr).await; + if start_planned_work(state, msg, &ctx, &pr, created_at, start).await? { + return Ok(()); + } } save_checkpoint( state, @@ -3460,6 +3477,270 @@ async fn run_conflict_round( /// request, and its Open items say what it found. Fixed, the items go and /// the pull request may be marked ready; still failing, or a check that /// didn't run, the items stay (with what it found now) and it stays a draft. +/// Starts the planned-work rounds when the pull request still lists planned +/// work not done (after a parked security round): the first round is parked +/// for a fresh invocation. False when nothing is listed. +async fn start_planned_work( + state: &WorkerState, + msg: &ResumeMessage, + ctx: &FixContext, + pr: &PrRef<'_>, + created_at: Option>, + start: &std::time::Instant, +) -> Result> { + let body = match ctx + .github + .get_pull_request(pr.owner, pr.repo, pr.number) + .await + { + Ok(p) => p["body"].as_str().unwrap_or("").to_string(), + Err(e) => { + warn!(run_id = msg.run_id, error = %e, "Could not read the PR for planned work not done"); + return Ok(false); + } + }; + let Some(round) = super::finish_planned::first_round(&body, chrono::Utc::now()) else { + return Ok(false); + }; + super::round::record(state, &msg.team_id, &msg.run_id, &round).await; + super::add_progress_note( + state, + &msg.team_id, + &msg.run_id, + &format!( + "{} planned task(s) are still not done: CoderHelm keeps working them on the pull request in rounds of its own", + super::finish_planned::listed(&body).len() + ), + ) + .await; + if set_run_awaiting_ci( + state, + &ctx.ticket_msg, + &msg.run_id, + pr.url, + pr.number, + pr.branch, + &ctx.usage, + wall_clock_secs(created_at, start), + ) + .await? + { + send_delayed_resume(state, msg, 5).await; + } + Ok(true) +} + +/// The check before the pull request, run again on the branch for a +/// planned-work round: the planned work it still finds not done. `None` +/// when it couldn't answer (no plan, no diff, no reply). +async fn recheck_planned_work( + state: &WorkerState, + msg: &ResumeMessage, + ctx: &mut FixContext, + pr: &PrRef<'_>, +) -> Option> { + let plan = super::run_plan_files(state, &ctx.ticket_msg).await?; + // Generated outputs their generator settled are never planned work left. + let settled = super::steps::load(state, &msg.team_id, &msg.run_id) + .await + .carry + .map(|c| c.generated) + .unwrap_or_default(); + let mut evidence = super::proof::RunEvidence::default(); + super::proof::judge( + state, + &ctx.ticket_msg, + &ctx.github, + pr.branch, + &plan, + &settled, + &mut evidence, + &ctx.provider, + &mut ctx.usage, + ) + .await + .map(|f| super::proof::drop_settled_generated(f, &settled)) +} + +/// After a planned-work round: judge the branch again, rewrite the "Not +/// finished" section to what is left, and go on (another round), finish +/// (ready) or stop (two rounds without progress) as `finish_planned` says. +#[allow(clippy::too_many_arguments)] +async fn after_planned_round( + state: &WorkerState, + msg: &ResumeMessage, + ctx: &mut FixContext, + pr: &PrRef<'_>, + round: &run_round::Round, + end: RoundEnd, + created_at: Option>, + start: &std::time::Instant, +) -> Result<(), Box> { + use super::finish_planned::{self, Next}; + let files = match end { + RoundEnd::Done { files } => files, + RoundEnd::Parked | RoundEnd::Incomplete => 0, + }; + let body = match ctx + .github + .get_pull_request(pr.owner, pr.repo, pr.number) + .await + { + Ok(p) => p["body"].as_str().unwrap_or("").to_string(), + Err(e) => { + warn!(run_id = msg.run_id, error = %e, "Could not read the PR after a planned-work round"); + String::new() + } + }; + let before = finish_planned::listed(&body); + let _ = super::update_pass(state, &msg.team_id, &msg.run_id, "review").await; + let section = recheck_planned_work(state, msg, ctx, pr) + .await + .map(|f| super::proof::unfinished_section(&f)); + let after = section.as_deref().map(finish_planned::listed); + // The description says what is still not done, never the earlier list. + if let Some(section) = §ion { + if !body.is_empty() { + let updated = super::completeness::with_section( + &body, + super::completeness::Section::Unfinished, + section.clone(), + ); + if updated != body { + if let Err(e) = ctx + .github + .update_pr_body(pr.owner, pr.repo, pr.number, &updated) + .await + { + warn!(run_id = msg.run_id, error = %e, "Could not update the PR's Not finished section"); + } + } + } + } + let duration = wall_clock_secs(created_at, start); + let next = finish_planned::next(&before, after.as_deref(), files, round); + let status = finish_planned::run_status(&next, files); + match next { + Next::Ready => { + super::add_progress_note( + state, + &msg.team_id, + &msg.run_id, + &format!( + "Planned-work round {}: the check finds no planned work left; the pull request is ready once its checks pass", + round.number + ), + ) + .await; + if files > 0 { + // New commits: CI runs on them, then the usual resume marks + // the pull request ready. + save_checkpoint( + state, + &msg.team_id, + &msg.run_id, + "pr", + pr.branch, + 0, + &ctx.usage, + ) + .await; + if set_run_awaiting_ci( + state, + &ctx.ticket_msg, + &msg.run_id, + pr.url, + pr.number, + pr.branch, + &ctx.usage, + duration, + ) + .await? + { + send_delayed_resume(state, msg, 120).await; + } + } else { + mark_pr_ready( + state, + &msg.team_id, + &ctx.github, + pr.owner, + pr.repo, + pr.number, + ) + .await; + complete_run_with_status( + state, + &ctx.ticket_msg, + &msg.run_id, + status, + pr.url, + pr.number, + pr.branch, + &ctx.usage, + duration, + ) + .await?; + } + } + Next::Again { stalled } => { + let items = after.unwrap_or(before); + let next = finish_planned::next_round(round, &items, stalled, chrono::Utc::now()); + super::round::record(state, &msg.team_id, &msg.run_id, &next).await; + super::add_progress_note( + state, + &msg.team_id, + &msg.run_id, + &format!( + "Planned-work round {} {}: {} task(s) still not done; round {} continues in a fresh step", + round.number, + if stalled == 0 { + "made progress" + } else { + "made no progress" + }, + items.len(), + next.number + ), + ) + .await; + if set_run_awaiting_ci( + state, + &ctx.ticket_msg, + &msg.run_id, + pr.url, + pr.number, + pr.branch, + &ctx.usage, + duration, + ) + .await? + { + send_delayed_resume(state, msg, 5).await; + } + } + Next::Stop(reason) => { + super::add_progress_note(state, &msg.team_id, &msg.run_id, &reason).await; + // Not completed: the run waits on a person, says which tasks and + // why, and the pull request stays a draft. + complete_run_with_status( + state, + &ctx.ticket_msg, + &msg.run_id, + status, + pr.url, + pr.number, + pr.branch, + &ctx.usage, + duration, + ) + .await?; + super::round::stopped(state, &msg.team_id, &msg.run_id, round, &reason).await; + } + } + Ok(()) +} + async fn recheck_security( state: &WorkerState, msg: &ResumeMessage, @@ -4127,6 +4408,23 @@ fn first_own_commit_message(commits: &[serde_json::Value]) -> Option { }) } +/// Why an open pull request stays a draft, read from its description and +/// title; `None` when nothing holds it. Security items still open, planned +/// work not done ("Not finished"), and an end-to-end fix or generated test +/// whose repeat runs haven't proved it (`proven`) each hold it. +pub(crate) fn draft_hold(body: &str, title: &str, proven: bool) -> Option<&'static str> { + if super::proof::holds_security_items(body) { + return Some("security items are open in the description"); + } + if super::proof::holds_unfinished(body) { + return Some("planned work not done is listed in the description"); + } + if !proven && is_e2e_proof_pr(title) { + return Some("an end-to-end proof PR waits for its repeat runs"); + } + None +} + async fn mark_ready( github: &GitHubClient, repo_owner: &str, @@ -4153,40 +4451,12 @@ async fn mark_ready( info!(pr_number, "PR is closed — not marking ready"); return; } - // Security issues not fixed yet (or a security check that - // didn't run) are listed under Open items: the PR stays a - // draft until they're gone. - if super::proof::holds_security_items( + if let Some(why) = draft_hold( pr.get("body").and_then(|v| v.as_str()).unwrap_or(""), + pr.get("title").and_then(|v| v.as_str()).unwrap_or(""), + proven, ) { - info!( - pr_number, - "Security items open in the description — the PR stays a draft" - ); - return; - } - // Planned work not done is listed at the top: the PR stays - // a draft until a person (or a later round) settles it. - if super::proof::holds_unfinished( - pr.get("body").and_then(|v| v.as_str()).unwrap_or(""), - ) { - info!( - pr_number, - "Planned work not done is listed in the description; the PR stays a draft" - ); - return; - } - // E2E fix and generated-test PRs wait for their repeat runs. - if !proven - && pr - .get("title") - .and_then(|v| v.as_str()) - .is_some_and(is_e2e_proof_pr) - { - info!( - pr_number, - "E2E proof PR — stays a draft until its repeat runs pass" - ); + info!(pr_number, why, "The PR stays a draft"); return; } // A person put this PR back into draft: that is their call, and diff --git a/services/worker/src/passes/round.rs b/services/worker/src/passes/round.rs index 87fc2c240..39f3c22e7 100644 --- a/services/worker/src/passes/round.rs +++ b/services/worker/src/passes/round.rs @@ -209,6 +209,41 @@ async fn write_incomplete( } } +/// Planned-work rounds stopped without progress: the run keeps its status +/// (`needs_input`, set by the caller) and says which round stopped and why; +/// the round leaves the record. +pub(crate) async fn stopped( + state: &WorkerState, + team_id: &str, + run_id: &str, + round: &Round, + reason: &str, +) { + let now = chrono::Utc::now().to_rfc3339(); + let inc = Incomplete::of(round, reason, &now); + 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 #inc = :inc, updated_at = :t REMOVE #round") + .condition_expression(common::run_status::not_ended("#s")) + .expression_attribute_names("#s", "status") + .expression_attribute_names("#inc", run_round::INCOMPLETE_FIELD) + .expression_attribute_names("#round", run_round::FIELD) + .expression_attribute_values(":inc", inc.to_attr()) + .expression_attribute_values(":t", attr_s(&now)) + .ended_values() + .send() + .await; + if let Err(e) = res { + if !common::run_fail::is_condition_failed(&e) { + warn!(run_id, error = %e, "Could not record why the planned work stopped"); + } + } +} + /// After a round's worker failed outright (an error the pass returned): /// when the run has an open pull request, it is left completed with the /// round named as not finished instead of failed. Returns false when the @@ -429,6 +464,7 @@ pub(crate) async fn round_message( Kind::Feedback => "Address the review comments", Kind::SecurityFix => "Fix the security issues the check found", Kind::Conflict => "Merge the base branch and resolve the conflicts", + Kind::PlannedWork => "Finish the planned work still not done", }; let conventions = super::load_git_conventions(state, team_id, &ticket.ticket_id).await; conventions.commit_message(&super::ticket_tokens(ticket), summary)