Skip to main content

lean_ctx_ext/core/
path_locks.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Process-wide per-path advisory locks.
3//!
4//! These in-process mutexes serialize concurrent operations on the *same* file
5//! path while letting operations on *different* paths run fully in parallel.
6//!
7//! Why this exists: tools like `ctx_read` and `ctx_edit` would otherwise contend
8//! on the single global cache write-lock for the entire duration of their disk
9//! I/O. When several agents (or sub-agents) hammer files concurrently, that
10//! global lock becomes a bottleneck and edits can time out waiting for it (see
11//! issue #320). A per-path lock keeps the contention scoped to the one file that
12//! actually needs serialization, so unrelated reads/edits never block each other.
13//!
14//! Lock ordering (see `LOCK_ORDERING.md`, L17): the inner registry mutex is held
15//! only long enough to clone the per-path `Arc<Mutex<()>>`, then released before
16//! the per-path lock itself is acquired. Never hold the registry mutex across the
17//! per-path lock, and never acquire a per-path lock while holding the global
18//! cache write-lock.
19
20use std::collections::HashMap;
21use std::sync::{Arc, Mutex};
22
23/// Upper bound on retained lock entries before we garbage-collect unused ones.
24const MAX_ENTRIES: usize = 500;
25
26/// Returns the shared advisory lock for `path`, creating it on first use.
27///
28/// The same path always yields the same `Arc<Mutex<()>>`, so callers across
29/// threads serialize on it. Different paths yield independent mutexes.
30pub fn per_file_lock(path: &str) -> Arc<Mutex<()>> {
31    static FILE_LOCKS: std::sync::OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> =
32        std::sync::OnceLock::new();
33    let map = FILE_LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
34    let mut map = map.lock().unwrap_or_else(|poisoned| {
35        tracing::warn!("path_locks registry poisoned; recovering");
36        poisoned.into_inner()
37    });
38
39    // Bounded growth: drop entries no one else is holding a reference to. The
40    // `> 1` check keeps any lock that is currently in use by another caller.
41    if map.len() > MAX_ENTRIES {
42        map.retain(|_, v| Arc::strong_count(v) > 1);
43    }
44
45    map.entry(path.to_string())
46        .or_insert_with(|| Arc::new(Mutex::new(())))
47        .clone()
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53    use std::sync::Barrier;
54    use std::sync::atomic::{AtomicUsize, Ordering};
55
56    #[test]
57    fn same_path_returns_same_mutex() {
58        let a1 = per_file_lock("/tmp/path_locks_same.txt");
59        let a2 = per_file_lock("/tmp/path_locks_same.txt");
60        assert!(Arc::ptr_eq(&a1, &a2));
61    }
62
63    #[test]
64    fn different_paths_return_different_mutexes() {
65        let a = per_file_lock("/tmp/path_locks_a.txt");
66        let b = per_file_lock("/tmp/path_locks_b.txt");
67        assert!(!Arc::ptr_eq(&a, &b));
68    }
69
70    #[test]
71    fn serializes_concurrent_access_to_same_path() {
72        let counter = Arc::new(AtomicUsize::new(0));
73        let max_concurrent = Arc::new(AtomicUsize::new(0));
74        let barrier = Arc::new(Barrier::new(8));
75        let path = "/tmp/path_locks_serialize.txt";
76        let mut handles = Vec::new();
77        for _ in 0..8 {
78            let counter = Arc::clone(&counter);
79            let max_concurrent = Arc::clone(&max_concurrent);
80            let barrier = Arc::clone(&barrier);
81            handles.push(std::thread::spawn(move || {
82                barrier.wait();
83                let lock = per_file_lock(path);
84                let _guard = lock
85                    .lock()
86                    .unwrap_or_else(std::sync::PoisonError::into_inner);
87                let active = counter.fetch_add(1, Ordering::SeqCst) + 1;
88                max_concurrent.fetch_max(active, Ordering::SeqCst);
89                std::thread::sleep(std::time::Duration::from_millis(5));
90                counter.fetch_sub(1, Ordering::SeqCst);
91            }));
92        }
93        for h in handles {
94            h.join().unwrap();
95        }
96        assert_eq!(
97            max_concurrent.load(Ordering::SeqCst),
98            1,
99            "per-file lock must serialize same-path access"
100        );
101    }
102
103    #[test]
104    fn allows_parallel_access_to_different_paths() {
105        let counter = Arc::new(AtomicUsize::new(0));
106        let max_concurrent = Arc::new(AtomicUsize::new(0));
107        let barrier = Arc::new(Barrier::new(8));
108        let mut handles = Vec::new();
109        for i in 0..8 {
110            let counter = Arc::clone(&counter);
111            let max_concurrent = Arc::clone(&max_concurrent);
112            let barrier = Arc::clone(&barrier);
113            handles.push(std::thread::spawn(move || {
114                let path = format!("/tmp/path_locks_parallel_{i}.txt");
115                barrier.wait();
116                let lock = per_file_lock(&path);
117                let _guard = lock
118                    .lock()
119                    .unwrap_or_else(std::sync::PoisonError::into_inner);
120                let active = counter.fetch_add(1, Ordering::SeqCst) + 1;
121                max_concurrent.fetch_max(active, Ordering::SeqCst);
122                std::thread::sleep(std::time::Duration::from_millis(5));
123                counter.fetch_sub(1, Ordering::SeqCst);
124            }));
125        }
126        for h in handles {
127            h.join().unwrap();
128        }
129        assert!(
130            max_concurrent.load(Ordering::SeqCst) > 1,
131            "different paths must be allowed to run in parallel"
132        );
133    }
134}