Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(priority): unify low-priority spawning in `priority` module (#2140)
Maximilian Roosa78541ac95e2
diff --git a/src/commands/process.rs b/src/commands/process.rsindex e16fe8c38..492fcc07a 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -2,6 +2,7 @@ use anyhow::Context;use color_print::cformat;use std::fs;use std::path::{Path, PathBuf};+#[cfg(windows)]use std::process::Command;use std::process::Stdio;use std::str::FromStr;@@ -212,55 +213,15 @@ fn create_detach_log(Ok((log_path, log_file))}-/// Build a [`Command`] that runs `program` at lowered priority when `low_priority`-/// is set.-///-/// Used by the detached-spawn paths so internal cleanup ops (`wt remove`'s background-/// `rm -rf`, trash sweep) don't compete with foreground work. The policy is inherited-/// by children, so wrapping the outer shell or the target binary covers any grand--/// children too. Shells out for the same reason as-/// [`worktrunk::copy::lower_process_priority`] — `forbid(unsafe_code)` rules out a-/// direct `setpriority(2)` / `setiopolicy_np(3)` call.-///-/// - **macOS**: `/usr/sbin/taskpolicy -b` puts the child into `PRIO_DARWIN_BG`, which-/// lowers CPU scheduling *and* throttles disk + network I/O (see `setpriority(2)`).-/// `nice(1)`/`renice(8)` only touch CPU on Darwin, which leaves the dominant cost-/// of `rm -rf` on APFS un-throttled. `taskpolicy` takes `program` as a positional-/// arg (no `--` separator accepted); safe here because callers pass `sh` or an-/// absolute path.-/// - **Linux/other Unix**: `nice -n 19` — CPU only. Chaining `ionice -c 3` would cover-/// I/O too, but `ionice` isn't guaranteed in base util-linux and making it-/// mandatory here would fail the spawn outright. The self-lowering path in-/// `copy.rs` does best-effort `ionice` since an individual `.status()` failure is-/// ignored.-#[cfg(unix)]-fn low_priority_command(program: impl AsRef<std::ffi::OsStr>, low_priority: bool) -> Command {- if !low_priority {- return Command::new(program);- }- #[cfg(target_os = "macos")]- {- let mut cmd = Command::new("/usr/sbin/taskpolicy");- cmd.arg("-b").arg(program);- cmd- }- #[cfg(not(target_os = "macos"))]- {- let mut cmd = Command::new("nice");- cmd.arg("-n").arg("19").arg("--").arg(program);- cmd- }-}-/// Spawn a detached background process with output redirected to a log file.////// The process will be fully detached from the parent:/// - On Unix: uses `process_group(0)` to create a new process group (survives PTY closure)/// - On Windows: uses `CREATE_NEW_PROCESS_GROUP` to detach from console///-/// Internal ops (`HookLog::Internal`) are run at lowered priority (`taskpolicy -b`-/// on macOS, `nice -n 19` elsewhere — see `low_priority_command`) so their I/O-/// and CPU don't compete with user-visible work; user hooks run at normal priority.+/// Internal ops (`HookLog::Internal`) are run at lowered priority via+/// [`worktrunk::priority::command`] so their I/O and CPU don't compete with+/// user-visible work; user hooks run at normal priority.////// Logs are centralized in the main worktree's `.git/wt/logs/` directory.pub fn spawn_detached(@@ -333,11 +294,10 @@ fn spawn_detached_unix(// When the controlling PTY closes, SIGHUP is sent to the foreground process group.// Since our process is in a different group, it doesn't receive the signal.//- // For low-priority ops (internal cleanup), wrap the shell via `low_priority_command`- // (`taskpolicy -b` on macOS, `nice -n 19` elsewhere). The policy is inherited by the- // backgrounded command and its grandchildren. Missing binaries would fail the spawn- // (tolerable — `taskpolicy` and `nice` ship in their respective base systems).- let mut cmd = low_priority_command("sh", low_priority);+ // For low-priority ops (internal cleanup), wrap the shell via+ // `worktrunk::priority::command`. The policy is inherited by the backgrounded+ // command and its grandchildren.+ let mut cmd = worktrunk::priority::command("sh", low_priority);cmd.arg("-c").arg(&shell_cmd).current_dir(worktree_path)@@ -490,9 +450,8 @@ fn spawn_detached_exec_unix(use std::io::Write;use std::os::unix::process::CommandExt;- // See `spawn_detached_unix` and `low_priority_command` for the priority-lowering- // rationale (macOS: `taskpolicy -b`; elsewhere: `nice -n 19`).- let mut cmd = low_priority_command(program, low_priority);+ // See [`worktrunk::priority`] for the priority-lowering rationale.+ let mut cmd = worktrunk::priority::command(program, low_priority);cmd.args(args).current_dir(worktree_path).stdin(Stdio::piped())diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex a37c03efd..a99a40a36 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -708,7 +708,7 @@ pub fn step_copy_ignored(dry_run: bool,force: bool,) -> anyhow::Result<()> {- worktrunk::copy::lower_process_priority();+ worktrunk::priority::lower_current_process();let repo = Repository::current()?;let copy_ignored_config = resolve_copy_ignored_config(&repo)?;diff --git a/src/copy.rs b/src/copy.rsindex a5e4bf1ab..f481bc14f 100644--- a/src/copy.rs+++ b/src/copy.rs@@ -10,7 +10,7 @@//! (no recursion) then copied in a single parallel pass.//!//! Callers that want low-priority I/O (e.g. `step_copy_ignored`) should call-//! [`lower_process_priority`] before starting work.+//! [`crate::priority::lower_current_process`] before starting work.use std::fs;use std::io::ErrorKind;@@ -30,51 +30,6 @@ static COPY_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {.expect("failed to build copy thread pool")});-/// Lower the current process's scheduling and I/O priority so copy work-/// doesn't compete with interactive foreground work.-///-/// Shells out rather than calling `setpriority(2)` / `setiopolicy_np(3)`-/// directly to stay within the `forbid(unsafe_code)` lint. Non-fatal: if-/// the helper binary is missing or fails, copies proceed at normal priority.-///-/// - **macOS**: `taskpolicy -b -p <pid>` — enters `PRIO_DARWIN_BG`, which lowers-/// CPU scheduling and throttles disk + network I/O. `renice` alone only covers-/// CPU on Darwin, which misses the dominant cost of a reflink-fallback copy on-/// APFS.-/// - **Linux/other Unix**: `renice -n 19 -p <pid>` plus a best-effort-/// `ionice -c 3 -p <pid>` (idle class). `ionice` is optional — absence is-/// silently ignored.-pub fn lower_process_priority() {- #[cfg(unix)]- {- use std::process::{Command, Stdio};- let pid = std::process::id().to_string();- let quiet = |mut cmd: Command| {- let _ = cmd- .stdin(Stdio::null())- .stdout(Stdio::null())- .stderr(Stdio::null())- .status();- };-- #[cfg(target_os = "macos")]- {- let mut cmd = Command::new("/usr/sbin/taskpolicy");- cmd.args(["-b", "-p", &pid]);- quiet(cmd);- }- #[cfg(not(target_os = "macos"))]- {- let mut renice = Command::new("renice");- renice.args(["-n", "19", "-p", &pid]);- quiet(renice);- let mut ionice = Command::new("ionice");- ionice.args(["-c", "3", "-p", &pid]);- quiet(ionice);- }- }-}-/// Copy a single file or symlink, using reflink (COW) when possible.////// Detects symlinks via `symlink_metadata` on the source. Returns `true` ifdiff --git a/src/lib.rs b/src/lib.rsindex cdd259204..fc7a04fae 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -13,6 +13,7 @@ pub mod copy;pub mod docs;pub mod git;pub mod path;+pub mod priority;pub mod shell;pub mod shell_exec;pub mod styling;diff --git a/src/priority.rs b/src/priority.rsnew file mode 100644index 000000000..3b91fe25f--- /dev/null+++ b/src/priority.rs@@ -0,0 +1,189 @@+//! Lowering process priority for background work.+//!+//! Worktrunk runs a handful of operations — background `wt remove` cleanup,+//! stale-trash sweeps, and `step copy-ignored` — that are latency-insensitive+//! but can compete for CPU and disk bandwidth with the foreground session.+//! This module centralises the policy we apply to those operations and the+//! two forms in which we apply it.+//!+//! ## Policy+//!+//! - **macOS**: `taskpolicy -b` enters `PRIO_DARWIN_BG` — lowers CPU+//! scheduling *and* throttles disk + network I/O (see `setpriority(2)`).+//! `nice(1)`/`renice(8)` only touch CPU on Darwin, leaving the dominant+//! cost of a bulk `rm -rf` or reflink-fallback copy on APFS un-throttled.+//! - **Linux**: `nice -n 19` for CPU plus best-effort `ionice -c 3` (idle+//! class) for I/O. `ionice` is probed once via `which` — it ships in+//! `util-linux` on every mainstream distro and is enabled in Alpine's+//! busybox, so the fallback path is only hit on stripped-down environments+//! (distroless, minimal busybox, etc.).+//! - **Other Unix / Windows**: no-op.+//!+//! ## Why shell out?+//!+//! `setpriority(2)` (with `PRIO_DARWIN_BG` on Darwin) and `setiopolicy_np(3)`+//! would be more direct, but both are unsafe FFI and the crate has+//! `#![forbid(unsafe_code)]`.+//!+//! ## Forms+//!+//! - [`lower_current_process`] — self-lower by pid. Used when the *current*+//! worktrunk process (and any threads/children it later spawns) should run+//! at lower priority. The policy is inherited across `fork`/`exec`.+//! - [`command`] — build a [`Command`] that starts its child under the+//! policy, by wrapping it in `taskpolicy -b <cmd>` or+//! `ionice … nice … <cmd>`. Used for detached background spawns where we+//! want the wrapper tool itself to apply the policy and then exec the real+//! work.++use std::ffi::OsStr;+use std::process::Command;+#[cfg(unix)]+use std::process::Stdio;+#[cfg(all(unix, not(target_os = "macos")))]+use std::sync::LazyLock;++/// Whether `ionice` is available on PATH. Probed once per process so we don't+/// stat `$PATH` on every call.+#[cfg(all(unix, not(target_os = "macos")))]+static HAS_IONICE: LazyLock<bool> = LazyLock::new(|| which::which("ionice").is_ok());++/// Lower the current process's scheduling and I/O priority.+///+/// Non-fatal: if a helper binary is missing or fails, we proceed at normal+/// priority. No-op on non-Unix. See the [module docs](self) for the policy+/// applied on each platform.+pub fn lower_current_process() {+ #[cfg(unix)]+ {+ let pid = std::process::id().to_string();+ let quiet = |mut cmd: Command| {+ let _ = cmd+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status();+ };++ #[cfg(target_os = "macos")]+ {+ let mut cmd = Command::new("/usr/sbin/taskpolicy");+ cmd.args(["-b", "-p", &pid]);+ quiet(cmd);+ }+ #[cfg(not(target_os = "macos"))]+ {+ let mut renice = Command::new("renice");+ renice.args(["-n", "19", "-p", &pid]);+ quiet(renice);+ if *HAS_IONICE {+ let mut ionice = Command::new("ionice");+ ionice.args(["-c", "3", "-p", &pid]);+ quiet(ionice);+ }+ }+ }+}++/// Build a [`Command`] that runs `program` at lowered priority when `lower`+/// is set, or at normal priority when not.+///+/// The wrapper tool (`taskpolicy` on macOS, `ionice`/`nice` on Linux) applies+/// the policy and then execs `program`, so policy is inherited by the child+/// and its descendants. `taskpolicy` takes `program` as a positional arg (no+/// `--` separator accepted); safe because callers pass `sh` or an absolute+/// path. See the [module docs](self) for the full policy.+pub fn command(program: impl AsRef<OsStr>, lower: bool) -> Command {+ if !lower {+ return Command::new(program);+ }+ #[cfg(target_os = "macos")]+ {+ let mut cmd = Command::new("/usr/sbin/taskpolicy");+ cmd.arg("-b").arg(program);+ cmd+ }+ #[cfg(all(unix, not(target_os = "macos")))]+ {+ linux_low_priority_command(program.as_ref(), *HAS_IONICE)+ }+ #[cfg(not(unix))]+ {+ Command::new(program)+ }+}++/// Linux wrap: `ionice -c 3 -- nice -n 19 -- <program>` if `has_ionice`,+/// else `nice -n 19 -- <program>`. Extracted so both branches are testable+/// without depending on whether the runner has `ionice` installed.+#[cfg(all(unix, not(target_os = "macos")))]+fn linux_low_priority_command(program: &OsStr, has_ionice: bool) -> Command {+ if has_ionice {+ let mut cmd = Command::new("ionice");+ cmd.args(["-c", "3", "--", "nice", "-n", "19", "--"])+ .arg(program);+ cmd+ } else {+ let mut cmd = Command::new("nice");+ cmd.arg("-n").arg("19").arg("--").arg(program);+ cmd+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn args_of(cmd: &Command) -> Vec<&str> {+ cmd.get_args().map(|a| a.to_str().unwrap()).collect()+ }++ #[test]+ fn command_no_lower_returns_bare() {+ let cmd = command("echo", false);+ assert_eq!(cmd.get_program(), "echo");+ assert!(args_of(&cmd).is_empty());+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn command_lower_wraps_in_taskpolicy() {+ let cmd = command("echo", true);+ assert_eq!(cmd.get_program(), "/usr/sbin/taskpolicy");+ assert_eq!(args_of(&cmd), ["-b", "echo"]);+ }++ #[cfg(all(unix, not(target_os = "macos")))]+ #[test]+ fn linux_wrap_with_ionice() {+ let cmd = linux_low_priority_command(OsStr::new("echo"), true);+ assert_eq!(cmd.get_program(), "ionice");+ assert_eq!(+ args_of(&cmd),+ ["-c", "3", "--", "nice", "-n", "19", "--", "echo"]+ );+ }++ #[cfg(all(unix, not(target_os = "macos")))]+ #[test]+ fn linux_wrap_without_ionice() {+ let cmd = linux_low_priority_command(OsStr::new("echo"), false);+ assert_eq!(cmd.get_program(), "nice");+ assert_eq!(args_of(&cmd), ["-n", "19", "--", "echo"]);+ }++ #[cfg(not(unix))]+ #[test]+ fn command_lower_noop_on_non_unix() {+ let cmd = command("echo", true);+ assert_eq!(cmd.get_program(), "echo");+ assert!(args_of(&cmd).is_empty());+ }++ #[test]+ fn lower_current_process_does_not_panic() {+ // Exercises the shell-out path; failures are silently swallowed so+ // this is effectively a smoke test that the cfg arms compile and run.+ lower_current_process();+ }+}