lean_ctx_fs/env_lock.rs
1// SPDX-License-Identifier: Apache-2.0
2//! The process-wide test environment lock.
3//!
4//! `std::env::set_var` / `std::env::remove_var` became `unsafe` in Rust 2024
5//! because they are not thread-safe: a concurrent environment read from another
6//! thread is undefined behaviour. Every test that mutates the environment
7//! serializes through [`test_env_lock`], here and in the engine (which
8//! re-exports it as `core::data_dir::test_env_lock`), so there is exactly one
9//! lock per process. The mutation helpers `set_var` / `remove_var` exist
10//! only for tests (`cfg(test)` or the `test-support` feature).
11
12static TEST_ENV_MUTEX: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
13
14thread_local! {
15 /// Re-entrancy depth for the current thread. >0 means this thread already
16 /// holds the lock, so a nested acquire is a no-op bump instead of a
17 /// self-deadlock.
18 static TEST_ENV_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
19 /// The real guard, held only while depth transitions 0→…→0.
20 static TEST_ENV_HELD: std::cell::RefCell<Option<std::sync::MutexGuard<'static, ()>>> =
21 const { std::cell::RefCell::new(None) };
22}
23
24/// Reentrant test env lock. Serializes env-mutating tests across threads (the
25/// point — `std::env::set_var` is not thread-safe) while letting the SAME
26/// thread re-acquire without deadlocking. A test and a `setup()` helper (or
27/// `isolated_data_dir`) can both take it; only the outermost acquisition holds
28/// the underlying mutex, nested ones just bump a per-thread depth. Other
29/// threads still block, so cross-test serialization is unchanged.
30#[track_caller]
31pub fn test_env_lock() -> TestEnvGuard {
32 #[cfg(any(test, feature = "test-support"))]
33 refuse_in_batch();
34 let mutex = TEST_ENV_MUTEX.get_or_init(|| std::sync::Mutex::new(()));
35 TEST_ENV_DEPTH.with(|depth| {
36 if depth.get() == 0 {
37 let guard = mutex
38 .lock()
39 .unwrap_or_else(std::sync::PoisonError::into_inner);
40 TEST_ENV_HELD.with(|held| *held.borrow_mut() = Some(guard));
41 }
42 depth.set(depth.get() + 1);
43 });
44 TestEnvGuard {
45 _not_send_sync: std::marker::PhantomData,
46 }
47}
48
49/// Set by batched test runs (scripts/ci/test_batch.py, P5_TEST_BATCH) to a
50/// file path. A batch runs many tests in one process, so a test that changes
51/// the process environment would change it under every other test running
52/// there. With this variable set, [`test_env_lock`] appends one line
53/// `<thread name>\t<caller file:line>` to that file and panics before anything
54/// is changed; the batch runner then re-runs the test in a process of its own.
55/// libtest names each test's thread after the test, so on a test's own thread
56/// the first field is the test name. On a thread the test spawned it is that
57/// thread's name (or `<unnamed thread>`): no test name is available there, and
58/// the runner re-runs every test of that process instead. The runner re-runs a
59/// recorded test even when it passed, so a caught panic cannot hide a hit.
60#[cfg(any(test, feature = "test-support"))]
61pub const TEST_BATCH_ENV: &str = "LEAN_CTX_TEST_BATCH";
62
63#[cfg(any(test, feature = "test-support"))]
64#[track_caller]
65fn refuse_in_batch() {
66 let Some(log) = std::env::var_os(TEST_BATCH_ENV) else {
67 return;
68 };
69 let test = std::thread::current()
70 .name()
71 .unwrap_or("<unnamed thread>")
72 .to_owned();
73 let caller = std::panic::Location::caller();
74 if let Ok(mut file) = std::fs::OpenOptions::new()
75 .create(true)
76 .append(true)
77 .open(&log)
78 {
79 use std::io::Write as _;
80 // One write per line: `writeln!` on a File issues a write per
81 // formatted piece, and tests of the same batch interleave them into
82 // torn lines that name no test (shadow !534, job 60311).
83 let line = format!("{test}\t{}:{}\n", caller.file(), caller.line());
84 let _ = file.write_all(line.as_bytes());
85 }
86 panic!(
87 "{test}: takes test_env_lock, so it needs a process of its own; \
88 the batched run ({TEST_BATCH_ENV}) re-runs it alone"
89 );
90}
91
92/// Whether the current thread holds [`test_env_lock`]. The lock belongs to
93/// the thread that took it: a guard held by another thread does not count.
94#[cfg(any(test, feature = "test-support"))]
95pub fn holds_test_env_lock() -> bool {
96 TEST_ENV_DEPTH.with(|depth| depth.get() > 0)
97}
98
99/// RAII guard for [`test_env_lock`]. Dropping the outermost one releases the
100/// underlying mutex; nested guards just decrement the depth.
101///
102/// The lock and its depth live in the acquiring thread's own storage, so the
103/// guard must be dropped on that thread: it is neither `Send` nor `Sync`.
104/// Moved to another thread it would decrement that thread's depth and leave
105/// the lock held here.
106pub struct TestEnvGuard {
107 _not_send_sync: std::marker::PhantomData<*const ()>,
108}
109
110impl Drop for TestEnvGuard {
111 fn drop(&mut self) {
112 TEST_ENV_DEPTH.with(|depth| {
113 let next = depth.get().saturating_sub(1);
114 depth.set(next);
115 if next == 0 {
116 TEST_ENV_HELD.with(|held| *held.borrow_mut() = None);
117 }
118 });
119 }
120}
121
122/// Sets `key` to `value` in the process environment (test-only).
123#[cfg(any(test, feature = "test-support"))]
124pub fn set_var<K: AsRef<std::ffi::OsStr>, V: AsRef<std::ffi::OsStr>>(key: K, value: V) {
125 assert_lock_held();
126 // SAFETY: the assertion above holds, so this thread owns test_env_lock()
127 // and no other thread reads or writes the environment concurrently.
128 unsafe { std::env::set_var(key, value) };
129}
130
131/// Removes `key` from the process environment (test-only).
132#[cfg(any(test, feature = "test-support"))]
133pub fn remove_var<K: AsRef<std::ffi::OsStr>>(key: K) {
134 assert_lock_held();
135 // SAFETY: the assertion above holds, so this thread owns test_env_lock()
136 // and no other thread reads or writes the environment concurrently.
137 unsafe { std::env::remove_var(key) };
138}
139
140/// The precondition of the two functions above, checked in every build of the
141/// tests and before anything is changed. It does not take the lock itself:
142/// that would hide a caller whose lock does not span its whole mutation.
143#[cfg(any(test, feature = "test-support"))]
144fn assert_lock_held() {
145 assert!(
146 holds_test_env_lock(),
147 "test environment mutation requires the current thread to hold test_env_lock()"
148 );
149}
150
151#[cfg(test)]
152mod tests {
153 use super::{TEST_BATCH_ENV, test_env_lock};
154
155 const NAME: &str = "env_lock::tests::batch_tripwire_records_and_refuses";
156
157 /// Under a batched run the lock records the test and refuses before any
158 /// change. The test runs itself in a child process with the variable set
159 /// (the child takes the lock and must fail), so the parent never mutates
160 /// its own environment.
161 #[test]
162 fn batch_tripwire_records_and_refuses() {
163 if std::env::var_os(TEST_BATCH_ENV).is_some() {
164 let _guard = test_env_lock();
165 unreachable!("test_env_lock returned inside a batched run");
166 }
167 let dir = tempfile::tempdir().expect("tempdir");
168 let log = dir.path().join("env-lock.log");
169 let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
170 .args([NAME, "--exact", "--test-threads=1"])
171 .env(TEST_BATCH_ENV, &log)
172 .output()
173 .expect("run the child test");
174 assert!(!output.status.success(), "the child must fail");
175 let stdout = String::from_utf8_lossy(&output.stdout);
176 assert!(stdout.contains("needs a process of its own"), "{stdout}");
177 let recorded = std::fs::read_to_string(&log).expect("tripwire log");
178 let (thread, caller) = recorded
179 .trim_end()
180 .split_once('\t')
181 .expect("a `<thread>\\t<caller>` line");
182 assert!(
183 thread.ends_with("batch_tripwire_records_and_refuses"),
184 "libtest names the thread after the test: {recorded}"
185 );
186 assert!(caller.contains("env_lock.rs:"), "{recorded}");
187 }
188}