diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 0dc8bf939..36ddd16c7 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -76,6 +76,90 @@ fn status_error_message(status: reqwest::StatusCode, url: &str, body: &str) -> S } } +/// Did this request fail because the thing does not exist? Matches the +/// status line `status_error_message` writes. +pub fn is_not_found(e: &(dyn std::error::Error + Send + Sync)) -> bool { + e.to_string().contains("(404 Not Found)") +} + +/// What a contents-API response says about a file's body. +#[derive(Debug, PartialEq)] +enum ContentsBody { + /// The body, decoded. + Text(String), + /// Too large for the contents API (over 1 MB it sends `encoding: none` + /// and no content): read the git blob with this sha instead. + Blob(String), +} + +/// Decode a contents-API response for `path`. A file whose `size` says it +/// has bytes never decodes to an empty string: it is either sent to the blob +/// API or reported as an error. +fn contents_body(path: &str, data: &serde_json::Value) -> Result { + if data.is_array() { + return Err(format!("'{path}' is a directory, not a file")); + } + let size = data.get("size").and_then(|s| s.as_u64()).unwrap_or(0); + let encoding = data.get("encoding").and_then(|e| e.as_str()).unwrap_or(""); + let content = data.get("content").and_then(|c| c.as_str()).unwrap_or(""); + let clean = content.replace(['\n', '\r'], ""); + if size > 0 && (clean.is_empty() || encoding == "none") { + let sha = data + .get("sha") + .and_then(|s| s.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| { + format!( + "'{path}' is {size} bytes but GitHub sent neither its content nor a blob sha" + ) + })?; + return Ok(ContentsBody::Blob(sha.to_string())); + } + Ok(ContentsBody::Text(decode_base64_text(path, &clean)?)) +} + +/// Decode a git-blob response for `path`. Errors rather than returning an +/// empty string for a blob that has bytes. +fn blob_text(path: &str, data: &serde_json::Value) -> Result { + let size = data.get("size").and_then(|s| s.as_u64()).unwrap_or(0); + let content = data.get("content").and_then(|c| c.as_str()).unwrap_or(""); + let text = match data.get("encoding").and_then(|e| e.as_str()) { + Some("utf-8") => content.to_string(), + _ => decode_base64_text(path, &content.replace(['\n', '\r'], ""))?, + }; + if text.is_empty() && size > 0 { + return Err(format!( + "'{path}' is {size} bytes but GitHub returned no content for it, even from the blob API" + )); + } + Ok(text) +} + +fn decode_base64_text(path: &str, clean: &str) -> Result { + let bytes = B64 + .decode(clean) + .map_err(|e| format!("'{path}': content is not valid base64 ({e})"))?; + String::from_utf8(bytes).map_err(|_| format!("'{path}' is not UTF-8 text")) +} + +/// The refusal for writing `content` over a file of `existing_size` bytes +/// (None = the file does not exist), or None when the write is allowed. +/// Blank content over a file with bytes is refused: removal must be explicit. +fn empty_overwrite_refusal( + path: &str, + content: &str, + existing_size: Option, +) -> Option { + let existing = existing_size.unwrap_or(0); + (content.trim().is_empty() && existing > 0).then(|| { + format!( + "refused: this write would replace '{path}' ({existing} bytes) with empty content. \ + That usually means the source read came back empty, not that the file should be emptied. \ + Re-read the file; if it really should go, delete it explicitly instead of writing nothing." + ) + }) +} + /// GitHub REST API client using installation token auth. pub struct GitHubClient { app_id: String, @@ -568,17 +652,34 @@ impl GitHubClient { return Ok(content); } } - let url = format!("{API_BASE}/repos/{owner}/{repo}/contents/{path}?ref={git_ref}"); - let data = self.get(&url).await?; - let content = data.get("content").and_then(|c| c.as_str()).unwrap_or(""); - let clean = content.replace('\n', ""); - let bytes = B64.decode(&clean)?; - Ok(String::from_utf8(bytes)?) + self.read_file_live(owner, repo, path, git_ref).await + } + + /// Like `read_file`, but a file that does not exist at `git_ref` is + /// `Ok(None)`. Every other failure stays an error, so a caller deciding + /// "deleted vs. present" never reads a failed fetch as a deletion. + pub async fn read_file_if_exists( + &self, + owner: &str, + repo: &str, + path: &str, + git_ref: &str, + ) -> Result, Box> { + match self.read_file(owner, repo, path, git_ref).await { + Ok(content) => Ok(Some(content)), + Err(e) if is_not_found(&*e) => Ok(None), + Err(e) => Err(e), + } } /// Read a file straight from the LIVE API, bypassing the snapshot cache. /// Used where staleness is dangerous — the 409 reconcile must compare /// against what is ACTUALLY on the branch, not our (possibly stale) mirror. + /// + /// The contents API carries no body for files over 1 MB (`encoding: + /// none`); those are read from their git blob. A file with bytes is never + /// returned as an empty string: callers write what they read back to the + /// branch, and an empty read once replaced a 28,915-line lockfile. async fn read_file_live( &self, owner: &str, @@ -588,10 +689,77 @@ impl GitHubClient { ) -> Result> { let url = format!("{API_BASE}/repos/{owner}/{repo}/contents/{path}?ref={git_ref}"); let data = self.get(&url).await?; - let content = data.get("content").and_then(|c| c.as_str()).unwrap_or(""); - let clean = content.replace('\n', ""); - let bytes = B64.decode(&clean)?; - Ok(String::from_utf8(bytes)?) + match contents_body(path, &data)? { + ContentsBody::Text(text) => Ok(text), + ContentsBody::Blob(sha) => { + let url = format!("{API_BASE}/repos/{owner}/{repo}/git/blobs/{sha}"); + let blob = self.get(&url).await?; + Ok(blob_text(path, &blob)?) + } + } + } + + /// Size in bytes of `path` at `git_ref`, or None when it does not exist. + /// Metadata only: the contents API reports `size` even for files too + /// large to carry a body. + async fn existing_file_size( + &self, + owner: &str, + repo: &str, + path: &str, + git_ref: &str, + ) -> Result, Box> { + let url = format!("{API_BASE}/repos/{owner}/{repo}/contents/{path}?ref={git_ref}"); + match self.get(&url).await { + Ok(data) => Ok(Some(data.get("size").and_then(|s| s.as_u64()).unwrap_or(0))), + Err(e) if is_not_found(&*e) => Ok(None), + Err(e) => Err(e), + } + } + + /// Does `path` exist at `git_ref`? Metadata only, so a presence check on + /// a large lockfile does not download it. + pub async fn file_exists(&self, owner: &str, repo: &str, path: &str, git_ref: &str) -> bool { + if let Some(snap) = self.existing_snapshot(owner, repo, git_ref).await { + if snap.read_file(path).await.is_some() { + return true; + } + } + matches!( + self.existing_file_size(owner, repo, path, git_ref).await, + Ok(Some(_)) + ) + } + + /// Refuse to write empty content over a file that has bytes. Emptying a + /// file is never what a write means here; it is what an empty or failed + /// read looks like by the time it reaches a write (8 fix cycles once kept + /// "restoring" a lockfile to nothing). Removing a file must be an explicit + /// delete. Only empty writes cost the extra lookup. + async fn guard_empty_overwrite( + &self, + owner: &str, + repo: &str, + path: &str, + git_ref: &str, + content: &str, + ) -> Result<(), Box> { + if !content.trim().is_empty() { + return Ok(()); + } + let existing = self + .existing_file_size(owner, repo, path, git_ref) + .await + .map_err(|e| { + format!( + "refusing to write empty content to '{path}': could not confirm the file is \ + empty or absent on '{git_ref}' ({e}). Delete the file explicitly if that is the intent." + ) + })?; + match empty_overwrite_refusal(path, content, existing) { + Some(msg) => Err(msg.into()), + None => Ok(()), + } } /// Get the SHA of a file at a given ref (for update operations). @@ -807,6 +975,23 @@ impl GitHubClient { Ok(sha.to_string()) } + /// The tree SHA at `branch`'s tip. Trees are content-addressed: two equal + /// tree SHAs mean byte-identical file sets, whatever commits lie between. + pub async fn get_tree_sha( + &self, + owner: &str, + repo: &str, + branch: &str, + ) -> Result> { + let sha = self.get_ref(owner, repo, branch).await?; + let url = format!("{API_BASE}/repos/{owner}/{repo}/git/commits/{sha}"); + let data = self.get(&url).await?; + data.pointer("/tree/sha") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()) + .ok_or_else(|| "Missing tree sha in commit".into()) + } + /// Fast-forward-only ref update (compare-and-swap): points `branch` at /// `sha` with `force:false`, so GitHub REJECTS a non-fast-forward move /// (another writer raced us). Returns Ok(false) on that conflict so the @@ -1086,6 +1271,8 @@ impl GitHubClient { message: &str, sha: Option<&str>, ) -> Result> { + self.guard_empty_overwrite(owner, repo, path, branch, content) + .await?; let url = format!("{API_BASE}/repos/{owner}/{repo}/contents/{path}"); let encoded = B64.encode(content.as_bytes()); // FRESHNESS CONTRACT (same as batch_write): if the branch tip moved @@ -1194,6 +1381,14 @@ impl GitHubClient { message: &str, files: &[FileOp], ) -> Result> { + // An empty Write over a file with bytes is refused before anything is + // created; a removal must come as FileOp::Delete. + for f in files { + if let FileOp::Write { path, content } = f { + self.guard_empty_overwrite(owner, repo, path, branch, content) + .await?; + } + } // Blobs are content-addressed and immutable — create them once, reuse // across retries. let mut blob_entries = Vec::new(); @@ -1377,6 +1572,16 @@ impl GitHubClient { .and_then(|v| v.as_str()) .ok_or("Missing tree sha in branch commit")?; + // The merge tree overlays these files on the branch's tree, so an + // empty resolution would empty the branch's copy. Same rule as + // batch_write: removal must be an explicit FileOp::Delete. + for f in resolved_files { + if let FileOp::Write { path, content } = f { + self.guard_empty_overwrite(owner, repo, path, branch_sha, content) + .await?; + } + } + let mut tree_entries = Vec::new(); for f in resolved_files { match f { @@ -2963,6 +3168,109 @@ mod status_error_tests { let m = status_error_message(reqwest::StatusCode::BAD_GATEWAY, "u", " "); assert_eq!(m, "HTTP status server error (502 Bad Gateway) for url (u)"); } + + #[test] + fn only_a_404_reads_as_not_found() { + let missing: Box = + status_error_message(reqwest::StatusCode::NOT_FOUND, "u", "").into(); + assert!(is_not_found(&*missing)); + // A 403 (rate limit, file too large) is a failed read, never "deleted". + let forbidden: Box = + status_error_message(reqwest::StatusCode::FORBIDDEN, "u", "too_large").into(); + assert!(!is_not_found(&*forbidden)); + } +} + +#[cfg(test)] +mod file_body_tests { + use super::*; + use serde_json::json; + + #[test] + fn small_file_decodes_from_the_contents_api() { + // GitHub wraps base64 at 60 columns. + let data = json!({"size": 11, "encoding": "base64", "sha": "abc", + "content": "aGVsbG8g\nd29ybGQ=\n"}); + assert_eq!( + contents_body("a.txt", &data), + Ok(ContentsBody::Text("hello world".into())) + ); + } + + #[test] + fn large_file_goes_to_the_blob_api_not_an_empty_string() { + // The prod shape: a 1.2 MB pnpm-lock.yaml comes back with + // `encoding: none` and an empty body. + let data = json!({"size": 1_200_000, "encoding": "none", "sha": "b10b", "content": ""}); + assert_eq!( + contents_body("pnpm-lock.yaml", &data), + Ok(ContentsBody::Blob("b10b".into())) + ); + // Same when the content key is missing outright. + let data = json!({"size": 5, "sha": "b10b"}); + assert_eq!( + contents_body("x", &data), + Ok(ContentsBody::Blob("b10b".into())) + ); + // No sha to fall back to: an error, never "". + let data = json!({"size": 5, "encoding": "none"}); + assert!(contents_body("x", &data).is_err()); + } + + #[test] + fn a_genuinely_empty_file_reads_as_empty() { + let data = json!({"size": 0, "encoding": "base64", "sha": "e69d", "content": ""}); + assert_eq!( + contents_body("x", &data), + Ok(ContentsBody::Text(String::new())) + ); + } + + #[test] + fn a_directory_is_an_error_not_an_empty_file() { + assert!(contents_body("src", &json!([{"name": "a.rs"}])).is_err()); + } + + #[test] + fn blob_decodes_and_refuses_to_come_back_empty() { + let data = json!({"size": 11, "encoding": "base64", "content": "aGVsbG8g\nd29ybGQ="}); + assert_eq!(blob_text("x", &data).unwrap(), "hello world"); + let data = json!({"size": 3, "encoding": "utf-8", "content": "abc"}); + assert_eq!(blob_text("x", &data).unwrap(), "abc"); + let data = json!({"size": 1_200_000, "encoding": "base64", "content": ""}); + assert!(blob_text("pnpm-lock.yaml", &data).is_err()); + let data = json!({"size": 0, "encoding": "base64", "content": ""}); + assert_eq!(blob_text("x", &data).unwrap(), ""); + } + + #[test] + fn empty_content_never_replaces_a_file_with_bytes() { + let refusal = empty_overwrite_refusal("pnpm-lock.yaml", "", Some(1_200_000)); + assert!(refusal + .as_deref() + .is_some_and(|m| m.contains("pnpm-lock.yaml") && m.contains("delete it explicitly"))); + // Whitespace is as empty as nothing. + assert!(empty_overwrite_refusal("a", " \n", Some(10)).is_some()); + // Allowed: real content, a new file, or an already-empty file. + assert!(empty_overwrite_refusal("a", "x", Some(10)).is_none()); + assert!(empty_overwrite_refusal("a", "", None).is_none()); + assert!(empty_overwrite_refusal("a", "", Some(0)).is_none()); + } + + #[tokio::test] + async fn non_empty_writes_skip_the_lookup() { + // No network and no credentials: a lookup here would error. + let client = GitHubClient::new("1", "", 0, &reqwest::Client::new()).unwrap(); + assert!(client + .guard_empty_overwrite("o", "r", "a", "main", "content") + .await + .is_ok()); + // An empty write that cannot verify the target is refused, not let through. + assert!(client + .guard_empty_overwrite("o", "r", "a", "main", "") + .await + .is_err()); + } } #[cfg(test)] diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 9e5f4b591..203ed600c 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -5733,19 +5733,14 @@ pub(crate) async fn detect_check_commands( // Package manager from whichever lockfile the repo commits. let (install, run) = if github - .read_file(owner, repo, "pnpm-lock.yaml", git_ref) + .file_exists(owner, repo, "pnpm-lock.yaml", git_ref) .await - .is_ok() { ( "corepack enable && pnpm install --frozen-lockfile", "pnpm run", ) - } else if github - .read_file(owner, repo, "yarn.lock", git_ref) - .await - .is_ok() - { + } else if github.file_exists(owner, repo, "yarn.lock", git_ref).await { ("corepack enable && yarn install --frozen-lockfile", "yarn") } else { ("npm ci --no-audit --no-fund", "npm run") @@ -6176,19 +6171,14 @@ pub(crate) async fn detect_codegen_command( let has = |name: &str| scripts.map(|s| s.contains_key(name)).unwrap_or(false); let (install, run) = if github - .read_file(owner, repo, "pnpm-lock.yaml", git_ref) + .file_exists(owner, repo, "pnpm-lock.yaml", git_ref) .await - .is_ok() { ( "corepack enable && pnpm install --frozen-lockfile", "pnpm run", ) - } else if github - .read_file(owner, repo, "yarn.lock", git_ref) - .await - .is_ok() - { + } else if github.file_exists(owner, repo, "yarn.lock", git_ref).await { ("corepack enable && yarn install --frozen-lockfile", "yarn") } else { ("npm ci --no-audit --no-fund", "npm run") diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 84d6ccc58..4e3e7ee3d 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -560,18 +560,20 @@ pub async fn resolve_conflicts( .iter() .any(|f| f.get("filename").and_then(|v| v.as_str()) == Some(base_file)); if !touched_by_branch { + // Only a 404 means base deleted the file. Any other failed read + // aborts the resolution: reading it as a deletion (or as empty + // content) would commit that loss into the branch. match github - .read_file(&msg.repo_owner, &msg.repo_name, base_file, &msg.base_branch) - .await + .read_file_if_exists(&msg.repo_owner, &msg.repo_name, base_file, &msg.base_branch) + .await? { - Ok(content) => { + Some(content) => { resolved_files.push(FileOp::Write { path: base_file.clone(), content, }); } - Err(_) => { - // File was deleted on base + None => { resolved_files.push(FileOp::Delete { path: base_file.clone(), }); @@ -587,19 +589,18 @@ pub async fn resolve_conflicts( None => continue, }; - // Read all three versions: merge base, base branch (main), feature branch + // Read all three versions: merge base, base branch (main), feature + // branch. None means the file is absent on that side; a failed read + // aborts instead of passing for a deletion. let ancestor = github - .read_file(&msg.repo_owner, &msg.repo_name, path, merge_base_sha) - .await - .ok(); + .read_file_if_exists(&msg.repo_owner, &msg.repo_name, path, merge_base_sha) + .await?; let main_content = github - .read_file(&msg.repo_owner, &msg.repo_name, path, &msg.base_branch) - .await - .ok(); + .read_file_if_exists(&msg.repo_owner, &msg.repo_name, path, &msg.base_branch) + .await?; let branch_content = github - .read_file(&msg.repo_owner, &msg.repo_name, path, branch) - .await - .ok(); + .read_file_if_exists(&msg.repo_owner, &msg.repo_name, path, branch) + .await?; // If either side deleted the file, prefer branch's decision let (main_content, branch_content) = match (main_content, branch_content) { diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 94fd9b53e..b9f96dbe0 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -85,8 +85,21 @@ fn ci_failure_signature(logs: &str) -> String { /// current signature, return the new count and whether to HALT. Halts when the /// exact same failure set has recurred MAX_STALL_CYCLES times — i.e. the fixes /// are making no progress. -fn stall_decision(prev_sig: &str, prev_stall: u32, current_sig: &str) -> (u32, bool) { - if !prev_sig.is_empty() && prev_sig == current_sig { +/// +/// `last_fix_noop`: the previous fix commit changed nothing (see +/// `fix_made_no_progress`). That cycle was already counted when the fix +/// landed, so a changed signature must not reset the count — the set of +/// failing workflows can shift between cycles while the tree stands still +/// (8 cycles once "restored" a lockfile to the same empty bytes this way). +fn stall_decision( + prev_sig: &str, + prev_stall: u32, + current_sig: &str, + last_fix_noop: bool, +) -> (u32, bool) { + if last_fix_noop { + (prev_stall, prev_stall >= MAX_STALL_CYCLES) + } else if !prev_sig.is_empty() && prev_sig == current_sig { let n = prev_stall + 1; (n, n >= MAX_STALL_CYCLES) } else { @@ -94,6 +107,30 @@ fn stall_decision(prev_sig: &str, prev_stall: u32, current_sig: &str) -> (u32, b } } +/// Did a fix cycle leave the code where it was? True when the tree after the +/// fix equals the tree before it (no commit, or files rewritten with +/// identical bytes) or equals a tree an earlier cycle already produced (a +/// change undone, back where CI already failed). Trees are content-addressed, +/// so this is exact. Unknown trees (a lookup failed) never count. +fn fix_made_no_progress(before: Option<&str>, after: Option<&str>, seen: &[String]) -> bool { + let Some(after) = after.filter(|s| !s.is_empty()) else { + return false; + }; + before == Some(after) || seen.iter().any(|t| t == after) +} + +/// Pure decision for a fix that just landed: a no-progress fix counts as a +/// stall cycle on its own, whatever CI says next. Returns the new count and +/// whether to HALT now. +fn noop_fix_decision(prev_stall: u32, noop: bool) -> (u32, bool) { + if noop { + let n = prev_stall + 1; + (n, n >= MAX_STALL_CYCLES) + } else { + (prev_stall, false) + } +} + #[cfg(test)] mod final_squash_tests { use super::first_own_commit_message; @@ -119,7 +156,10 @@ mod final_squash_tests { #[cfg(test)] mod stall_tests { - use super::{ci_failure_signature, stall_decision, MAX_STALL_CYCLES}; + use super::{ + ci_failure_signature, fix_made_no_progress, noop_fix_decision, stall_decision, + MAX_STALL_CYCLES, + }; #[test] fn signature_is_order_and_noise_independent() { @@ -137,11 +177,11 @@ mod stall_tests { #[test] fn halts_after_the_same_failure_repeats() { - let (s1, h1) = stall_decision("", 0, "SIG"); // first sight + let (s1, h1) = stall_decision("", 0, "SIG", false); // first sight assert_eq!((s1, h1), (0, false)); - let (s2, _) = stall_decision("SIG", 0, "SIG"); // 1st repeat + let (s2, _) = stall_decision("SIG", 0, "SIG", false); // 1st repeat assert_eq!(s2, 1); - let (s3, h3) = stall_decision("SIG", 1, "SIG"); // 2nd repeat → cap + let (s3, h3) = stall_decision("SIG", 1, "SIG", false); // 2nd repeat → cap assert_eq!(s3, MAX_STALL_CYCLES); assert!(h3); } @@ -149,7 +189,44 @@ mod stall_tests { #[test] fn progress_resets_the_counter() { // errors changed → not stalled, count resets even if it was high. - assert_eq!(stall_decision("SIG_A", 5, "SIG_B"), (0, false)); + assert_eq!(stall_decision("SIG_A", 5, "SIG_B", false), (0, false)); + } + + #[test] + fn a_noop_fix_is_not_reset_by_a_shifting_signature() { + // The prod loop: each cycle's failing workflow set differed, so the + // signature never repeated, while the fix rewrote the same bytes. + assert_eq!(stall_decision("SIG_A", 1, "SIG_B", true), (1, false)); + assert_eq!( + stall_decision("SIG_A", MAX_STALL_CYCLES, "SIG_B", true), + (MAX_STALL_CYCLES, true) + ); + // Counted once at the fix; the same signature after it adds nothing. + assert_eq!(stall_decision("SIG", 1, "SIG", true), (1, false)); + } + + #[test] + fn an_unchanged_or_revisited_tree_is_no_progress() { + let seen = vec!["t1".to_string(), "t2".to_string()]; + // Identical bytes rewritten (or nothing committed): same tree. + assert!(fix_made_no_progress(Some("t3"), Some("t3"), &[])); + // Back to a tree an earlier cycle already had. + assert!(fix_made_no_progress(Some("t3"), Some("t1"), &seen)); + // A new tree is progress. + assert!(!fix_made_no_progress(Some("t3"), Some("t4"), &seen)); + // A failed lookup proves nothing. + assert!(!fix_made_no_progress(Some("t3"), None, &seen)); + assert!(!fix_made_no_progress(None, Some(""), &[String::new()])); + } + + #[test] + fn noop_fixes_halt_on_their_own() { + let (s1, h1) = noop_fix_decision(0, true); + assert_eq!((s1, h1), (1, false)); + let (s2, h2) = noop_fix_decision(s1, true); + assert_eq!((s2, h2), (MAX_STALL_CYCLES, true)); + // A fix that changed the tree leaves the count to the signature check. + assert_eq!(noop_fix_decision(1, false), (1, false)); } #[test] @@ -1411,6 +1488,13 @@ pub async fn run( Full logs:\n{logs}{review_context}" ); + // The tree before the fix: compared with the tree after it to tell a + // fix that changed code from one that only rewrote the same bytes. + let tree_before = github + .get_tree_sha(&repo_owner, &repo_name, &branch) + .await + .ok(); + match implement::run( state, &ticket_msg, @@ -1512,6 +1596,58 @@ pub async fn run( } } + // A fix that left the tree unchanged (or returned it to an earlier + // cycle's state) is a stall cycle in its own right; enough of them + // hand the PR to a human now rather than after the next CI run. + let tree_after = github + .get_tree_sha(&repo_owner, &repo_name, &branch) + .await + .ok(); + if record_fix_progress( + state, + &msg.team_id, + &msg.run_id, + tree_before.as_deref(), + tree_after.as_deref(), + ) + .await + { + warn!( + run_id = msg.run_id, + "CI fixes are not changing the code — handing PR to human review" + ); + super::add_progress_note( + state, + &msg.team_id, + &msg.run_id, + "Automated fixes stopped changing the code (same files, same bytes) — handed off for human review.", + ) + .await; + mark_events_processed(state, &msg.run_id, &events).await; + mark_pr_ready( + state, + &msg.team_id, + &github, + &repo_owner, + &repo_name, + pr_number, + ) + .await; + complete_run_with_status( + state, + &ticket_msg, + &msg.run_id, + "completed", + &pr_url, + pr_number, + &branch, + &usage, + wall_clock_secs(created_at, &start), + ) + .await?; + return Ok(()); + } + // The fix changed code: count it before going back to wait for CI. super::record_ci_outcome( state, @@ -2179,7 +2315,7 @@ async fn check_and_record_stall( .table_name(&state.config.runs_table_name) .key("team_id", attr_s(team_id)) .key("run_id", attr_s(run_id)) - .projection_expression("last_error_sig, stall_count") + .projection_expression("last_error_sig, stall_count, last_fix_noop") .send() .await .ok() @@ -2196,7 +2332,13 @@ async fn check_and_record_stall( .and_then(|v| v.as_n().ok()) .and_then(|n| n.parse().ok()) .unwrap_or(0u32); - let (new_stall, halt) = stall_decision(&prev_sig, prev_stall, ¤t_sig); + let last_fix_noop = item + .as_ref() + .and_then(|i| i.get("last_fix_noop")) + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false); + let (new_stall, halt) = stall_decision(&prev_sig, prev_stall, ¤t_sig, last_fix_noop); let _ = state .dynamo .update_item() @@ -2211,6 +2353,76 @@ async fn check_and_record_stall( halt } +/// After a fix lands: decide whether it moved the code at all (tree before +/// vs. after, and every tree earlier cycles produced), persist that, and +/// return true if the run has STALLED. Signature checks alone miss a fix +/// that rewrites the same bytes while the failing workflows shift. The pure +/// decisions (`fix_made_no_progress` / `noop_fix_decision`) are unit-tested. +async fn record_fix_progress( + state: &WorkerState, + team_id: &str, + run_id: &str, + tree_before: Option<&str>, + tree_after: Option<&str>, +) -> bool { + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("stall_count, fix_trees") + .send() + .await + .ok() + .and_then(|o| o.item); + let prev_stall = item + .as_ref() + .and_then(|i| i.get("stall_count")) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0u32); + let seen: Vec = item + .as_ref() + .and_then(|i| i.get("fix_trees")) + .and_then(|v| v.as_ss().ok()) + .cloned() + .unwrap_or_default(); + let noop = fix_made_no_progress(tree_before, tree_after, &seen); + let (new_stall, halt) = noop_fix_decision(prev_stall, noop); + if noop { + warn!( + run_id, + tree = tree_after.unwrap_or(""), + stall_count = new_stall, + "CI fix left the tree unchanged or back at an earlier state — counted as a stall" + ); + } + let trees: Vec = [tree_before, tree_after] + .into_iter() + .flatten() + .filter(|t| !t.is_empty()) + .map(String::from) + .collect(); + let mut update = 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)) + .expression_attribute_values(":c", attr_n(new_stall as u64)) + .expression_attribute_values(":n", AttributeValue::Bool(noop)); + update = if trees.is_empty() { + update.update_expression("SET stall_count = :c, last_fix_noop = :n") + } else { + update + .update_expression("SET stall_count = :c, last_fix_noop = :n ADD fix_trees :t") + .expression_attribute_values(":t", AttributeValue::Ss(trees)) + }; + let _ = update.send().await; + halt +} + async fn load_cycle_from_checkpoint(state: &WorkerState, team_id: &str, run_id: &str) -> usize { if state.config.checkpoints_table_name.is_empty() { return 0;