返回 CodeWhale
test_env_lock.rs
根目录 / crates / util / src / test_env_lock.rs
1 //! Process-wide test-environment barrier.
2
3 use std::ffi::{OsStr, OsString};
4 use std::sync::atomic::{AtomicBool, Ordering};
5 use std::sync::{Mutex, MutexGuard, OnceLock, TryLockError};
6 use std::thread::ThreadId;
7
8 fn env_lock() -> &'static Mutex<()> {
9 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
10 LOCK.get_or_init(|| Mutex::new(()))
11 }
12
13 /// Who currently counts as "inside" the process-wide env lock.
14 ///
15 /// The owner is the thread holding [`TestEnvLock`]. `adopted` holds helper
16 /// threads that owner explicitly enrolled with [`join_env_scope`] — see that
17 /// function for why a worker thread of the current test must not be treated as
18 /// a foreign reader.
19 #[derive(Default)]
20 struct EnvScope {
21 /// Bumped on every acquisition, so a ticket minted by an earlier test can
22 /// never enroll a thread into a later test's environment.
23 generation: u64,
24 owner: Option<ThreadId>,
25 adopted: Vec<ThreadId>,
26 }
27
28 fn env_scope() -> &'static Mutex<EnvScope> {
29 static SCOPE: OnceLock<Mutex<EnvScope>> = OnceLock::new();
30 SCOPE.get_or_init(|| Mutex::new(EnvScope::default()))
31 }
32
33 fn lock_env_scope() -> MutexGuard<'static, EnvScope> {
34 match env_scope().lock() {
35 Ok(scope) => scope,
36 Err(poisoned) => poisoned.into_inner(),
37 }
38 }
39
40 fn open_env_scope() {
41 let mut scope = lock_env_scope();
42 scope.generation = scope.generation.wrapping_add(1);
43 scope.owner = Some(std::thread::current().id());
44 scope.adopted.clear();
45 }
46
47 fn current_thread_owns_contended_env_lock() -> bool {
48 let scope = lock_env_scope();
49 let current = std::thread::current().id();
50 scope.owner == Some(current) || scope.adopted.contains(&current)
51 }
52
53 /// Proof that the calling thread belongs to a live [`lock_test_env`] scope, handed to
54 /// a worker thread so it can join that scope with [`join_env_scope`].
55 ///
56 /// Owners and adopted workers can pass the same live generation to child
57 /// workers. Foreign threads cannot mint a ticket for a test they did not join.
58 #[derive(Clone, Copy, Debug)]
59 pub struct EnvScopeTicket {
60 generation: u64,
61 }
62
63 impl EnvScopeTicket {
64 /// Which sealed environment this ticket authorizes. Callers that gate real
65 /// disk writes on a live scope key their bookkeeping by this value, so a
66 /// straggler from generation N can never be mistaken for work belonging to
67 /// generation N+1.
68 pub fn generation(&self) -> u64 {
69 self.generation
70 }
71 }
72
73 /// The generation of the env scope the calling thread is currently inside, as
74 /// owner or as a [`join_env_scope`]-adopted worker; `None` when the thread is a
75 /// foreign reader with no sealed environment of its own.
76 ///
77 /// This is the authorization primitive for anything that must only touch disk
78 /// on behalf of a test that actually sealed `HOME`. A process-global "writes
79 /// are enabled" flag cannot distinguish unrelated parallel tests.
80 pub fn current_env_scope_generation() -> Option<u64> {
81 let scope = lock_env_scope();
82 let current = std::thread::current().id();
83 if scope.owner == Some(current) || scope.adopted.contains(&current) {
84 Some(scope.generation)
85 } else {
86 None
87 }
88 }
89
90 pub fn env_scope_ticket() -> Option<EnvScopeTicket> {
91 let scope = lock_env_scope();
92 let current = std::thread::current().id();
93 (scope.owner == Some(current) || scope.adopted.contains(&current)).then_some(EnvScopeTicket {
94 generation: scope.generation,
95 })
96 }
97
98 /// Enroll the calling thread in the ticket's env scope for as long as the
99 /// returned guard lives.
100 ///
101 /// [`with_test_env_lock`] stops a foreign test from resolving another test's
102 /// temporary `HOME`. A helper thread doing work for the sealing test must see
103 /// that same environment without blocking on the mutex its owner holds.
104 pub fn join_env_scope(ticket: Option<EnvScopeTicket>) -> Option<EnvScopeMembership> {
105 let ticket = ticket?;
106 let mut scope = lock_env_scope();
107 if scope.owner.is_none() || scope.generation != ticket.generation {
108 return None;
109 }
110 let thread = std::thread::current().id();
111 if !scope.adopted.contains(&thread) {
112 scope.adopted.push(thread);
113 }
114 Some(EnvScopeMembership {
115 generation: ticket.generation,
116 thread,
117 })
118 }
119
120 pub struct EnvScopeMembership {
121 generation: u64,
122 thread: ThreadId,
123 }
124
125 impl Drop for EnvScopeMembership {
126 fn drop(&mut self) {
127 let mut scope = lock_env_scope();
128 if scope.generation == self.generation {
129 scope.adopted.retain(|thread| *thread != self.thread);
130 }
131 }
132 }
133
134 /// Owned process-wide test-environment lock.
135 ///
136 /// Clearing the owner before the underlying mutex unlocks keeps re-entrant
137 /// reader detection exact. Closing the scope also evicts adopted workers, so
138 /// enrollment cannot outlive the test that granted it.
139 pub struct TestEnvLock {
140 _guard: MutexGuard<'static, ()>,
141 }
142
143 impl Drop for TestEnvLock {
144 fn drop(&mut self) {
145 let mut scope = lock_env_scope();
146 if scope.owner == Some(std::thread::current().id()) {
147 scope.owner = None;
148 scope.adopted.clear();
149 }
150 }
151 }
152
153 /// Acquire the process-wide env-var mutex.
154 ///
155 /// If a prior test panicked while holding the lock, recover the guard instead
156 /// of cascading failures across unrelated tests.
157 pub fn lock_test_env() -> TestEnvLock {
158 let guard = match env_lock().lock() {
159 Ok(guard) => guard,
160 Err(poisoned) => poisoned.into_inner(),
161 };
162 open_env_scope();
163 TestEnvLock { _guard: guard }
164 }
165
166 /// Read process-global test environment while respecting [`lock_test_env`].
167 ///
168 /// The owner check makes the barrier re-entrant for a test that reads its own
169 /// guarded override.
170 pub fn with_test_env_lock<T>(read: impl FnOnce() -> T) -> T {
171 if current_thread_owns_contended_env_lock() {
172 return read();
173 }
174
175 let _guard = lock_test_env();
176 read()
177 }
178
179 /// [`with_test_env_lock`] for readers that run inside a `LazyLock`/`OnceLock`
180 /// initializer: takes the barrier when it is free, and reads *without* it
181 /// rather than waiting when another thread holds it.
182 ///
183 /// Blocking is not an option there. The initializer's own lock is held for the
184 /// duration, so a second thread that already owns the env barrier and then
185 /// touches the same lazy value deadlocks against this one: A waits for the
186 /// initializer, B (this thread) waits for A's barrier. Both threads wedge, and
187 /// libtest has no per-test timeout, so the whole test binary hangs instead of
188 /// failing — which is how a single wedged run burns an entire CI job.
189 ///
190 /// The trade is deliberate and small: an uncontended read is still fully
191 /// serialized, and a contended one reads a variable mid-mutation at worst.
192 /// Callers must therefore only use this for values whose staleness is
193 /// tolerable, never to gate a disk write.
194 pub fn with_test_env_lock_if_uncontended<T>(read: impl FnOnce() -> T) -> T {
195 if current_thread_owns_contended_env_lock() {
196 return read();
197 }
198
199 match env_lock().try_lock() {
200 Ok(_guard) => read(),
201 Err(TryLockError::Poisoned(poisoned)) => {
202 let _guard = poisoned.into_inner();
203 read()
204 }
205 Err(TryLockError::WouldBlock) => read(),
206 }
207 }
208
209 pub fn current_thread_holds_test_env_lock() -> bool {
210 match env_lock().try_lock() {
211 Ok(guard) => {
212 drop(guard);
213 false
214 }
215 Err(TryLockError::Poisoned(poisoned)) => {
216 drop(poisoned.into_inner());
217 false
218 }
219 Err(TryLockError::WouldBlock) => current_thread_owns_contended_env_lock(),
220 }
221 }
222
223 /// Restore one environment variable when dropped.
224 ///
225 /// Callers that mutate process-global environment variables must hold
226 /// [`lock_test_env`] until after this guard is dropped.
227 ///
228 /// Every live guard is also recorded in the guarded-key registry, so path
229 /// resolution can distinguish a test that deliberately redirected `HOME`
230 /// from one that merely holds the lock to serialize unrelated env access.
231 pub struct EnvVarGuard {
232 key: &'static str,
233 previous: Option<OsString>,
234 }
235
236 fn guarded_env_keys() -> &'static Mutex<std::collections::HashMap<&'static str, usize>> {
237 static KEYS: OnceLock<Mutex<std::collections::HashMap<&'static str, usize>>> = OnceLock::new();
238 KEYS.get_or_init(|| Mutex::new(std::collections::HashMap::new()))
239 }
240
241 pub fn register_guarded_env_key(key: &'static str) {
242 let mut keys = match guarded_env_keys().lock() {
243 Ok(keys) => keys,
244 Err(poisoned) => poisoned.into_inner(),
245 };
246 *keys.entry(key).or_insert(0) += 1;
247 }
248
249 pub fn unregister_guarded_env_key(key: &'static str) {
250 let mut keys = match guarded_env_keys().lock() {
251 Ok(keys) => keys,
252 Err(poisoned) => poisoned.into_inner(),
253 };
254 if let Some(count) = keys.get_mut(key) {
255 *count -= 1;
256 if *count == 0 {
257 keys.remove(key);
258 }
259 }
260 }
261
262 static STATE_FROM_ENVIRONMENT: AtomicBool = AtomicBool::new(false);
263
264 pub fn resolve_state_from_environment() {
265 STATE_FROM_ENVIRONMENT.store(true, Ordering::SeqCst);
266 }
267
268 pub fn state_from_environment() -> bool {
269 STATE_FROM_ENVIRONMENT.load(Ordering::SeqCst)
270 }
271
272 /// Whether some live [`EnvVarGuard`] currently covers `key`.
273 pub fn env_var_currently_guarded(key: &str) -> bool {
274 if state_from_environment() {
275 return true;
276 }
277 match guarded_env_keys().lock() {
278 Ok(keys) => keys.contains_key(key),
279 Err(poisoned) => poisoned.into_inner().contains_key(key),
280 }
281 }
282
283 impl EnvVarGuard {
284 pub fn set(key: &'static str, value: impl AsRef<OsStr>) -> Self {
285 debug_assert!(
286 current_thread_holds_test_env_lock(),
287 "EnvVarGuard::set({key}) requires lock_test_env()"
288 );
289 let previous = std::env::var_os(key);
290 // SAFETY: callers hold the process-wide test env mutex.
291 unsafe { std::env::set_var(key, value) };
292 register_guarded_env_key(key);
293 Self { key, previous }
294 }
295
296 pub fn remove(key: &'static str) -> Self {
297 debug_assert!(
298 current_thread_holds_test_env_lock(),
299 "EnvVarGuard::remove({key}) requires lock_test_env()"
300 );
301 let previous = std::env::var_os(key);
302 // SAFETY: callers hold the process-wide test env mutex.
303 unsafe { std::env::remove_var(key) };
304 register_guarded_env_key(key);
305 Self { key, previous }
306 }
307 }
308
309 impl Drop for EnvVarGuard {
310 fn drop(&mut self) {
311 // Withdraw the claim *before* restoring the value: a reader on another
312 // thread that still saw the key as guarded would otherwise follow the
313 // restored — ambient, possibly real — path for the instant in between.
314 unregister_guarded_env_key(self.key);
315 // SAFETY: callers hold the process-wide test env mutex until after this
316 // guard is dropped.
317 unsafe {
318 if let Some(value) = self.previous.take() {
319 std::env::set_var(self.key, value);
320 } else {
321 std::env::remove_var(self.key);
322 }
323 }
324 }
325 }
326
327 #[cfg(test)]
328 mod tests {
329 use super::{lock_test_env, with_test_env_lock_if_uncontended};
330 use std::sync::mpsc;
331 use std::time::{Duration, Instant};
332
333 #[test]
334 fn adopted_worker_can_pass_only_its_live_environment_generation() {
335 let owner = lock_test_env();
336 let ticket = super::env_scope_ticket().unwrap();
337 let nested = std::thread::spawn(move || {
338 assert!(
339 super::env_scope_ticket().is_none(),
340 "foreign thread has no authority"
341 );
342 let _membership = super::join_env_scope(Some(ticket)).unwrap();
343 let child_ticket =
344 super::env_scope_ticket().expect("adopted worker can enroll its child");
345 std::thread::spawn(move || {
346 let _membership = super::join_env_scope(Some(child_ticket)).unwrap();
347 assert_eq!(
348 super::current_env_scope_generation(),
349 Some(child_ticket.generation())
350 );
351 assert_eq!(super::with_test_env_lock(|| 7), 7);
352 child_ticket
353 })
354 .join()
355 .unwrap()
356 })
357 .join()
358 .unwrap();
359 drop(owner);
360 let _next = lock_test_env();
361 assert!(
362 super::join_env_scope(Some(nested)).is_none(),
363 "old generation cannot join the next test"
364 );
365 }
366
367 /// The lock-order inversion this helper exists to break.
368 ///
369 /// A reader running inside a `LazyLock`/`OnceLock` initializer must not wait
370 /// for the env barrier: the thread holding the barrier may itself be waiting
371 /// on that initializer. Both threads then wedge, and libtest has no per-test
372 /// timeout, so the entire test binary hangs — reproduced locally as
373 /// `cargo test -p codewhale-tui --lib -- shell` never returning.
374 #[test]
375 fn uncontended_read_returns_while_another_thread_holds_the_barrier() {
376 let (held_tx, held_rx) = mpsc::channel();
377 let (release_tx, release_rx) = mpsc::channel::<()>();
378 let holder = std::thread::spawn(move || {
379 let _guard = lock_test_env();
380 held_tx.send(()).expect("announce that the barrier is held");
381 // Outlive the assertion below without depending on timing.
382 let _ = release_rx.recv_timeout(Duration::from_secs(30));
383 });
384 held_rx
385 .recv_timeout(Duration::from_secs(10))
386 .expect("holder thread must take the barrier");
387
388 let start = Instant::now();
389 let value = with_test_env_lock_if_uncontended(|| 7);
390 let elapsed = start.elapsed();
391
392 release_tx.send(()).ok();
393 holder.join().expect("holder thread");
394
395 assert_eq!(value, 7, "the read still runs, just unsynchronized");
396 assert!(
397 elapsed < Duration::from_secs(1),
398 "a contended read must not block; waited {elapsed:?}"
399 );
400 }
401 }
402
402 lines RUST