Skip to content

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

fix: add file locking to prevent config race conditions (#693)

Maximilian Roos0308cf5a28d6
diff --git a/Cargo.lock b/Cargo.lock
index dcd07e922..5ecb8d373 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -916,6 +916,16 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+[[package]]
+name = "fs2"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
+dependencies = [
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "futures-core"
version = "0.3.31"
@@ -3043,6 +3053,7 @@ dependencies = [
"dunce",
"env_logger",
"etcetera",
+ "fs2",
"home",
"ignore",
"indexmap",
diff --git a/Cargo.toml b/Cargo.toml
index 97f3f06bc..0bcfbe02e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -117,6 +117,7 @@ regex = "1.12"
ignore = "0.4"
reflink-copy = "0.1"
dashmap = "6.1.0"
+fs2 = "0.4.3"
[target.'cfg(unix)'.dependencies]
skim = "0.20"
diff --git a/src/config/user.rs b/src/config/user.rs
index 0ab1f7deb..b1b1297b3 100644
--- a/src/config/user.rs
+++ b/src/config/user.rs
@@ -3,12 +3,40 @@
//! Personal preferences and per-project approved commands, not checked into git.
use config::{Case, Config, ConfigError, File};
+use fs2::FileExt;
use serde::{Deserialize, Deserializer, Serialize};
use std::path::PathBuf;
use std::sync::OnceLock;
use super::HooksConfig;
+/// Acquire an exclusive lock on the config file for read-modify-write operations.
+///
+/// Uses a `.lock` file alongside the config file to coordinate between processes.
+/// The lock is released when the returned guard is dropped.
+fn acquire_config_lock(config_path: &std::path::Path) -> Result<std::fs::File, ConfigError> {
+ let lock_path = config_path.with_extension("toml.lock");
+
+ // Create parent directory if needed
+ if let Some(parent) = lock_path.parent() {
+ std::fs::create_dir_all(parent)
+ .map_err(|e| ConfigError::Message(format!("Failed to create config directory: {e}")))?;
+ }
+
+ let file = std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&lock_path)
+ .map_err(|e| ConfigError::Message(format!("Failed to open lock file: {e}")))?;
+
+ file.lock_exclusive()
+ .map_err(|e| ConfigError::Message(format!("Failed to acquire config lock: {e}")))?;
+
+ Ok(file)
+}
+
/// Deserialize a Vec<String> that can also accept a single String
/// This enables setting array config fields via environment variables
fn deserialize_string_or_vec<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
@@ -444,6 +472,34 @@ impl WorktrunkConfig {
expand_template(&self.worktree_path(), &vars, false, repo)
}
+ /// Execute a mutation under an exclusive file lock.
+ ///
+ /// Acquires lock, reloads from disk, calls the mutator, and saves if mutator returns true.
+ fn with_locked_mutation<F>(
+ &mut self,
+ config_path: Option<&std::path::Path>,
+ mutate: F,
+ ) -> Result<(), ConfigError>
+ where
+ F: FnOnce(&mut Self) -> bool,
+ {
+ let path = match config_path {
+ Some(p) => p.to_path_buf(),
+ None => get_config_path().ok_or_else(|| {
+ ConfigError::Message(
+ "Cannot determine config directory. Set $HOME or $XDG_CONFIG_HOME".to_string(),
+ )
+ })?,
+ };
+ let _lock = acquire_config_lock(&path)?;
+ self.reload_projects_from(config_path)?;
+
+ if mutate(self) {
+ self.save_impl(config_path)?;
+ }
+ Ok(())
+ }
+
/// Check if a command is approved for the given project.
///
/// Normalizes both the stored approvals and the incoming command to canonical
@@ -464,7 +520,7 @@ impl WorktrunkConfig {
/// Add an approved command and save to config file.
///
- /// Reloads from disk before modifying to reduce race conditions from concurrent processes.
+ /// Acquires lock, reloads from disk, adds command if not present, and saves.
/// Pass `None` for default config path, or `Some(path)` for testing.
pub fn approve_command(
&mut self,
@@ -472,20 +528,18 @@ impl WorktrunkConfig {
command: String,
config_path: Option<&std::path::Path>,
) -> Result<(), ConfigError> {
- // Reload from disk first to get fresh state (fixes race condition where
- // concurrent approvals would overwrite each other)
- self.reload_projects_from(config_path)?;
-
- if self.is_command_approved(&project, &command) {
- return Ok(());
- }
-
- self.projects
- .entry(project)
- .or_default()
- .approved_commands
- .push(command);
- self.save_impl(config_path)
+ self.with_locked_mutation(config_path, |config| {
+ if config.is_command_approved(&project, &command) {
+ return false;
+ }
+ config
+ .projects
+ .entry(project)
+ .or_default()
+ .approved_commands
+ .push(command);
+ true
+ })
}
/// Reload only the projects section from disk, preserving other in-memory state
@@ -534,7 +588,7 @@ impl WorktrunkConfig {
/// Revoke an approved command and save to config file.
///
- /// Reloads from disk before modifying to reduce race conditions from concurrent processes.
+ /// Acquires lock, reloads from disk, removes command if present, and saves.
/// Pass `None` for default config path, or `Some(path)` for testing.
pub fn revoke_command(
&mut self,
@@ -542,57 +596,53 @@ impl WorktrunkConfig {
command: &str,
config_path: Option<&std::path::Path>,
) -> Result<(), ConfigError> {
- // Reload from disk first to get fresh state (fixes race condition)
- self.reload_projects_from(config_path)?;
-
- if let Some(project_config) = self.projects.get_mut(project) {
+ let project = project.to_string();
+ let command = command.to_string();
+ self.with_locked_mutation(config_path, |config| {
+ let Some(project_config) = config.projects.get_mut(&project) else {
+ return false;
+ };
let len_before = project_config.approved_commands.len();
- project_config.approved_commands.retain(|c| c != command);
+ project_config.approved_commands.retain(|c| c != &command);
let changed = len_before != project_config.approved_commands.len();
if project_config.approved_commands.is_empty() {
- self.projects.remove(project);
- }
-
- if changed {
- self.save_impl(config_path)?;
+ config.projects.remove(&project);
}
- }
- Ok(())
+ changed
+ })
}
/// Remove all approvals for a project and save to config file.
///
- /// Reloads from disk before modifying to reduce race conditions from concurrent processes.
+ /// Acquires lock, reloads from disk, removes project if present, and saves.
/// Pass `None` for default config path, or `Some(path)` for testing.
pub fn revoke_project(
&mut self,
project: &str,
config_path: Option<&std::path::Path>,
) -> Result<(), ConfigError> {
- // Reload from disk first to get fresh state (fixes race condition)
- self.reload_projects_from(config_path)?;
-
- if self.projects.remove(project).is_some() {
- self.save_impl(config_path)?;
- }
- Ok(())
+ let project = project.to_string();
+ self.with_locked_mutation(config_path, |config| {
+ config.projects.remove(&project).is_some()
+ })
}
/// Set `skip-shell-integration-prompt = true` and save.
///
+ /// Acquires lock, reloads from disk, sets flag if not already set, and saves.
/// Pass `None` for default config path, or `Some(path)` for testing.
pub fn set_skip_shell_integration_prompt(
&mut self,
config_path: Option<&std::path::Path>,
) -> Result<(), ConfigError> {
- if self.skip_shell_integration_prompt {
- return Ok(());
- }
- // Reload from disk first to avoid clobbering concurrent changes
- self.reload_projects_from(config_path)?;
- self.skip_shell_integration_prompt = true;
- self.save_impl(config_path)
+ self.with_locked_mutation(config_path, |config| {
+ if config.skip_shell_integration_prompt {
+ return false;
+ }
+ config.skip_shell_integration_prompt = true;
+ true
+ })
}
/// Save the current configuration to the default config file location
diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rs
index 16755a0e0..169357d32 100644
--- a/tests/integration_tests/approval_save.rs
+++ b/tests/integration_tests/approval_save.rs
@@ -500,6 +500,65 @@ fn test_concurrent_approve_different_projects() {
);
}
+/// Test true concurrent access from multiple threads.
+///
+/// Unlike the sequential tests above, this spawns multiple threads that race
+/// to approve commands simultaneously. With file locking, all approvals should
+/// be preserved.
+#[test]
+fn test_truly_concurrent_approve_with_threads() {
+ use std::sync::{Arc, Barrier};
+ use std::thread;
+
+ let temp_dir = TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("config.toml");
+
+ // Create 10 threads that will all try to approve at the same time
+ let num_threads = 10;
+ let barrier = Arc::new(Barrier::new(num_threads));
+ let config_path = Arc::new(config_path);
+
+ let handles: Vec<_> = (0..num_threads)
+ .map(|i| {
+ let barrier = Arc::clone(&barrier);
+ let config_path = Arc::clone(&config_path);
+
+ thread::spawn(move || {
+ let mut config = WorktrunkConfig::default();
+
+ // Wait for all threads to be ready
+ barrier.wait();
+
+ // All threads try to approve at the same time
+ config
+ .approve_command(
+ "github.com/user/repo".to_string(),
+ format!("command_{i}"),
+ Some(&config_path),
+ )
+ .unwrap();
+ })
+ })
+ .collect();
+
+ // Wait for all threads to complete
+ for handle in handles {
+ handle.join().unwrap();
+ }
+
+ // Read the final state from disk
+ let toml_content = fs::read_to_string(&*config_path).unwrap();
+
+ // All 10 approvals should be preserved
+ for i in 0..num_threads {
+ assert!(
+ toml_content.contains(&format!("command_{i}")),
+ "command_{i} should be preserved. With file locking, no approvals should be lost.\n\
+ Content:\n{toml_content}"
+ );
+ }
+}
+
///
/// This tests the lower-level `approve_command()` method fails when permissions
/// are denied. The higher-level `approve_command_batch()` catches this error and