Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(remove): find Linux reap candidates through procfs (#4631)

Worktrunk Bot4907d2dd40de
diff --git a/flake.nix b/flake.nix
index 2fef12bb5..8656a0f5d 100644
--- a/flake.nix
+++ b/flake.nix
@@ -164,9 +164,9 @@
src = pkgs.lib.cleanSource ./.;
# Tests shell out to a few host tools — `git` for the harness,
# `python3` for argv-quoting and post-start fixtures, `ps`
- # (procps) for the pgid invariant test, `lsof` for the
- # `--reap` process-discovery test, `ssh-keygen` (openssh) for
- # the `--no-ff` commit-signing test. Without these on PATH
+ # (procps) for process checks, `lsof` for fsmonitor socket
+ # discovery, and `ssh-keygen` (openssh) for the `--no-ff`
+ # commit-signing test. Without these on PATH
# the sandbox surfaces them as `No such file or directory`.
nativeBuildInputs = commonArgs.nativeBuildInputs ++ [
pkgs.git
diff --git a/src/git/reap.rs b/src/git/reap.rs
index a0f576323..2c9c69f5b 100644
--- a/src/git/reap.rs
+++ b/src/git/reap.rs
@@ -11,11 +11,10 @@
//! # Discovery
//!
//! Processes are discovered by working directory: any process whose `cwd` is
-//! at or under the worktree path. `lsof -d cwd` reports every visible
-//! process's cwd in one call; [`parse_lsof_cwd`] parses it and the caller
-//! filters by path prefix. This is deliberately scoped to processes the
-//! invoking user can see (no root), matching the `lsof` reliance already
-//! established by [`super::fsmonitor`].
+//! at or under the worktree path. Linux reads `/proc/<pid>/cwd` directly so a
+//! system-wide `lsof` scan cannot time out and hide all candidates. Other Unix
+//! systems use `lsof -d cwd`; [`parse_lsof_cwd`] parses its output. Both paths
+//! skip processes whose cwd cannot be read and filter by the worktree prefix.
//!
//! # Data-safety contract
//!
@@ -56,11 +55,11 @@ use crate::shell_exec::Cmd;
use super::fsmonitor::{NixSignaller, REAP_KILL_DEADLINE, escalate_terminate};
/// One process discovered under a worktree: its PID, short command name, and
-/// the working directory `lsof` reported.
+/// the working directory reported by the platform's process probe.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CwdProcess {
pub pid: u32,
- /// Short command name from `lsof` (truncated to ~9 chars by `lsof`).
+ /// Short command name from `/proc` or `lsof`.
pub command: String,
pub cwd: PathBuf,
}
@@ -180,14 +179,49 @@ fn without_controlling_terminal(pids: &[u32]) -> HashSet<u32> {
/// current `wt` process. This is the raw discovery step, *before* the
/// controlling-terminal guard — [`collect_reapable`] layers that on top.
///
-/// Best-effort: an `lsof` spawn failure yields an empty list. `lsof -d cwd` is
-/// run system-wide rather than with `+D <path>` so it never walks the
-/// worktree's file tree; the prefix filter is applied here instead. Results
-/// are sorted by PID for stable output.
+/// Best-effort: unreadable or disappeared processes are skipped. On non-Linux
+/// Unix, an `lsof` spawn failure yields an empty list. Results are sorted by
+/// PID for stable output.
pub fn processes_under(worktree_path: &Path) -> Vec<CwdProcess> {
let canonical =
dunce::canonicalize(worktree_path).unwrap_or_else(|_| worktree_path.to_path_buf());
+ let self_pid = std::process::id();
+
+ #[cfg(target_os = "linux")]
+ let processes = processes_from_proc(Path::new("/proc"));
+ #[cfg(not(target_os = "linux"))]
+ let processes = processes_from_lsof();
+
+ let mut candidates: Vec<CwdProcess> = processes
+ .into_iter()
+ .filter(|p| p.pid != self_pid)
+ .filter(|p| p.cwd.starts_with(&canonical))
+ .collect();
+ candidates.sort_by_key(|p| p.pid);
+ candidates
+}
+
+#[cfg(target_os = "linux")]
+fn processes_from_proc(proc_root: &Path) -> Vec<CwdProcess> {
+ let Ok(entries) = std::fs::read_dir(proc_root) else {
+ return Vec::new();
+ };
+ entries
+ .filter_map(Result::ok)
+ .filter_map(|entry| {
+ let pid = entry.file_name().to_str()?.parse::<u32>().ok()?;
+ let cwd = std::fs::read_link(entry.path().join("cwd")).ok()?;
+ let command = std::fs::read_to_string(entry.path().join("comm"))
+ .unwrap_or_default()
+ .trim_end_matches('\n')
+ .to_owned();
+ Some(CwdProcess { pid, command, cwd })
+ })
+ .collect()
+}
+#[cfg(not(target_os = "linux"))]
+fn processes_from_lsof() -> Vec<CwdProcess> {
// `lsof -d cwd` lists every visible process's cwd. It exits non-zero when
// some processes are inaccessible (other users), but still prints the
// accessible ones — so parse whatever stdout we got rather than gating on
@@ -200,14 +234,7 @@ pub fn processes_under(worktree_path: &Path) -> Vec<CwdProcess> {
return Vec::new();
};
- let self_pid = std::process::id();
- let mut candidates: Vec<CwdProcess> = parse_lsof_cwd(&String::from_utf8_lossy(&output.stdout))
- .into_iter()
- .filter(|p| p.pid != self_pid)
- .filter(|p| p.cwd.starts_with(&canonical))
- .collect();
- candidates.sort_by_key(|p| p.pid);
- candidates
+ parse_lsof_cwd(&String::from_utf8_lossy(&output.stdout))
}
/// Discover the processes eligible for reaping under `worktree_path`.
@@ -260,6 +287,13 @@ pub fn reap_summary(count: usize, gone: usize) -> Result<String, String> {
mod tests {
use super::*;
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn missing_procfs_yields_no_processes() {
+ let root = tempfile::tempdir().unwrap();
+ assert!(processes_from_proc(&root.path().join("absent")).is_empty());
+ }
+
#[test]
fn parse_lsof_cwd_extracts_pid_command_and_path() {
let stdout = "\
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 943f5a203..997da1b52 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -211,29 +211,42 @@ fn test_remove_reap_kills_process(mut repo: TestRepo) {
.unwrap();
let pid = child.id();
- // Wait until lsof reports the child's cwd — fast when idle, but under
- // suite load a single probe can burn its whole 5s in-process timeout;
- // `wait_for` carries the suite's generous presence-poll deadline.
- wait_for(
- &format!("child {pid} in cwd discovery — is lsof installed and able to read process cwds?"),
- || {
- reap::processes_under(&canonical)
- .iter()
- .any(|p| p.pid == pid)
- },
- );
+ // Wait until the platform probe reports the child's cwd.
+ wait_for(&format!("child {pid} in cwd discovery"), || {
+ reap::processes_under(&canonical)
+ .iter()
+ .any(|p| p.pid == pid)
+ });
// The guard reaps the child iff it holds no controlling terminal — which
// it inherited from this process's session, so read the session directly:
// `/dev/tty` opens iff the session has a controlling terminal.
let will_reap = std::fs::File::open("/dev/tty").is_err();
+ // Linux discovery must not depend on lsof completing its system-wide
+ // scan. An empty lsof result reproduces the timeout's lost output.
+ #[cfg(target_os = "linux")]
+ let mock_path = {
+ use crate::common::mock_commands::{MockConfig, MockResponse};
+ let bin_dir = repo.root_path().join(".bin");
+ std::fs::create_dir_all(&bin_dir).unwrap();
+ MockConfig::new("lsof")
+ .command("_default", MockResponse::output(""))
+ .write(&bin_dir);
+ let mut paths: Vec<std::path::PathBuf> = std::env::var_os("PATH")
+ .map(|p| std::env::split_paths(&p).collect())
+ .unwrap_or_default();
+ paths.insert(0, bin_dir.clone());
+ (std::env::join_paths(paths).unwrap(), bin_dir)
+ };
+
let run_remove = |repo: &TestRepo| {
- let output = repo
- .wt_command()
- .args(["remove", "--reap", "feature-reapkill"])
- .output()
- .unwrap();
+ let mut cmd = repo.wt_command();
+ cmd.args(["remove", "--reap", "feature-reapkill"]);
+ #[cfg(target_os = "linux")]
+ cmd.env("PATH", &mock_path.0)
+ .env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", &mock_path.1);
+ let output = cmd.output().unwrap();
String::from_utf8_lossy(&output.stderr).into_owned()
};
@@ -245,6 +258,13 @@ fn test_remove_reap_kills_process(mut repo: TestRepo) {
// thread already blocked in `wait()` reaps it the instant it exits.
let reaper = std::thread::spawn(move || child.wait().unwrap());
let stderr = run_remove(&repo);
+ if !stderr.contains("Reaping 1 process under") {
+ // On a regression, release the test child promptly before failing.
+ let _ = nix::sys::signal::kill(
+ nix::unistd::Pid::from_raw(pid as i32),
+ nix::sys::signal::Signal::SIGKILL,
+ );
+ }
let status = reaper.join().unwrap();
assert!(