vtcode_commons/sync.rs
1//! Poison-tolerant locking for `std::sync::Mutex`.
2//!
3//! `std::sync::Mutex` poisoning is advisory bookkeeping: a guard dropped while
4//! panicking flags the mutex, but the guarded value is often still consistent.
5//! Panicking on every subsequent `lock()` turns one localized failure into a
6//! process-wide cascade, especially for process-global state and cleanup paths.
7//!
8//! VT Code's policy:
9//! - short synchronous critical sections use `parking_lot::Mutex` (no poison);
10//! - where `std::sync::Mutex` is required, use [`lock_or_recover`] so poison is
11//! recovered instead of propagated;
12//! - callers with a genuine mid-critical-section invariant should model poison
13//! explicitly rather than relying on the standard library's boolean flag.
14
15use std::sync::{Mutex, MutexGuard, PoisonError};
16
17/// Lock `mutex`, returning the guard even if a previous holder panicked.
18///
19/// Accepts `&Mutex<T>` and, through deref coercion, `&Arc<Mutex<T>>`. On stable
20/// Rust this is the non-panicking alternative to `mutex.lock().unwrap()`;
21/// panic-freedom matters most in globals, shutdown, and panic-hook paths where
22/// a second panic aborts the process.
23#[inline]
24pub fn lock_or_recover<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
25 mutex.lock().unwrap_or_else(PoisonError::into_inner)
26}
27
28#[cfg(test)]
29mod tests {
30 use super::lock_or_recover;
31 use std::sync::{Arc, Mutex};
32
33 #[test]
34 fn lock_or_recover_returns_the_guard_for_a_healthy_mutex() {
35 let mutex = Mutex::new(7);
36 assert_eq!(*lock_or_recover(&mutex), 7);
37 assert!(!mutex.is_poisoned());
38 }
39
40 #[test]
41 fn lock_or_recover_recovers_and_allows_mutation_after_poison() {
42 let mutex = Arc::new(Mutex::new(vec![1, 2, 3]));
43 let poisoner = Arc::clone(&mutex);
44 let result = std::thread::spawn(move || {
45 let _guard = poisoner.lock().expect("poisoner acquires the lock");
46 panic!("deliberate panic while holding the lock");
47 })
48 .join();
49 assert!(result.is_err(), "the helper thread must panic while locked");
50 assert!(mutex.is_poisoned());
51
52 {
53 let mut guard = lock_or_recover(&mutex);
54 guard.push(4);
55 }
56 assert_eq!(*lock_or_recover(&mutex), vec![1, 2, 3, 4]);
57 }
58}