diff --git a/docs/incidents/xl_file_modes_kept.md b/docs/incidents/xl_file_modes_kept.md new file mode 100644 index 00000000..b0f9e778 --- /dev/null +++ b/docs/incidents/xl_file_modes_kept.md @@ -0,0 +1,9 @@ +# xl. `xl_file_modes_kept` + +**What happened:** A pull request held an executable `scripts/deploy.sh` and a symbolic link. CoderHelm brought the base into it. The merge conflicted, so CoderHelm built the merged tree itself, and every file it took from the base was written as a plain file. The script lost its executable bit, and the pipeline that ran it failed with "permission denied". A later fix round that edited the script dropped the bit again. + +**Why:** Every tree CoderHelm wrote through GitHub's API named each file it wrote as a plain file, whatever the file was: the batch write of a round, the merge commit of a conflicted merge of the base, and a reader that filled in a plain file's mode when GitHub's listing named none. Only GitHub's own merge, used when nothing conflicts, kept modes. + +**The guarantee:** Every entry CoderHelm writes keeps the mode the path already has in the tree the write is based on. A new path takes the mode of the entry it came from, such as the other side of a merge, or the executable bit a sandbox build left on a file it generated. Only a new path with no source is a plain file. Text is never written over a symbolic link or a submodule: the write is refused and says why. A conflicted merge of the base lays whole entries from the base over the branch, and a path both sides changed takes its mode as git merges it. A commit that still changes a mode names each change in its message and in the run's log. The mode values live in one helper, and a scan of the source fails on any other place that types one. On the pull request watch sweep, each open pull request's CoderHelm commits of the last 30 days are read once. A mode one of them dropped is put back at the head in one commit named "Restore file modes CoderHelm dropped", moved only as a fast forward. What can't safely be put back (a path a person changed since, a link whose text changed, a submodule) is listed on the run page and in an internal alert. + +**Where it's enforced:** `clients::git_mode::{archive_sources, for_content, overlay, merged, tree_entry, changes, with_trailer, dropped, repair}`. `sandbox::read_changed_tar` and `CodegenOutcome::executable`. `GitHubClient::{entries_at, batch_write, batch_write_from, create_merge_commit, write_file, put_tree}`, `GitEntry::from_json`. `pr::{resolve_conflicts, merge_plan}`, `restack::resolve`, `agent::tool_outcome::remark`, `mode_repair::{sweep, repair_one, plan}` and `pr_watch::sweep`. diff --git a/services/common/src/agent_log.rs b/services/common/src/agent_log.rs index 50dba01d..8930c768 100644 --- a/services/common/src/agent_log.rs +++ b/services/common/src/agent_log.rs @@ -132,6 +132,18 @@ impl ToolOutcome { pub fn to_value(&self) -> Value { serde_json::to_value(self).unwrap_or(Value::Null) } + /// The outcome with lines the code under the tool added (a commit that + /// changed file modes) put first, so the summary's cap never cuts them. + pub fn with_remarks(self, remarks: &[String]) -> Self { + if remarks.is_empty() { + return self; + } + let mut parts: Vec<&str> = remarks.iter().map(String::as_str).collect(); + if let Some(s) = self.summary.as_deref() { + parts.push(s); + } + Self::new(self.status, parts.join("; ")) + } } /// A message the worker put into the conversation itself. diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index edeaca34..17ee1dd0 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -1150,14 +1150,15 @@ pub async fn converse_tool_loop( let tool_start = std::time::Instant::now(); info!(tool = %tool_name, "Executing tool"); - let (gated, noted) = super::tool_outcome::capture(super::policy::gated_execute( - gate, - tool_executor, - tool_name, - tool_input, - common::truncate_str(why.trim(), 500), - )) - .await; + let (gated, noted, remarks) = + super::tool_outcome::capture(super::policy::gated_execute( + gate, + tool_executor, + tool_name, + tool_input, + common::truncate_str(why.trim(), 500), + )) + .await; let ran = match gated { super::policy::Gated::Ran(r) => r, super::policy::Gated::Refused(message) => { @@ -1237,7 +1238,8 @@ pub async fn converse_tool_loop( Some(o) if !is_error => o, Some(o) if o.status == common::agent_log::OutcomeStatus::Error => o, _ => common::agent_log::ToolOutcome::default_for(is_error), - }; + } + .with_remarks(&remarks); if let Some(o) = observer { o.on_tool_ended(&super::llm::ToolEnded { name: tool_name, diff --git a/services/worker/src/agent/tool_outcome.rs b/services/worker/src/agent/tool_outcome.rs index 9c79ea57..77a8b5c7 100644 --- a/services/worker/src/agent/tool_outcome.rs +++ b/services/worker/src/agent/tool_outcome.rs @@ -14,6 +14,7 @@ pub use common::agent_log::ToolOutcome; tokio::task_local! { static SLOT: RefCell>; + static REMARKS: RefCell>; } /// Records the outcome of the tool call running now. Outside a call (a @@ -22,13 +23,26 @@ pub fn note(outcome: ToolOutcome) { let _ = SLOT.try_with(|s| *s.borrow_mut() = Some(outcome)); } +/// Adds a line to the outcome of the tool call running now, whatever its +/// tool notes: what the code under the tool did that the run's log must +/// show (a commit that changed file modes). Outside a call it does nothing. +pub fn remark(line: impl Into) { + let line = line.into(); + let _ = REMARKS.try_with(|r| r.borrow_mut().push(line)); +} + /// Runs one tool call and returns what it returned with the outcome its -/// tool noted, if it noted one. -pub async fn capture(call: F) -> (F::Output, Option) { +/// tool noted, if it noted one, and the remarks made under it. +pub async fn capture(call: F) -> (F::Output, Option, Vec) { SLOT.scope(RefCell::new(None), async move { - let out = call.await; - let noted = SLOT.with(|s| s.borrow_mut().take()); - (out, noted) + REMARKS + .scope(RefCell::new(Vec::new()), async move { + let out = call.await; + let noted = SLOT.with(|s| s.borrow_mut().take()); + let remarks = REMARKS.with(|r| std::mem::take(&mut *r.borrow_mut())); + (out, noted, remarks) + }) + .await }) .await } @@ -39,7 +53,7 @@ mod tests { #[tokio::test] async fn a_noted_outcome_is_captured_and_the_last_note_wins() { - let (v, o) = capture(async { + let (v, o, _) = capture(async { note(ToolOutcome::ok("first")); tokio::task::yield_now().await; note(ToolOutcome::soft_fail("NO edits applied")); @@ -52,16 +66,34 @@ mod tests { #[tokio::test] async fn no_note_is_none_and_notes_never_leak_between_calls() { - let (_, o) = capture(async {}).await; + let (_, o, r) = capture(async {}).await; + assert!(r.is_empty()); assert_eq!(o, None); // A nested call (a sub-agent's tool) keeps its own outcome. - let (_, outer) = capture(async { - let (_, inner) = capture(async { note(ToolOutcome::error("inner")) }).await; + let (_, outer, _) = capture(async { + let (_, inner, _) = capture(async { note(ToolOutcome::error("inner")) }).await; assert_eq!(inner, Some(ToolOutcome::error("inner"))); }) .await; assert_eq!(outer, None); // Outside any call a note does nothing (and never panics). note(ToolOutcome::ok("nowhere")); + remark("nowhere"); + } + + #[tokio::test] + async fn a_remark_is_kept_whatever_the_tool_notes_after_it() { + let (_, o, r) = capture(async { + remark("File modes changed: `run.sh`"); + note(ToolOutcome::ok("Wrote run.sh")); + }) + .await; + assert_eq!(o, Some(ToolOutcome::ok("Wrote run.sh"))); + assert_eq!(r, vec!["File modes changed: `run.sh`".to_string()]); + let (_, outcome, _) = capture(async {}).await; + let merged = outcome + .unwrap_or_else(|| ToolOutcome::default_for(false)) + .with_remarks(&r); + assert!(merged.summary.unwrap().contains("File modes changed")); } } diff --git a/services/worker/src/clients/git_mode.rs b/services/worker/src/clients/git_mode.rs new file mode 100644 index 00000000..f1d4ebf4 --- /dev/null +++ b/services/worker/src/clients/git_mode.rs @@ -0,0 +1,347 @@ +//! The mode of every entry CoderHelm writes into a git tree. +//! +//! A tree written through GitHub's API names each entry's mode. Writing +//! every file as a plain file turned executable scripts into plain files +//! on every merge of the base and every edit, and would have turned a +//! symbolic link or a submodule into a text file. Every tree CoderHelm +//! writes takes its modes from here: +//! +//! - a path that is already in the tree the write is based on keeps the +//! mode it has there ([`for_content`]); +//! - a new path takes the mode of the entry it was copied from (the other +//! side of a merge, the other branch of a rebuild); +//! - only a new path with no source is a plain file; +//! - text is never written over a symbolic link or a submodule. +//! +//! A path both sides of a merge changed takes its mode as git merges it +//! ([`merged`]). A commit that still changes a path's mode says so +//! ([`changes`], [`with_trailer`]). +//! +//! The mode literals live only in this file: incident `xl` scans the rest +//! of the source for them. + +use std::collections::{BTreeMap, HashMap}; + +use serde_json::{json, Value}; + +use super::github::GitEntry; + +/// A plain file. +pub const FILE: &str = "100644"; +/// An executable file. +pub const EXECUTABLE: &str = "100755"; +/// A symbolic link (its blob is the link's target). +pub const SYMLINK: &str = "120000"; +/// A submodule (its entry is a commit of another repository). +pub const SUBMODULE: &str = "160000"; + +/// The message of the commit that puts back modes CoderHelm dropped. +pub const RESTORE_MESSAGE: &str = "Restore file modes CoderHelm dropped"; + +/// Whether `mode` is a file's: plain or executable. +pub fn is_file(mode: &str) -> bool { + mode == FILE || mode == EXECUTABLE +} + +/// The mode in words. +pub fn named(mode: &str) -> &'static str { + match mode { + FILE => "a plain file", + EXECUTABLE => "an executable file", + SYMLINK => "a symbolic link", + SUBMODULE => "a submodule", + _ => "an entry of unknown mode", + } +} + +/// A new file with no source to copy a mode from (a screenshot, a file the +/// agent created): a plain file. +pub fn new_file(sha: impl Into) -> GitEntry { + GitEntry { + mode: FILE.to_string(), + kind: "blob".to_string(), + sha: sha.into(), + } +} + +/// The source entries of files a sandbox build wrote: each path its archive +/// marks executable is the source of an executable file, so a new one is +/// committed executable ([`for_content`]). A path already in the tree keeps +/// its own mode. +pub fn archive_sources(executable: &[String]) -> HashMap { + executable + .iter() + .map(|p| { + ( + p.clone(), + GitEntry { + mode: EXECUTABLE.to_string(), + kind: "blob".to_string(), + sha: String::new(), + }, + ) + }) + .collect() +} + +/// The entry text written at `path` is committed as: the path's mode in the +/// tree the write is based on (`existing`), else the mode of the file it +/// was copied from (`source`), else a plain file. `Err` (the refusal the +/// writer reads) when the path, or its source, is a symbolic link or a +/// submodule: writing text there would replace it with a file. +pub fn for_content( + path: &str, + existing: Option<&GitEntry>, + source: Option<&GitEntry>, +) -> Result { + let (e, how) = match (existing, source) { + (Some(e), _) => (e, "is"), + (None, Some(s)) => (s, "was copied from"), + (None, None) => return Ok(FILE.to_string()), + }; + if e.kind == "blob" && is_file(&e.mode) { + return Ok(e.mode.clone()); + } + Err(format!( + "`{path}` {how} {} in the tree; writing text there would replace it with a file, \ + so nothing was written. Change what it points to instead.", + named(&e.mode) + )) +} + +/// The mode of a path both sides of a merge kept, as git merges it: a side +/// that left the mode as it was at the common ancestor takes the other +/// side's; when both changed it, ours (the branch's) stands. +pub fn merged(ancestor: Option<&str>, ours: Option<&str>, theirs: Option<&str>) -> Option { + match (ours, theirs) { + (Some(o), Some(t)) if ancestor == Some(o) => Some(t.to_string()), + (Some(o), _) => Some(o.to_string()), + (None, t) => t.map(String::from), + } +} + +/// Content writes laid over the tree they are based on, each with its mode: +/// `writes` holds each path with its new blob (`None` removes the path), +/// `existing` the paths' entries in the base tree, `sources` the entry a +/// new path was copied from. `Err` names a path whose write was refused +/// ([`for_content`]). +pub fn overlay( + writes: &[(String, Option)], + existing: &HashMap, + sources: &HashMap, +) -> Result)>, String> { + writes + .iter() + .map(|(path, blob)| match blob { + None => Ok((path.clone(), None)), + Some(sha) => { + let mode = for_content(path, existing.get(path), sources.get(path))?; + Ok(( + path.clone(), + Some(GitEntry { + mode, + kind: "blob".to_string(), + sha: sha.clone(), + }), + )) + } + }) + .collect() +} + +/// The trees API's entry for `path` (`None` removes it). `Err` for an entry +/// whose mode isn't known: GitHub would refuse it, or worse, take a default. +pub fn tree_entry(path: &str, e: Option<&GitEntry>) -> Result { + match e { + Some(e) if e.mode.is_empty() || e.kind.is_empty() => Err(format!( + "`{path}` has no known mode in the tree it came from; it wasn't written" + )), + Some(e) => Ok(json!({"path": path, "mode": e.mode, "type": e.kind, "sha": e.sha})), + // A removal names no object; GitHub still asks for a mode. + None => Ok(json!({"path": path, "mode": FILE, "type": "blob", "sha": Value::Null})), + } +} + +/// A path a commit kept under another mode than its first parent had. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ModeChange { + pub path: String, + pub from: String, + pub to: String, +} + +impl ModeChange { + /// "`scripts/deploy.sh`: an executable file (100755) to a plain file + /// (100644)". + pub fn line(&self) -> String { + format!( + "`{}`: {} ({}) to {} ({})", + self.path, + named(&self.from), + self.from, + named(&self.to), + self.to + ) + } +} + +/// Each path of `written` that is in `parent` too but under another mode. +pub fn changes<'a>( + parent: impl Fn(&str) -> Option<&'a GitEntry>, + written: &[(String, Option)], +) -> Vec { + written + .iter() + .filter_map(|(path, e)| { + let (before, after) = (parent(path)?, e.as_ref()?); + (before.mode != after.mode).then(|| ModeChange { + path: path.clone(), + from: before.mode.clone(), + to: after.mode.clone(), + }) + }) + .collect() +} + +/// The commit message with the modes it changes said at its end, so the +/// change is visible in the pull request's history. +pub fn with_trailer(message: &str, changes: &[ModeChange]) -> String { + if changes.is_empty() { + return message.to_string(); + } + let mut m = format!("{}\n\nFile modes changed:", message.trim_end()); + for c in changes { + m.push_str(&format!("\n- {}", c.line())); + } + m +} + +/// One line for a run's log. +pub fn note(changes: &[ModeChange]) -> Option { + (!changes.is_empty()).then(|| { + format!( + "File modes changed: {}", + changes + .iter() + .map(ModeChange::line) + .collect::>() + .join("; ") + ) + }) +} + +// ── Putting back modes an earlier commit dropped ────────────────────────── + +/// A mode one of CoderHelm's commits dropped: the path, the commit, the +/// entry its first parent had and the one the commit wrote. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Dropped { + pub path: String, + pub commit: String, + pub before: GitEntry, + pub after: GitEntry, +} + +/// The paths `commit` turned from an executable file, a symbolic link or a +/// submodule into a plain file, against its first parent. +pub fn dropped( + commit: &str, + parent: &HashMap, + after: &HashMap, +) -> Vec { + let mut out: Vec = after + .iter() + .filter_map(|(path, a)| { + let b = parent.get(path)?; + let lost = b.mode == EXECUTABLE || b.mode == SYMLINK || b.mode == SUBMODULE; + (lost && a.mode == FILE && a.kind == "blob").then(|| Dropped { + path: path.clone(), + commit: commit.to_string(), + before: b.clone(), + after: a.clone(), + }) + }) + .collect(); + out.sort_by(|x, y| x.path.cmp(&y.path)); + out +} + +/// What the repair does with one dropped mode at the branch's head. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Repair { + /// The entry the head gets back. + Restore(GitEntry), + /// Nothing to do: the path isn't a plain file at the head any more. + Fine, + /// Left as it is, with why; listed for a person. + Leave(String), +} + +/// One dropped mode against the branch's head: `head` is the path's entry +/// there, `person_since` whether a commit that isn't CoderHelm's touched +/// the path after the one that dropped its mode. Only the mode moves: an +/// executable gets its bit back on the head's own content; a symbolic +/// link only while its text is still the link's target, unchanged. +pub fn repair(d: &Dropped, head: Option<&GitEntry>, person_since: bool) -> Repair { + let Some(h) = head else { + return Repair::Fine; + }; + if h.mode != FILE || h.kind != "blob" { + return Repair::Fine; + } + if person_since { + return Repair::Leave(format!( + "`{}` was {} before CoderHelm's commit {}; a person changed it since, so it is left for them", + d.path, + named(&d.before.mode), + short(&d.commit) + )); + } + match d.before.mode.as_str() { + EXECUTABLE => Repair::Restore(GitEntry { + mode: EXECUTABLE.to_string(), + kind: "blob".to_string(), + sha: h.sha.clone(), + }), + SYMLINK if h.sha == d.before.sha => Repair::Restore(d.before.clone()), + SYMLINK => Repair::Leave(format!( + "`{}` was a symbolic link before CoderHelm's commit {}; its text changed since, \ + so the link's target isn't known", + d.path, + short(&d.commit) + )), + _ => Repair::Leave(format!( + "`{}` was {} before CoderHelm's commit {}; it can't be set back from a file", + d.path, + named(&d.before.mode), + short(&d.commit) + )), + } +} + +/// The first drop of each path, oldest commit first (`drops` in commit +/// order). +pub fn first_drops(drops: Vec) -> BTreeMap { + let mut out = BTreeMap::new(); + for d in drops { + out.entry(d.path.clone()).or_insert(d); + } + out +} + +/// The restore commit's message: what each path gets back. +pub fn restore_message(restored: &[(String, GitEntry)]) -> String { + let mut m = format!("{RESTORE_MESSAGE}\n"); + for (path, e) in restored { + m.push_str(&format!( + "\n- `{path}`: back to {} ({})", + named(&e.mode), + e.mode + )); + } + m +} + +fn short(sha: &str) -> &str { + &sha[..7.min(sha.len())] +} diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 81b61841..659d71a8 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -7,6 +7,7 @@ use std::sync::Arc; use std::sync::Mutex; use std::time::{SystemTime, UNIX_EPOCH}; +use super::git_mode; use super::repo_snapshot::RepoSnapshot; const API_BASE: &str = "https://api.github.com"; @@ -819,6 +820,16 @@ pub enum ResetDecision { /// A commit CoderHelm made: its GitHub author is a bot (an app's /// `name[bot]`), or, with no linked account, its author email is a bot's /// noreply address. +/// A commit that changed file modes says so in the run's log: the tool call +/// that made it carries the line, and the worker's log names the branch. +fn note_mode_changes(branch: &str, changes: &[git_mode::ModeChange]) { + let Some(line) = git_mode::note(changes) else { + return; + }; + tracing::warn!(branch, changes = %line, "A commit CoderHelm made changed file modes"); + crate::agent::tool_outcome::remark(line); +} + pub fn is_bot_commit(c: &serde_json::Value) -> bool { common::person_lines::is_bot_commit(c) } @@ -3465,6 +3476,65 @@ impl GitHubClient { .collect()) } + /// Each of `paths`' entry in the tree of `rev` (a commit or tree sha), + /// read level by level: only the directories on the paths are read, + /// and a level named by its sha is never asked twice. A path that isn't + /// there, or is a directory, is left out. + pub async fn entries_at( + &self, + owner: &str, + repo: &str, + rev: &str, + paths: &[&str], + ) -> Result, Box> { + let mut levels: HashMap> = HashMap::new(); + let mut dirs: HashMap> = HashMap::new(); + dirs.insert(String::new(), Some(rev.to_string())); + let mut out = HashMap::new(); + for path in paths { + let (dir, name) = path.rsplit_once('/').unwrap_or(("", path)); + // The directory's tree, walked down from the root once. + let mut walked = String::new(); + let mut cur = dirs[""].clone(); + for part in dir.split('/').filter(|p| !p.is_empty()) { + if !walked.is_empty() { + walked.push('/'); + } + walked.push_str(part); + if let Some(t) = dirs.get(&walked) { + cur = t.clone(); + continue; + } + cur = match cur { + Some(t) => { + if !levels.contains_key(&t) { + let l = self.tree_level(owner, repo, &t).await?; + levels.insert(t.clone(), l); + } + levels[&t] + .iter() + .find(|(n, e)| n == part && e.kind == "tree") + .map(|(_, e)| e.sha.clone()) + } + None => None, + }; + dirs.insert(walked.clone(), cur.clone()); + } + let Some(t) = cur else { continue }; + if !levels.contains_key(&t) { + let l = self.tree_level(owner, repo, &t).await?; + levels.insert(t.clone(), l); + } + if let Some((_, e)) = levels[&t] + .iter() + .find(|(n, e)| n == name && e.kind != "tree") + { + out.insert(path.to_string(), e.clone()); + } + } + Ok(out) + } + /// A blob's bytes. pub async fn blob_bytes( &self, @@ -3511,17 +3581,10 @@ impl GitHubClient { base_tree: &str, changes: &[(String, Option)], ) -> Result> { - let entries: Vec = changes + let entries = changes .iter() - .map(|(path, e)| match e { - Some(e) => serde_json::json!({ - "path": path, "mode": e.mode, "type": e.kind, "sha": e.sha, - }), - None => serde_json::json!({ - "path": path, "mode": "100644", "type": "blob", "sha": null, - }), - }) - .collect(); + .map(|(path, e)| git_mode::tree_entry(path, e.as_ref())) + .collect::, _>>()?; // An empty base: a tree of only these entries. let body = if base_tree.is_empty() { serde_json::json!({"tree": entries}) @@ -3777,6 +3840,24 @@ impl GitHubClient { // ─── Single file write ────────────────────────────────────── + /// Whether a write of text at `path` on `branch` must go through a tree + /// to keep the path's mode: it is an executable file there. `Err` (the + /// refusal) when it is a symbolic link or a submodule. + async fn needs_tree_write( + &self, + owner: &str, + repo: &str, + branch: &str, + path: &str, + ) -> Result> { + let tip = self.get_ref(owner, repo, branch).await?; + let here = self.entries_at(owner, repo, &tip, &[path]).await?; + Ok(match here.get(path) { + Some(e) => git_mode::for_content(path, Some(e), None)? != git_mode::FILE, + None => false, + }) + } + /// Create or update a single file via Contents API. #[allow(clippy::too_many_arguments)] pub async fn write_file( @@ -3789,6 +3870,18 @@ impl GitHubClient { message: &str, sha: Option<&str>, ) -> Result> { + // The contents API names no mode: a path that isn't a plain file + // (an executable script) is written through a tree, which keeps it. + if self.needs_tree_write(owner, repo, branch, path).await? { + let op = FileOp::Write { + path: path.to_string(), + content: content.to_string(), + }; + let sha = self + .batch_write(owner, repo, branch, message, std::slice::from_ref(&op)) + .await?; + return Ok(serde_json::json!({"commit": {"sha": sha}})); + } // A person's lines on the branch stay theirs: what of this write // would undo one is not committed (`hold_for_people`). let held = self @@ -3907,7 +4000,8 @@ impl GitHubClient { // ─── Batch write (atomic multi-file commit) ───────────────── - /// Atomic multi-file commit via git trees API. + /// Atomic multi-file commit via git trees API: each path keeps its mode, + /// and a new one is a plain file ([`Self::batch_write_from`]). pub async fn batch_write( &self, owner: &str, @@ -3915,6 +4009,21 @@ impl GitHubClient { branch: &str, message: &str, files: &[FileOp], + ) -> Result> { + self.batch_write_from(owner, repo, branch, message, files, &HashMap::new()) + .await + } + + /// [`Self::batch_write`] where a new path takes the mode of its entry + /// in `sources` (a file a sandbox build left executable). + pub async fn batch_write_from( + &self, + owner: &str, + repo: &str, + branch: &str, + message: &str, + files: &[FileOp], + sources: &HashMap, ) -> Result> { // A person's lines on the branch stay theirs: what of this write // would undo one is not committed (`hold_for_people`). @@ -3931,43 +4040,9 @@ impl GitHubClient { } } // Blobs are content-addressed and immutable — create them once, reuse - // across retries. - let mut blob_entries = Vec::new(); - for f in files { - match f { - FileOp::Write { path, content } => { - let blob_url = format!("{API_BASE}/repos/{owner}/{repo}/git/blobs"); - let blob = self - .post( - &blob_url, - &serde_json::json!({ - "content": content, - "encoding": "utf-8", - }), - ) - .await?; - let blob_sha = blob - .get("sha") - .and_then(|v| v.as_str()) - .ok_or("Missing blob sha")? - .to_string(); - blob_entries.push(serde_json::json!({ - "path": path, - "mode": "100644", - "type": "blob", - "sha": blob_sha, - })); - } - FileOp::Delete { path } => { - blob_entries.push(serde_json::json!({ - "path": path, - "mode": "100644", - "type": "blob", - "sha": null, - })); - } - } - } + // across retries. Their modes are read per attempt from the tree + // each attempt builds on (`git_mode`). + let blobs = self.put_text_blobs(owner, repo, files).await?; // Build tree + commit ON THE CURRENT TIP and update the ref with a // fast-forward-only CAS. If another writer raced us, rebuild on their @@ -3993,6 +4068,7 @@ impl GitHubClient { let commit_url = format!("{API_BASE}/repos/{owner}/{repo}/git/commits"); let mut commit_sha = String::new(); let mut committed = false; + let mut landed_modes = Vec::new(); for attempt in 0..6u32 { let branch_sha = self.get_ref(owner, repo, branch).await?; if let Some(expected) = self.snapshot_base_sha(owner, repo, branch).await { @@ -4032,6 +4108,18 @@ impl GitHubClient { self.invalidate_snapshot(owner, repo, branch).await; } } + // Each path keeps the mode it has on the tip this commit builds + // on: an executable stays executable, and text is never written + // over a symbolic link or a submodule. + let existing = self + .entries_at(owner, repo, &branch_sha, &write_paths) + .await?; + let changes = git_mode::overlay(&blobs, &existing, sources)?; + let modes = git_mode::changes(|p| existing.get(p), &changes); + let blob_entries = changes + .iter() + .map(|(path, e)| git_mode::tree_entry(path, e.as_ref())) + .collect::, _>>()?; let tree = self .post( &tree_url, @@ -4046,12 +4134,13 @@ impl GitHubClient { .post( &commit_url, &serde_json::json!({ - "message": message, + "message": git_mode::with_trailer(message, &modes), "tree": tree_sha, "parents": [branch_sha], }), ) .await?; + landed_modes = modes; commit_sha = commit .get("sha") .and_then(|v| v.as_str()) @@ -4073,6 +4162,7 @@ impl GitHubClient { "batch_write: branch kept advancing under concurrent writes (6 retries)".into(), ); } + note_mode_changes(branch, &landed_modes); for f in files { match f { @@ -4091,43 +4181,19 @@ impl GitHubClient { Ok(commit_sha) } - /// Create a merge commit with two parents (for conflict resolution). - /// Builds a tree from the branch tree + overridden files, then creates - /// a commit with both branch and base as parents. - #[allow(clippy::too_many_arguments)] - pub async fn create_merge_commit( + /// Writes each `FileOp::Write`'s text as a blob: each path with its + /// blob, `None` for a removal. + async fn put_text_blobs( &self, owner: &str, repo: &str, - branch: &str, - branch_sha: &str, - base_sha: &str, - message: &str, - resolved_files: &[FileOp], - ) -> Result> { - // Get the branch commit's tree as the base tree - let commit_url = format!("{API_BASE}/repos/{owner}/{repo}/git/commits/{branch_sha}"); - let commit_data = self.get(&commit_url).await?; - let base_tree = commit_data - .pointer("/tree/sha") - .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 { + files: &[FileOp], + ) -> Result)>, Box> { + let blob_url = format!("{API_BASE}/repos/{owner}/{repo}/git/blobs"); + let mut out = Vec::with_capacity(files.len()); + for f in files { match f { FileOp::Write { path, content } => { - let blob_url = format!("{API_BASE}/repos/{owner}/{repo}/git/blobs"); let blob = self .post( &blob_url, @@ -4137,27 +4203,51 @@ impl GitHubClient { }), ) .await?; - let blob_sha = blob + let sha = blob .get("sha") .and_then(|v| v.as_str()) - .ok_or("Missing blob sha")?; - tree_entries.push(serde_json::json!({ - "path": path, - "mode": "100644", - "type": "blob", - "sha": blob_sha, - })); - } - FileOp::Delete { path } => { - tree_entries.push(serde_json::json!({ - "path": path, - "mode": "100644", - "type": "blob", - "sha": null, - })); + .ok_or("Missing blob sha")? + .to_string(); + out.push((path.clone(), Some(sha))); } + FileOp::Delete { path } => out.push((path.clone(), None)), } } + Ok(out) + } + + /// Create a merge commit with two parents (for conflict resolution): + /// the branch's tree with `changes` laid over it, each an entry already + /// carrying its mode (taken whole from the side it came from, or merged + /// by [`git_mode::merged`]); `None` removes the path. Returns the commit + /// and the modes it changed against the branch, which its message also + /// names. + #[allow(clippy::too_many_arguments)] + pub async fn create_merge_commit( + &self, + owner: &str, + repo: &str, + branch: &str, + branch_sha: &str, + base_sha: &str, + message: &str, + changes: &[(String, Option)], + ) -> Result<(String, Vec), Box> { + // Get the branch commit's tree as the base tree + let commit_url = format!("{API_BASE}/repos/{owner}/{repo}/git/commits/{branch_sha}"); + let commit_data = self.get(&commit_url).await?; + let base_tree = commit_data + .pointer("/tree/sha") + .and_then(|v| v.as_str()) + .ok_or("Missing tree sha in branch commit")?; + + let paths: Vec<&str> = changes.iter().map(|(p, _)| p.as_str()).collect(); + let before = self.entries_at(owner, repo, branch_sha, &paths).await?; + let modes = git_mode::changes(|p| before.get(p), changes); + let tree_entries = changes + .iter() + .map(|(path, e)| git_mode::tree_entry(path, e.as_ref())) + .collect::, _>>()?; // Create tree with resolved files overlaid on branch tree let tree_url = format!("{API_BASE}/repos/{owner}/{repo}/git/trees"); @@ -4181,7 +4271,7 @@ impl GitHubClient { .post( &new_commit_url, &serde_json::json!({ - "message": message, + "message": git_mode::with_trailer(message, &modes), "tree": tree_sha, "parents": [branch_sha, base_sha], }), @@ -4205,8 +4295,9 @@ impl GitHubClient { // Merge commit pulls in base content we can't mirror file-by-file. self.invalidate_snapshot(owner, repo, branch).await; + note_mode_changes(branch, &modes); - Ok(commit_sha) + Ok((commit_sha, modes)) } // ─── Diff ─────────────────────────────────────────────────── @@ -6658,7 +6749,9 @@ impl GitEntry { pub fn from_json(e: &serde_json::Value) -> Option { let kind = e["type"].as_str()?; (kind != "tree").then(|| GitEntry { - mode: e["mode"].as_str().unwrap_or("100644").to_string(), + // Never a guessed mode: an entry with none is refused when + // written (`git_mode::tree_entry`). + mode: e["mode"].as_str().unwrap_or("").to_string(), kind: kind.to_string(), sha: e["sha"].as_str().unwrap_or("").to_string(), }) diff --git a/services/worker/src/clients/mod.rs b/services/worker/src/clients/mod.rs index d4c6719d..714abcb8 100644 --- a/services/worker/src/clients/mod.rs +++ b/services/worker/src/clients/mod.rs @@ -1,4 +1,5 @@ pub mod email; +pub mod git_mode; pub mod github; pub mod github_budget; pub mod github_cache; diff --git a/services/worker/src/clients/sandbox.rs b/services/worker/src/clients/sandbox.rs index cc543846..52e4e09b 100644 --- a/services/worker/src/clients/sandbox.rs +++ b/services/worker/src/clients/sandbox.rs @@ -284,6 +284,8 @@ pub struct CodegenOutcome { pub passed: bool, /// (path, content) for each file codegen created or modified. pub changed: Vec<(String, String)>, + /// The paths of `changed` the build left executable. + pub executable: Vec, /// Files codegen changed that couldn't be brought back (too large, not /// text, past the file cap), each with why. A run with any is not a /// complete regeneration. @@ -298,6 +300,7 @@ impl CodegenOutcome { ran: false, passed: false, changed: Vec::new(), + executable: Vec::new(), dropped: Vec::new(), output: reason.into(), } @@ -310,6 +313,9 @@ impl CodegenOutcome { pub struct Captured { pub files: Vec<(String, String)>, pub dropped: Vec, + /// The paths of `files` the archive marks executable: a new one is + /// committed executable (`git_mode::archive_sources`). + pub executable: Vec, } /// Reads a changed-files archive (tar.gz, paths from the repository root). @@ -342,12 +348,16 @@ pub fn read_changed_tar( )); continue; } + let executable = entry.header().mode().is_ok_and(|m| m & 0o111 != 0); let mut content = String::new(); use std::io::Read; if entry.read_to_string(&mut content).is_err() { out.dropped.push(format!("`{path}` (not a text file)")); continue; } + if executable { + out.executable.push(path.clone()); + } out.files.push((path, content)); } Ok(out) @@ -1542,6 +1552,7 @@ pub async fn codegen_outcome( ran: true, passed: true, changed: captured.files, + executable: captured.executable, dropped: captured.dropped, output, }; @@ -1584,6 +1595,7 @@ pub async fn codegen_outcome( ran: true, passed: true, changed: retry.files, + executable: retry.executable, dropped: retry.dropped, output, }; @@ -1599,6 +1611,7 @@ pub async fn codegen_outcome( ran: true, passed, changed: Vec::new(), + executable: Vec::new(), dropped: Vec::new(), output, } diff --git a/services/worker/src/passes/deploy_revert.rs b/services/worker/src/passes/deploy_revert.rs index bba8b468..950cd6f5 100644 --- a/services/worker/src/passes/deploy_revert.rs +++ b/services/worker/src/passes/deploy_revert.rs @@ -621,11 +621,7 @@ mod tests { use super::*; fn e(sha: &str) -> GitEntry { - GitEntry { - mode: "100644".to_string(), - kind: "blob".to_string(), - sha: sha.to_string(), - } + crate::clients::git_mode::new_file(sha) } fn tree(files: &[(&str, &str)]) -> HashMap { diff --git a/services/worker/src/passes/generators.rs b/services/worker/src/passes/generators.rs index 271bd43f..9419449a 100644 --- a/services/worker/src/passes/generators.rs +++ b/services/worker/src/passes/generators.rs @@ -1346,50 +1346,54 @@ async fn run_in_sandbox( ) .await { - Ok(o) => match read_outcome(o, cmd, || sandbox.has_time(w.deadline)) { - Read::Refused(f) => { - EgressBlocks::record(w.run_id, &f); - Ran::Blocked(f) - } - 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()), - }; + Ok(o) => { + // A new file the build left executable is committed executable. + let sources = crate::clients::git_mode::archive_sources(&o.executable); + 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 = 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::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_from(owner, name, w.branch, &message, &ops, &sources) + .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), } - 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()), } } @@ -2177,9 +2181,10 @@ pub(crate) async fn run_lock_repair( .into_iter() .map(|(path, content)| FileOp::Write { path, content }) .collect(); + let sources = crate::clients::git_mode::archive_sources(&o.executable); if let Err(e) = job .github - .batch_write(job.owner, job.repo, job.branch, job.message, &ops) + .batch_write_from(job.owner, job.repo, job.branch, job.message, &ops, &sources) .await { // Written in the sandbox, not on the branch: say so per lockfile. diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 58b2daec..48ec0c32 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -4151,14 +4151,17 @@ impl<'a> WriteToolExecutor<'a> { }) .collect(); let paths: Vec = o.changed.iter().map(|(p, _)| p.clone()).collect(); + // A new file the build left executable is committed executable. + let sources = crate::clients::git_mode::archive_sources(&o.executable); match self .github - .batch_write( + .batch_write_from( &self.owner, &self.repo, &self.branch, &self.commit_message("chore: regenerate generated files (codegen)"), &ops, + &sources, ) .await { diff --git a/services/worker/src/passes/incidents/bc_stays_through_merge_and_deploy.rs b/services/worker/src/passes/incidents/bc_stays_through_merge_and_deploy.rs index d4d7ee4f..4511519a 100644 --- a/services/worker/src/passes/incidents/bc_stays_through_merge_and_deploy.rs +++ b/services/worker/src/passes/incidents/bc_stays_through_merge_and_deploy.rs @@ -42,11 +42,7 @@ fn approved() -> Seen { } fn entry(sha: &str) -> GitEntry { - GitEntry { - mode: "100644".into(), - kind: "blob".into(), - sha: sha.into(), - } + crate::clients::git_mode::new_file(sha) } fn tree(files: &[(&str, &str)]) -> HashMap { diff --git a/services/worker/src/passes/incidents/bd_skill_runs_on_coderhelm.rs b/services/worker/src/passes/incidents/bd_skill_runs_on_coderhelm.rs index 147977ab..898a4ea4 100644 --- a/services/worker/src/passes/incidents/bd_skill_runs_on_coderhelm.rs +++ b/services/worker/src/passes/incidents/bd_skill_runs_on_coderhelm.rs @@ -290,6 +290,7 @@ fn the_script_run_keeps_its_files_as_outputs_and_never_its_token() { ("report.html".into(), "".into()), ], dropped: vec![], + executable: vec![], }, ); assert!(out.ran && out.exit_code == Some(0)); diff --git a/services/worker/src/passes/incidents/f_steps.rs b/services/worker/src/passes/incidents/f_steps.rs index a9b2d057..569397f8 100644 --- a/services/worker/src/passes/incidents/f_steps.rs +++ b/services/worker/src/passes/incidents/f_steps.rs @@ -24,6 +24,7 @@ fn a_generator_build_without_time_needs_a_step_not_a_failure() { ran: false, passed: false, changed: Vec::new(), + executable: Vec::new(), dropped: Vec::new(), output: "codegen not run: not enough time left in this step for a sandbox build".into(), }; diff --git a/services/worker/src/passes/incidents/xl_file_modes_kept.rs b/services/worker/src/passes/incidents/xl_file_modes_kept.rs new file mode 100644 index 00000000..f530d761 --- /dev/null +++ b/services/worker/src/passes/incidents/xl_file_modes_kept.rs @@ -0,0 +1,537 @@ +//! xl. A pull request held an executable `scripts/deploy.sh` and a +//! symbolic link. CoderHelm brought the base into it; the merge +//! conflicted, so CoderHelm built the merged tree itself, and every file +//! it took from the base was written as a plain file. The script lost its +//! executable bit and the pipeline that ran it failed with "permission +//! denied". A later fix round that edited the script dropped the bit +//! again. +//! +//! Why: every tree CoderHelm wrote through GitHub's API named the mode of +//! each file it wrote as a plain file, whatever the file was: the batch +//! write of a round, the merge commit of a conflicted merge of the base, +//! and a reader that filled in a plain file's mode when GitHub's listing +//! named none. Only GitHub's own merge (no conflict) kept modes. +//! +//! Guarantee: every entry CoderHelm writes keeps the mode the path already +//! has in the tree the write is based on; a new path takes the mode of the +//! entry it came from (the other side of a merge); only a new path with no +//! source is a plain file; text is never written over a symbolic link or a +//! submodule. A conflicted merge of the base lays whole entries from the +//! base over the branch, and a path both sides changed takes its mode as +//! git merges it. A commit that still changes a mode says so in its +//! message and in the run's log. The mode literals live in one helper +//! (`clients::git_mode`), and a scan of the source fails on any other. On +//! the pull request watch sweep, each open pull request's CoderHelm commits +//! of the last 30 days are read once, and a mode one of them dropped is put +//! back at the head in a commit named "Restore file modes CoderHelm +//! dropped"; what can't safely be put back is listed on the run page and +//! in an internal alert. + +use std::collections::{HashMap, HashSet}; + +use super::fixture::fn_src; +use crate::clients::git_mode::{self, Repair, EXECUTABLE, FILE, SUBMODULE, SYMLINK}; +use crate::clients::github::GitEntry; +use crate::passes::mode_repair; +use crate::passes::pr::merge_plan; + +const DEPLOY: &str = "scripts/deploy.sh"; +const LINK: &str = "config/current"; +const RELEASE: &str = "scripts/release.sh"; + +fn entry(mode: &str, sha: &str) -> GitEntry { + GitEntry { + mode: mode.to_string(), + kind: "blob".to_string(), + sha: sha.to_string(), + } +} + +fn tree(entries: &[(&str, GitEntry)]) -> HashMap { + entries + .iter() + .map(|(p, e)| (p.to_string(), e.clone())) + .collect() +} + +/// The branch's tree with `changes` laid over it, as GitHub's trees API +/// with a base tree does. +fn laid_over( + base: &HashMap, + changes: &[(String, Option)], +) -> HashMap { + let mut out = base.clone(); + for (p, e) in changes { + match e { + Some(e) => { + out.insert(p.clone(), e.clone()); + } + None => { + out.remove(p); + } + } + } + out +} + +/// A pull request with an executable script and a symbolic link; the base +/// changed both (a new line in the script, the link pointed elsewhere) and +/// added an executable script of its own; both sides changed `README.md`, +/// so the merge conflicts and CoderHelm builds the merged tree. +#[test] +fn merging_the_base_keeps_the_executable_and_the_link() { + let ancestor = tree(&[ + (DEPLOY, entry(EXECUTABLE, "d0")), + (LINK, entry(SYMLINK, "l0")), + ("README.md", entry(FILE, "r0")), + ]); + let branch = tree(&[ + (DEPLOY, entry(EXECUTABLE, "d0")), + (LINK, entry(SYMLINK, "l0")), + ("README.md", entry(FILE, "r-branch")), + ]); + let base = tree(&[ + (DEPLOY, entry(EXECUTABLE, "d-base")), + (LINK, entry(SYMLINK, "l-base")), + (RELEASE, entry(EXECUTABLE, "rel")), + ("README.md", entry(FILE, "r-base")), + ]); + let base_only = [DEPLOY, LINK, RELEASE]; + let both = ["README.md"]; + let plan = merge_plan(&base_only, &base, &both, &ancestor, &branch, &base); + + // Every path only the base changed is its whole entry from the base. + let merged = laid_over(&branch, &plan.take); + assert_eq!(merged[DEPLOY], entry(EXECUTABLE, "d-base")); + assert_eq!(merged[LINK], entry(SYMLINK, "l-base")); + // A new file copied from the base keeps its executable bit. + assert_eq!(merged[RELEASE], entry(EXECUTABLE, "rel")); + // The text both changed goes to the model, as a plain file. + assert_eq!(plan.to_merge.len(), 1); + assert_eq!(plan.to_merge[0].path, "README.md"); + assert_eq!(plan.to_merge[0].mode, FILE); + assert!(plan.kept_branch.is_empty()); + + // The trees API is sent each entry's own mode, never a default. + for (p, e) in &plan.take { + let v = git_mode::tree_entry(p, e.as_ref()).unwrap(); + assert_eq!(v["mode"], base[p.as_str()].mode.as_str()); + } + // Against the branch, the merge changed no mode. + assert!(git_mode::changes(|p| branch.get(p), &plan.take).is_empty()); +} + +/// Both sides edited the script: the merged script stays executable, and +/// when only the base made a file executable the merge takes it, as git +/// does. A link changed on one side and edited as text on the other is +/// never merged as text: the branch's entry stands. +#[test] +fn a_file_both_sides_changed_takes_its_mode_as_git_merges_it() { + let ancestor = tree(&[ + (DEPLOY, entry(EXECUTABLE, "d0")), + ("bin/tool", entry(FILE, "t0")), + (LINK, entry(SYMLINK, "l0")), + ]); + let branch = tree(&[ + (DEPLOY, entry(EXECUTABLE, "d-branch")), + ("bin/tool", entry(FILE, "t-branch")), + (LINK, entry(SYMLINK, "l-branch")), + ]); + let base = tree(&[ + (DEPLOY, entry(EXECUTABLE, "d-base")), + ("bin/tool", entry(EXECUTABLE, "t-base")), + (LINK, entry(FILE, "l-text")), + ]); + let both = [DEPLOY, "bin/tool", LINK]; + let plan = merge_plan(&[], &HashMap::new(), &both, &ancestor, &branch, &base); + let mode = |p: &str| { + plan.to_merge + .iter() + .find(|m| m.path == p) + .map(|m| m.mode.clone()) + }; + assert_eq!(mode(DEPLOY).as_deref(), Some(EXECUTABLE)); + assert_eq!(mode("bin/tool").as_deref(), Some(EXECUTABLE)); + assert_eq!(plan.kept_branch, vec![LINK.to_string()]); + + // The same content with only the mode changed on the base: the mode + // alone is taken. + let branch = tree(&[("bin/tool", entry(FILE, "t1"))]); + let base = tree(&[("bin/tool", entry(EXECUTABLE, "t1"))]); + let ancestor = tree(&[("bin/tool", entry(FILE, "t0"))]); + let plan = merge_plan( + &[], + &HashMap::new(), + &["bin/tool"], + &ancestor, + &branch, + &base, + ); + assert_eq!( + plan.take, + vec![("bin/tool".to_string(), Some(entry(EXECUTABLE, "t1")))] + ); + // That change is named: in the merge commit's message and the log. + let changes = git_mode::changes(|p| branch.get(p), &plan.take); + assert_eq!(changes.len(), 1); + let message = git_mode::with_trailer("Merge main into the branch", &changes); + assert!(message.contains("File modes changed:")); + assert!(message.contains("`bin/tool`: a plain file (100644) to an executable file (100755)")); + assert!(git_mode::note(&changes).unwrap().contains("`bin/tool`")); +} + +/// A fix round edits the script: the new content is written with the mode +/// the script has on the branch. A new file with no source is a plain +/// file; one copied from an executable is executable. Text over a symbolic +/// link or a submodule is refused, never written as a file. +#[test] +fn a_fix_round_editing_the_script_keeps_it_executable() { + let on_branch = tree(&[ + (DEPLOY, entry(EXECUTABLE, "d1")), + (LINK, entry(SYMLINK, "l1")), + ( + "vendor/lib", + GitEntry { + mode: SUBMODULE.to_string(), + kind: "commit".to_string(), + sha: "c1".to_string(), + }, + ), + ]); + let writes = vec![ + (DEPLOY.to_string(), Some("d2".to_string())), + ("notes.md".to_string(), Some("n1".to_string())), + (RELEASE.to_string(), Some("rel".to_string())), + ("old.txt".to_string(), None), + ]; + let sources = tree(&[(RELEASE, entry(EXECUTABLE, "d1"))]); + let changes = git_mode::overlay(&writes, &on_branch, &sources).unwrap(); + assert_eq!( + changes[0], + (DEPLOY.to_string(), Some(entry(EXECUTABLE, "d2"))) + ); + assert_eq!( + changes[1], + ("notes.md".to_string(), Some(entry(FILE, "n1"))) + ); + assert_eq!( + changes[2], + (RELEASE.to_string(), Some(entry(EXECUTABLE, "rel"))) + ); + assert_eq!(changes[3], ("old.txt".to_string(), None)); + assert!(git_mode::changes(|p| on_branch.get(p), &changes).is_empty()); + let sent = git_mode::tree_entry(DEPLOY, changes[0].1.as_ref()).unwrap(); + assert_eq!(sent["mode"], EXECUTABLE); + + for refused in [LINK, "vendor/lib"] { + let w = vec![(refused.to_string(), Some("text".to_string()))]; + let err = git_mode::overlay(&w, &on_branch, &HashMap::new()).unwrap_err(); + assert!(err.contains("nothing was written"), "{err}"); + } + // An entry read with no mode is never sent with a guessed one. + let unknown = GitEntry { + mode: String::new(), + kind: "blob".to_string(), + sha: "x".to_string(), + }; + assert!(git_mode::tree_entry("a", Some(&unknown)).is_err()); + assert!( + GitEntry::from_json(&serde_json::json!({"type": "blob", "sha": "x"})) + .unwrap() + .mode + .is_empty() + ); +} + +/// The writers read each path's mode before they write: the batch write +/// and the merge commit build their entries through the helper, and the +/// single-file write sends anything that isn't a plain file through a tree. +/// One method of an `impl`: from its head to the next method. +fn method<'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 = [ + "\n pub async fn ", + "\n async fn ", + "\n pub fn ", + "\n fn ", + ] + .iter() + .filter_map(|m| rest.find(m)) + .min() + .unwrap_or(rest.len()); + &rest[..end] +} + +#[test] +fn every_writer_reads_the_mode_it_writes() { + let gh = include_str!("../../clients/github.rs"); + let fn_src = method; + let plain = fn_src(gh, "pub async fn batch_write("); + assert!( + plain.contains(".batch_write_from(owner, repo, branch, message, files, &HashMap::new())") + ); + let batch = fn_src(gh, "pub async fn batch_write_from("); + assert!(batch.contains(".entries_at(owner, repo, &branch_sha, &write_paths)")); + assert!(batch.contains("git_mode::overlay(")); + assert!(batch.contains("git_mode::with_trailer(")); + let merge = fn_src(gh, "pub async fn create_merge_commit("); + assert!(merge.contains("git_mode::tree_entry(")); + assert!(merge.contains("git_mode::with_trailer(")); + let single = fn_src(gh, "pub async fn write_file("); + assert!(single.contains(".needs_tree_write(owner, repo, branch, path)")); + let needs = method(gh, "async fn needs_tree_write("); + assert!(needs.contains("git_mode::for_content(path, Some(e), None)?")); + assert!(single.contains(".batch_write(")); + let put = fn_src(gh, "pub async fn put_tree("); + assert!(put.contains("git_mode::tree_entry(")); + + let pr = include_str!("../pr.rs"); + let resolve = super::fixture::fn_src(pr, "pub async fn resolve_conflicts("); + assert!(resolve.contains("merge_plan(")); + assert!(!resolve.contains("FileOp::Write")); + let restack = include_str!("../restack.rs"); + assert!(restack.contains("crate::clients::git_mode::merged(")); +} + +/// The guard: no source file but the helper names a mode. A new tree write +/// that types a mode instead of reading the path's fails here. +#[test] +fn no_mode_is_typed_outside_the_helper() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let q = |a: &str, b: &str| format!("\"{a}{b}\""); + let plain = [q("100", "644"), q("100", "755")]; + let with_mode = [q("120", "000"), q("160", "000")]; + let mut found = Vec::new(); + for dir in ["worker/src", "common/src", "gateway/src"] { + let mut stack = vec![root.join(dir)]; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + continue; + } + if p.extension().and_then(|x| x.to_str()) != Some("rs") + || p.ends_with("clients/git_mode.rs") + { + continue; + } + let src = std::fs::read_to_string(&p).unwrap(); + for (n, line) in src.lines().enumerate() { + let typed = plain.iter().any(|m| line.contains(m.as_str())) + || (line.contains("mode") + && with_mode.iter().any(|m| line.contains(m.as_str()))); + if typed { + found.push(format!("{}:{}", p.display(), n + 1)); + } + } + } + } + } + assert!( + found.is_empty(), + "a git mode typed outside clients/git_mode.rs (read the path's entry instead): {found:?}" + ); +} + +fn commits(own: &[(&str, bool)]) -> Vec { + own.iter().map(|(s, _)| s.to_string()).collect() +} + +/// The repair: CoderHelm's merge commit dropped the script's bit and turned +/// the link into a file. Both come back at the head, in one commit that +/// changes only modes; a second look finds nothing to do. +#[test] +fn the_sweep_puts_back_what_an_own_commit_dropped() { + let parent = tree(&[ + (DEPLOY, entry(EXECUTABLE, "d1")), + (LINK, entry(SYMLINK, "l1")), + ("README.md", entry(FILE, "r1")), + ]); + let after = tree(&[ + (DEPLOY, entry(FILE, "d2")), + (LINK, entry(FILE, "l1")), + ("README.md", entry(FILE, "r2")), + ]); + let read = vec![("c-merge".to_string(), true, parent, after)]; + let drops = mode_repair::drops_of(&read); + assert_eq!(drops.len(), 2); + let order = commits(&[("c-merge", true), ("c-fix", true)]); + // A later CoderHelm commit edited the script again. + let head = tree(&[(DEPLOY, entry(FILE, "d3")), (LINK, entry(FILE, "l1"))]); + let r = mode_repair::plan(drops.clone(), &head, &order, &HashMap::new()); + assert_eq!( + r.restored, + vec![ + (LINK.to_string(), entry(SYMLINK, "l1")), + (DEPLOY.to_string(), entry(EXECUTABLE, "d3")), + ] + ); + assert!(r.left.is_empty()); + let message = git_mode::restore_message(&r.restored); + assert!(message.starts_with("Restore file modes CoderHelm dropped")); + assert!(message.contains("`scripts/deploy.sh`: back to an executable file (100755)")); + + // Idempotent: once restored, the head needs nothing. + let fixed = tree(&[ + (DEPLOY, entry(EXECUTABLE, "d3")), + (LINK, entry(SYMLINK, "l1")), + ]); + let again = mode_repair::plan(drops, &fixed, &order, &HashMap::new()); + assert_eq!(again, mode_repair::Repaired::default()); + assert_eq!(mode_repair::page_line(&again), None); +} + +/// What can't be put back safely is left and listed: a path a person +/// touched after the drop, a link whose text changed, a submodule. A +/// person's own commit is never read as a drop. +#[test] +fn the_sweep_leaves_what_is_in_doubt_and_lists_it() { + let parent = tree(&[ + (DEPLOY, entry(EXECUTABLE, "d1")), + (LINK, entry(SYMLINK, "l1")), + ( + "vendor/lib", + GitEntry { + mode: SUBMODULE.to_string(), + kind: "commit".to_string(), + sha: "c1".to_string(), + }, + ), + ]); + let after = tree(&[ + (DEPLOY, entry(FILE, "d1")), + (LINK, entry(FILE, "l1")), + ("vendor/lib", entry(FILE, "v1")), + ]); + let read = vec![ + ("c-own".to_string(), true, parent.clone(), after.clone()), + ("c-person".to_string(), false, parent, after), + ]; + let drops = mode_repair::drops_of(&read); + assert!(drops.iter().all(|d| d.commit == "c-own")); + let order = commits(&[("c-own", true), ("c-person", false)]); + let mut people = HashMap::new(); + people.insert( + "c-person".to_string(), + [DEPLOY.to_string()].into_iter().collect::>(), + ); + let head = tree(&[ + (DEPLOY, entry(FILE, "d9")), + (LINK, entry(FILE, "l-edited")), + ("vendor/lib", entry(FILE, "v1")), + ]); + let r = mode_repair::plan(drops, &head, &order, &people); + assert!(r.restored.is_empty()); + assert_eq!(r.left.len(), 3); + assert!(r + .left + .iter() + .any(|w| w.contains("a person changed it since"))); + assert!(r + .left + .iter() + .any(|w| w.contains("the link's target isn't known"))); + assert!(r.left.iter().any(|w| w.contains("a submodule"))); + let line = mode_repair::page_line(&r).unwrap(); + assert!(line.contains("left as they are")); + + // A path gone from the head needs nothing. + let d = git_mode::Dropped { + path: DEPLOY.to_string(), + commit: "c-own".to_string(), + before: entry(EXECUTABLE, "d1"), + after: entry(FILE, "d1"), + }; + assert_eq!(git_mode::repair(&d, None, false), Repair::Fine); +} + +/// The repair runs on the watch sweep, claimed once per pull request and +/// version, inside the sweep's budget, and moves the branch only as a fast +/// forward from the head it read. +#[test] +fn the_repair_is_claimed_capped_and_never_forced() { + let watch = include_str!("../pr_watch.rs"); + assert!(watch.contains("super::mode_repair::sweep(state, &mut budget, &mut clients)")); + let src = include_str!("../mode_repair.rs"); + let sweep = fn_src(src, "pub async fn sweep("); + assert!(sweep.contains("if !claim(state, &c).await")); + assert!(sweep.contains("budget.allows(state, c.installation_id, REQUESTS)")); + assert!(sweep.contains("catch_up_picks(all, PER_TEAM, MAX_PRS)")); + assert!(sweep.contains("own_problems::alert(")); + assert!(sweep.contains("add_progress_note(")); + let one = fn_src(src, "pub async fn repair_one("); + assert!(one.contains(".fast_forward(owner, repo, branch, head, &commit)")); + assert!(!one.contains("move_with_lease")); + assert!(!one.contains("move_scratch_ref")); + assert_eq!(mode_repair::WINDOW_DAYS, 30); +} + +/// A codegen build's archive with Unix modes: `(path, text, mode)`. +fn archive(files: &[(&str, &str, u32)]) -> Vec { + use std::io::Write; + let gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + let mut ar = tar::Builder::new(gz); + for (path, data, mode) in files { + let mut h = tar::Header::new_gnu(); + h.set_size(data.len() as u64); + h.set_mode(*mode); + h.set_entry_type(tar::EntryType::Regular); + h.set_cksum(); + ar.append_data(&mut h, format!("./{path}"), data.as_bytes()) + .unwrap(); + } + let mut out = ar.into_inner().unwrap().finish().unwrap(); + out.flush().unwrap(); + out +} + +/// A codegen build writes a new executable script next to a plain file: +/// the archive's executable bit reaches the commit, so the new script is +/// executable; a plain file stays plain, and a path already on the branch +/// keeps the branch's mode whatever the archive says. +#[test] +fn a_new_file_a_build_left_executable_is_committed_executable() { + use crate::clients::sandbox; + let bytes = archive(&[ + ("bin/generate-client.sh", "#!/bin/sh\necho ok\n", 0o755), + ("src/gen/types.ts", "export type Id = string;\n", 0o644), + ("scripts/lint.sh", "#!/bin/sh\n", 0o644), + ]); + let captured = sandbox::read_archive(&bytes).unwrap(); + assert_eq!(captured.files.len(), 3); + assert_eq!( + captured.executable, + vec!["bin/generate-client.sh".to_string()] + ); + + // The branch already has `scripts/lint.sh` executable. + let on_branch = tree(&[("scripts/lint.sh", entry(EXECUTABLE, "s0"))]); + let sources = git_mode::archive_sources(&captured.executable); + let writes = vec![ + ("bin/generate-client.sh".to_string(), Some("g1".to_string())), + ("src/gen/types.ts".to_string(), Some("t1".to_string())), + ("scripts/lint.sh".to_string(), Some("s1".to_string())), + ]; + let changes = git_mode::overlay(&writes, &on_branch, &sources).unwrap(); + assert_eq!(changes[0].1, Some(entry(EXECUTABLE, "g1"))); + assert_eq!(changes[1].1, Some(entry(FILE, "t1"))); + assert_eq!(changes[2].1, Some(entry(EXECUTABLE, "s1"))); + + // Every commit of a build's output passes the archive's modes on. + let implement = include_str!("../implement.rs"); + assert!(implement.contains("git_mode::archive_sources(&o.executable)")); + assert!(implement.contains(".batch_write_from(")); + let generators = include_str!("../generators.rs"); + assert_eq!( + generators + .matches("git_mode::archive_sources(&o.executable)") + .count(), + 2 + ); + assert_eq!(generators.matches(".batch_write_from(").count(), 2); + let sandbox_src = include_str!("../../clients/sandbox.rs"); + assert!(sandbox_src.contains("executable: captured.executable,")); + assert!(sandbox_src.contains("executable: retry.executable,")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index c38c0d29..01d09a39 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1370,6 +1370,7 @@ mod log_fix_checks; mod log_fix_eval; pub mod log_look; pub mod minimal_change; +pub mod mode_repair; pub mod model_check; #[cfg(test)] mod model_route_eval; diff --git a/services/worker/src/passes/mode_repair.rs b/services/worker/src/passes/mode_repair.rs new file mode 100644 index 00000000..cdbef7c4 --- /dev/null +++ b/services/worker/src/passes/mode_repair.rs @@ -0,0 +1,367 @@ +//! Putting back the file modes CoderHelm's own commits dropped. +//! +//! Until every tree write kept each path's mode (`clients::git_mode`), a +//! commit CoderHelm made through GitHub's API wrote every file it touched +//! as a plain file: a merge of the base into a pull request, or a fix round +//! editing a script, turned an executable script into a plain file and +//! could turn a symbolic link into a text file. +//! +//! On the pull request watch sweep, each open pull request of a run +//! changed in the last [`WINDOW_DAYS`] is read once ([`FIELD`] claims it on +//! the run, against [`VERSION`]): CoderHelm's own commits of the window are +//! compared with their first parents, and each path one of them turned from +//! an executable or a symbolic link into a plain file gets its mode back at +//! the branch's head, in one commit named [`git_mode::RESTORE_MESSAGE`] +//! that changes nothing but modes. GitHub signs a commit an app makes +//! through its API. +//! +//! Only the mode moves, and only where nothing else is in doubt +//! (`git_mode::repair`): a path a person touched since, a link whose text +//! changed, a submodule, are left as they are and listed on the run page +//! and in an internal alert. The branch moves only as a fast forward from +//! the head that was read. A second look finds nothing to do: the modes +//! are back. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use tracing::{info, warn}; + +use super::pr_watch::{self, Candidate}; +use super::{attr_n, attr_s}; +use crate::clients::git_mode::{self, Dropped, Repair}; +use crate::clients::github::{GitEntry, GitHubClient}; +use crate::WorkerState; + +/// The run attribute claiming the repair of its pull request. +pub const FIELD: &str = "modes_repaired"; +/// The repair's version: a pull request is read once per version. +pub const VERSION: &str = "1"; +/// CoderHelm's commits this recent are read. +pub const WINDOW_DAYS: i64 = 30; +/// Pull requests one sweep reads for each team. +pub const PER_TEAM: usize = 3; +/// The most pull requests one sweep reads, all teams together. +pub const MAX_PRS: usize = 15; +/// The most of a branch's commits one repair reads. +pub const MAX_COMMITS: usize = 30; +/// GitHub requests one repair may make (the pull request, its commits, +/// each own commit's files and trees, the write): one isn't started with +/// less than this left of the sweep's budget. +pub const REQUESTS: u64 = 60; + +/// What one repair came to. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Repaired { + /// The restore commit, when one was pushed. + pub commit: Option, + /// Each path given its mode back. + pub restored: Vec<(String, GitEntry)>, + /// Each path left as it is, with why. + pub left: Vec, +} + +/// The run's pull request is CoderHelm's and still open, in the window: +/// the sweep's scan. +const FILTER: &str = "pr_number > :zero AND attribute_not_exists(pr_outcome) \ + AND updated_at >= :cut AND (attribute_not_exists(#m) OR #m <> :v)"; + +/// One commit read for the repair: its sha, whether CoderHelm made it, its +/// paths' entries at its first parent and at the commit. +pub type ReadCommit = ( + String, + bool, + HashMap, + HashMap, +); + +/// The paths each own commit dropped, in commit order, from `commits` +/// (oldest first): each commit's `(sha, author is CoderHelm, parent +/// entries, own entries)`. +pub fn drops_of(commits: &[ReadCommit]) -> Vec { + commits + .iter() + .filter(|(_, own, _, _)| *own) + .flat_map(|(sha, _, parent, after)| git_mode::dropped(sha, parent, after)) + .collect() +} + +/// The plan for the head: `drops` (oldest first), the paths' entries at the +/// head, the branch's commits in order (`order`), and the paths each +/// person's commit touched (`people`, by commit). +pub fn plan( + drops: Vec, + head: &HashMap, + order: &[String], + people: &HashMap>, +) -> Repaired { + let mut out = Repaired::default(); + for (path, d) in git_mode::first_drops(drops) { + let at = order.iter().position(|c| *c == d.commit).unwrap_or(0); + let person_since = order[at + 1..] + .iter() + .any(|c| people.get(c).is_some_and(|ps| ps.contains(&path))); + match git_mode::repair(&d, head.get(&path), person_since) { + Repair::Restore(e) => out.restored.push((path, e)), + Repair::Fine => {} + Repair::Leave(why) => out.left.push(why), + } + } + out +} + +/// One pull request: its CoderHelm commits of the window read against their +/// parents, and what they dropped put back at the head. +pub async fn repair_one( + github: &GitHubClient, + c: &Candidate, +) -> Result> { + let (owner, repo) = (c.owner.as_str(), c.repo.as_str()); + let pr = github.get_pull_request(owner, repo, c.pr).await?; + if pr["state"].as_str() != Some("open") { + return Ok(Repaired::default()); + } + let same_repo = pr["head"]["repo"]["full_name"] + .as_str() + .is_some_and(|f| f.eq_ignore_ascii_case(&format!("{owner}/{repo}"))); + let (Some(head), Some(branch), Some(base)) = ( + pr["head"]["sha"].as_str(), + pr["head"]["ref"].as_str(), + pr["base"]["sha"].as_str(), + ) else { + return Ok(Repaired::default()); + }; + if !same_repo { + return Ok(Repaired::default()); + } + let bot = github.app_bot_login().await?; + let cutoff = chrono::Utc::now() - chrono::Duration::days(WINDOW_DAYS); + let all = github.compare_all_commits(owner, repo, base, head).await?; + let listed: Vec<&serde_json::Value> = all + .iter() + .rev() + .take(MAX_COMMITS) + .collect::>() + .into_iter() + .rev() + .collect(); + let order: Vec = listed + .iter() + .filter_map(|c| c["sha"].as_str().map(String::from)) + .collect(); + let mut read = Vec::new(); + let mut persons = Vec::new(); + for commit in &listed { + let Some(sha) = commit["sha"].as_str() else { + continue; + }; + if commit["author"]["login"].as_str() != Some(bot.as_str()) { + persons.push(sha.to_string()); + continue; + } + let recent = commit + .pointer("/commit/committer/date") + .and_then(|d| d.as_str()) + .and_then(|d| chrono::DateTime::parse_from_rfc3339(d).ok()) + .is_some_and(|d| d >= cutoff); + let Some(parent) = commit["parents"][0]["sha"].as_str() else { + continue; + }; + if !recent { + continue; + } + let files = github.commit_files(owner, repo, sha).await?; + if files.is_empty() { + continue; + } + let paths: Vec<&str> = files.iter().map(String::as_str).collect(); + let before = github.entries_at(owner, repo, parent, &paths).await?; + let after = github.entries_at(owner, repo, sha, &paths).await?; + read.push((sha.to_string(), true, before, after)); + } + let drops = drops_of(&read); + if drops.is_empty() { + return Ok(Repaired::default()); + } + // The paths a person's commit after the first drop touched: theirs to + // decide. + let first = drops + .iter() + .filter_map(|d| order.iter().position(|c| *c == d.commit)) + .min() + .unwrap_or(0); + let mut people: HashMap> = HashMap::new(); + for sha in persons { + if order.iter().position(|c| *c == sha).unwrap_or(0) > first { + let files = github.commit_files(owner, repo, &sha).await?; + people.insert(sha, files.into_iter().collect()); + } + } + let paths: Vec<&str> = drops.iter().map(|d| d.path.as_str()).collect(); + let at_head = github.entries_at(owner, repo, head, &paths).await?; + let mut out = plan(drops, &at_head, &order, &people); + if out.restored.is_empty() { + return Ok(out); + } + let (head_tree, _) = github.commit_tree_parents(owner, repo, head).await?; + let changes: Vec<(String, Option)> = out + .restored + .iter() + .map(|(p, e)| (p.clone(), Some(e.clone()))) + .collect(); + let tree = github.put_tree(owner, repo, &head_tree, &changes).await?; + let message = git_mode::restore_message(&out.restored); + let commit = github + .put_commit(owner, repo, &message, &tree, &[head.to_string()]) + .await?; + // A fast forward from the head that was read, never a force push: when + // someone pushed meanwhile, nothing moves and the next version's look + // reads it again. + if github + .fast_forward(owner, repo, branch, head, &commit) + .await? + { + out.commit = Some(commit); + } else { + out.left.push(format!( + "the branch moved while the modes were being put back; nothing was pushed to `{branch}`" + )); + out.restored.clear(); + } + Ok(out) +} + +/// The run page's line for a repair. +pub fn page_line(r: &Repaired) -> Option { + let mut parts = Vec::new(); + if let Some(c) = &r.commit { + parts.push(format!( + "Put back the file modes an earlier CoderHelm commit dropped ({}): {}.", + &c[..7.min(c.len())], + r.restored + .iter() + .map(|(p, e)| format!("`{p}` is {} again", git_mode::named(&e.mode))) + .collect::>() + .join(", ") + )); + } + if !r.left.is_empty() { + parts.push(format!( + "File modes an earlier CoderHelm commit dropped, left as they are: {}.", + r.left.join("; ") + )); + } + (!parts.is_empty()).then(|| parts.join(" ")) +} + +/// Claims the repair of `c`'s pull request for this version: false when it +/// already was. +async fn claim(state: &WorkerState, c: &Candidate) -> bool { + state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&c.team_id)) + .key("run_id", attr_s(&c.run_id)) + .update_expression("SET #f = :v") + .condition_expression("attribute_exists(run_id) AND (attribute_not_exists(#f) OR #f <> :v)") + .expression_attribute_names("#f", FIELD) + .expression_attribute_values(":v", attr_s(VERSION)) + .send() + .await + .is_ok() +} + +/// Gives the claim back when GitHub refused for a while, so a later sweep +/// reads it again. +async fn release(state: &WorkerState, c: &Candidate) { + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&c.team_id)) + .key("run_id", attr_s(&c.run_id)) + .update_expression("REMOVE #f") + .condition_expression("#f = :v") + .expression_attribute_names("#f", FIELD) + .expression_attribute_values(":v", attr_s(VERSION)) + .send() + .await; +} + +/// The sweep's part: a few open pull requests per team each sweep, inside +/// its GitHub budget, each read once per [`VERSION`]. Returns +/// `owner/repo#pr` for each whose modes were put back. +pub async fn sweep( + state: &WorkerState, + budget: &mut crate::clients::github_budget::SweepGate, + clients: &mut HashMap, +) -> Vec { + let cutoff = (chrono::Utc::now() - chrono::Duration::days(WINDOW_DAYS)).to_rfc3339(); + let filter = super::team_runs::Filter { + expr: FILTER, + names: vec![("#m", FIELD)], + values: vec![ + (":zero", attr_n(0)), + (":cut", attr_s(&cutoff)), + (":v", attr_s(VERSION)), + ], + projection: None, + }; + let all: Vec<_> = super::team_runs::matching(state, "File mode repair", &filter) + .await + .iter() + .filter_map(pr_watch::candidate_of) + .collect(); + let mut repaired = Vec::new(); + let mut done: BTreeMap = BTreeMap::new(); + for c in pr_watch::catch_up_picks(all, PER_TEAM, MAX_PRS) { + // Two runs on one pull request: it is read once. + let key = format!("{}/{}#{}", c.owner, c.repo, c.pr); + if done.insert(key.clone(), ()).is_some() { + continue; + } + if !budget.allows(state, c.installation_id, REQUESTS).await { + continue; + } + if let std::collections::hash_map::Entry::Vacant(v) = clients.entry(c.installation_id) { + match pr_watch::client(state, c.installation_id) { + Some(g) => { + v.insert(g); + } + None => continue, + } + } + if !claim(state, &c).await { + continue; + } + let github = &clients[&c.installation_id]; + let r = match repair_one(github, &c).await { + Ok(r) => r, + Err(e) => { + warn!(run_id = %c.run_id, pr = c.pr, error = %e, "File mode repair: could not read or write the pull request"); + if github.outside().is_some() { + release(state, &c).await; + } + continue; + } + }; + if let Some(line) = page_line(&r) { + super::add_progress_note(state, &c.team_id, &c.run_id, &line).await; + } + if !r.left.is_empty() { + super::own_problems::alert( + state, + &c.team_id, + &c.run_id, + "file_modes_left", + &format!("{key}: {}", r.left.join("; ")), + ) + .await; + } + if r.commit.is_some() { + info!(pr = %key, restored = r.restored.len(), "File mode repair: modes put back"); + repaired.push(key); + } + } + repaired +} diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 260b42f3..3c79d986 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -1,9 +1,12 @@ +use std::collections::HashMap; + use aws_sdk_dynamodb::types::AttributeValue; use tracing::{info, warn}; use crate::agent::provider::ModelProvider; use crate::agent::{llm, provider}; -use crate::clients::github::{FileOp, GitHubClient}; +use crate::clients::git_mode; +use crate::clients::github::{GitEntry, GitHubClient}; use crate::models::{TicketMessage, TicketSource, TokenUsage}; use crate::passes::checks::CiCommand; use crate::passes::plan::PlanResult; @@ -1250,76 +1253,65 @@ pub async fn resolve_conflicts( "Identified conflicting files (changed on both sides)" ); - let mut resolved_files: Vec = Vec::new(); + let (owner, repo) = (msg.repo_owner.as_str(), msg.repo_name.as_str()); + // Every path is laid over the branch's tree as a whole entry, mode and + // all: a file taken from the base keeps the base's mode (an executable + // script stays executable, a symbolic link stays a link), and a merged + // file takes its mode as git merges it (`git_mode::merged`). - // For files only changed on base (not touched by branch), take the base version - for base_file in &base_changed { - let touched_by_branch = branch_files - .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_if_exists(&msg.repo_owner, &msg.repo_name, base_file, &msg.base_branch) - .await? - { - Some(content) => { - resolved_files.push(FileOp::Write { - path: base_file.clone(), - content, - }); - } - None => { - resolved_files.push(FileOp::Delete { - path: base_file.clone(), - }); - } - } - } - } + // For files only changed on base (not touched by branch), take the base + // version: its entry as it is on the base, or its removal. A failed read + // aborts the resolution instead of passing for a deletion. + let base_only: Vec<&str> = base_changed + .iter() + .filter(|base_file| { + !branch_files + .iter() + .any(|f| f.get("filename").and_then(|v| v.as_str()) == Some(base_file.as_str())) + }) + .map(String::as_str) + .collect(); + let on_base = github + .entries_at(owner, repo, &base_sha, &base_only) + .await?; // For files changed on BOTH sides, do 3-way merge with LLM - for file in &conflicting { - let path = match file.get("filename").and_then(|v| v.as_str()) { - Some(p) => p, - None => continue, - }; - + let both: Vec<&str> = conflicting + .iter() + .filter_map(|f| f.get("filename").and_then(|v| v.as_str())) + .collect(); + let ancestors = github + .entries_at(owner, repo, merge_base_sha, &both) + .await?; + let theirs = github.entries_at(owner, repo, &base_sha, &both).await?; + let ours = github.entries_at(owner, repo, &branch_sha, &both).await?; + let planned = merge_plan(&base_only, &on_base, &both, &ancestors, &ours, &theirs); + for path in &planned.kept_branch { + warn!( + branch, + path, + "Conflict on a path that isn't a text file on both sides; the branch's entry is kept" + ); + } + let mut resolved = planned.take; + for m in planned.to_merge { + let (path, o, t, mode) = (m.path.as_str(), &m.ours, &m.theirs, m.mode); // 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_if_exists(&msg.repo_owner, &msg.repo_name, path, merge_base_sha) - .await?; - let main_content = github - .read_file_if_exists(&msg.repo_owner, &msg.repo_name, path, &msg.base_branch) - .await?; - let branch_content = github - .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) { - (Some(m), Some(b)) if m == b => continue, // no actual conflict - (Some(m), Some(b)) => (m, b), - (None, Some(b)) => { - // Main deleted, branch still has it — keep branch version - resolved_files.push(FileOp::Write { - path: path.to_string(), - content: b, - }); - continue; - } - (Some(_), None) => { - // Branch deleted, main still has it — keep branch's deletion - resolved_files.push(FileOp::Delete { - path: path.to_string(), - }); - continue; - } - (None, None) => continue, + // branch, by their blobs. + let text = |b: Vec| String::from_utf8(b).ok(); + let (Some(main_content), Some(branch_content)) = ( + text(github.blob_bytes(owner, repo, &t.sha).await?), + text(github.blob_bytes(owner, repo, &o.sha).await?), + ) else { + warn!( + branch, + path, "Conflict on a file that isn't text; the branch's version is kept" + ); + continue; + }; + let ancestor = match &m.ancestor { + Some(e) => text(github.blob_bytes(owner, repo, &e.sha).await?), + None => None, }; let Some(merged_content) = merge_file( @@ -1337,13 +1329,20 @@ pub async fn resolve_conflicts( return Ok(false); }; - resolved_files.push(FileOp::Write { - path: path.to_string(), - content: merged_content, - }); + let sha = github + .put_blob(owner, repo, merged_content.as_bytes()) + .await?; + resolved.push(( + path.to_string(), + Some(GitEntry { + mode, + kind: "blob".to_string(), + sha, + }), + )); } - if resolved_files.is_empty() && !conflicting.is_empty() { + if resolved.is_empty() && !conflicting.is_empty() { warn!( branch, "Conflict detected but no files to resolve — all files matched" @@ -1363,14 +1362,14 @@ pub async fn resolve_conflicts( info!( branch, - resolved = resolved_files.len(), + resolved = resolved.len(), llm_resolved = conflicting.len(), - auto_resolved = resolved_files.len().saturating_sub(conflicting.len()), + auto_resolved = resolved.len().saturating_sub(conflicting.len()), "Creating merge commit" ); // Create a proper merge commit with TWO parents — this tells Git the merge is done - github + let (_, modes) = github .create_merge_commit( &msg.repo_owner, &msg.repo_name, @@ -1378,13 +1377,99 @@ pub async fn resolve_conflicts( &branch_sha, &base_sha, &merge_message, - &resolved_files, + &resolved, ) .await?; + if let Some(line) = git_mode::note(&modes) { + info!(branch, changes = %line, "The merge of the base changed file modes, as the base did"); + } Ok(true) } +/// A path both sides changed whose two versions are text files: the model +/// merges them, and the result is committed with `mode`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ToMerge { + pub path: String, + /// The common ancestor's version, when it is a file. + pub ancestor: Option, + pub ours: GitEntry, + pub theirs: GitEntry, + /// The merged file's mode (`git_mode::merged`). + pub mode: String, +} + +/// What resolving a conflicted merge of the base lays over the branch's +/// tree, before the model merges anything. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct MergePlan { + /// Whole entries, mode and all (`None` removes the path). + pub take: Vec<(String, Option)>, + /// Paths for the model. + pub to_merge: Vec, + /// Paths where the branch's entry stands though both changed it: a + /// symbolic link or a submodule on one side is never merged as text. + pub kept_branch: Vec, +} + +/// The plan of a conflicted merge of the base into the branch, from the +/// paths' entries: `base_only` are the paths only the base changed (their +/// entries on the base in `on_base`), `both` the paths both changed (their +/// entries at the common ancestor, on the branch and on the base). A path +/// taken from the base keeps the base's mode; a path either side deleted +/// keeps the branch's decision (its tree already holds it); a path whose +/// content is the same on both sides takes only the merged mode. +pub fn merge_plan( + base_only: &[&str], + on_base: &HashMap, + both: &[&str], + ancestors: &HashMap, + ours: &HashMap, + theirs: &HashMap, +) -> MergePlan { + let mut out = MergePlan::default(); + for path in base_only { + out.take + .push((path.to_string(), on_base.get(*path).cloned())); + } + let text_file = |e: &GitEntry| e.kind == "blob" && git_mode::is_file(&e.mode); + for path in both { + let a = ancestors.get(*path); + let (Some(o), Some(t)) = (ours.get(*path), theirs.get(*path)) else { + continue; + }; + if o == t { + continue; + } + let mode = git_mode::merged( + a.map(|e| e.mode.as_str()), + Some(o.mode.as_str()), + Some(t.mode.as_str()), + ) + .unwrap_or_else(|| o.mode.clone()); + if o.sha == t.sha { + if mode != o.mode && git_mode::is_file(&mode) && text_file(o) { + out.take + .push((path.to_string(), Some(GitEntry { mode, ..o.clone() }))); + } + continue; + } + if !text_file(o) || !text_file(t) { + out.kept_branch.push(path.to_string()); + continue; + } + out.to_merge.push(ToMerge { + path: path.to_string(), + ancestor: a.filter(|e| text_file(e)).cloned(), + ours: o.clone(), + theirs: t.clone(), + mode, + }); + } + out +} + /// Merges two versions of `path` with the model, keeping both sides' work: /// `main_content` (the `their_label` version) and `branch_content` (the /// change's, preferred only where both changed the same lines), read from diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 5e9890e5..46c61d5b 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -1325,7 +1325,7 @@ pub async fn look(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> act } -fn client(state: &WorkerState, installation_id: u64) -> Option { +pub(crate) fn client(state: &WorkerState, installation_id: u64) -> Option { GitHubClient::new( &state.secrets.github_app_id, &state.secrets.github_private_key, @@ -1389,6 +1389,9 @@ pub struct SweepReport { /// green at its head, with no event that re-evaluated it /// (`await_merge::sweep_stalled`). pub merges_woken: Vec, + /// `owner/repo#pr` for each pull request whose file modes, dropped by + /// an earlier CoderHelm commit, were put back (`mode_repair`). + pub modes_restored: Vec, } /// The sweep's scan: finished runs with a pull request, changed inside the @@ -1467,6 +1470,9 @@ pub async fn sweep(state: &WorkerState) -> SweepReport { // green that no event re-evaluated is woken once for its head. report.merges_woken = super::await_merge::sweep_stalled(state, &mut budget, &mut clients).await; report.caught_up = catch_up(state, &mut budget, &mut clients).await; + // Open pull requests whose executables or links an earlier CoderHelm + // commit turned into plain files get their modes back, once each. + report.modes_restored = super::mode_repair::sweep(state, &mut budget, &mut clients).await; report.skipped_installations = budget.skipped(); report.retry_in = budget.retry_in(); report diff --git a/services/worker/src/passes/preview.rs b/services/worker/src/passes/preview.rs index 74121d99..dd6c307e 100644 --- a/services/worker/src/passes/preview.rs +++ b/services/worker/src/passes/preview.rs @@ -1158,14 +1158,8 @@ pub async fn keep_on_ref( let mut entries: Vec<(String, Option)> = Vec::new(); for (path, bytes) in files { let sha = gh.put_blob(owner, repo, bytes).await?; - entries.push(( - path.clone(), - Some(GitEntry { - mode: "100644".into(), - kind: "blob".into(), - sha, - }), - )); + // A new image with no source: a plain file. + entries.push((path.clone(), Some(crate::clients::git_mode::new_file(sha)))); } let mut last: Box = "nothing was tried".into(); for _ in 0..REF_TRIES { diff --git a/services/worker/src/passes/restack.rs b/services/worker/src/passes/restack.rs index 13051a2c..55b52944 100644 --- a/services/worker/src/passes/restack.rs +++ b/services/worker/src/passes/restack.rs @@ -609,8 +609,16 @@ async fn resolve( repo.put_blob(m.as_bytes()) }) .await?; + // Its mode as git merges it: a side that left the mode alone takes the + // other side's (an executable stays executable). + let mode = crate::clients::git_mode::merged( + base.as_ref().map(|b| b.mode.as_str()), + Some(o.mode.as_str()), + Some(t.mode.as_str()), + ) + .unwrap_or_else(|| o.mode.clone()); Ok(Some(GitEntry { - mode: o.mode.clone(), + mode, kind: "blob".to_string(), sha, })) @@ -969,11 +977,7 @@ mod tests { use std::sync::Mutex; fn blob(sha: &str) -> GitEntry { - GitEntry { - mode: "100644".into(), - kind: "blob".into(), - sha: sha.into(), - } + crate::clients::git_mode::new_file(sha) } /// A repository in memory: commits hold whole trees (path to entry),