返回 CodeWhale
test_support.rs
根目录 / crates / runtime / src / test_support.rs
1 //! Shared test-only helpers.
2
3 use std::path::{Path, PathBuf};
4 use std::sync::{Mutex, OnceLock};
5 use std::time::{SystemTime, UNIX_EPOCH};
6
7 pub use codewhale_util::test_env_lock::{
8 EnvScopeMembership, EnvScopeTicket, EnvVarGuard, TestEnvLock, current_env_scope_generation,
9 current_thread_holds_test_env_lock, env_scope_ticket, env_var_currently_guarded,
10 join_env_scope, lock_test_env, register_guarded_env_key, resolve_state_from_environment,
11 state_from_environment, unregister_guarded_env_key, with_test_env_lock,
12 with_test_env_lock_if_uncontended,
13 };
14
15 /// Mark `workspace` trusted in the test's config, creating it first so the
16 /// trust key is the canonical path. Repository-supplied commands and skills
17 /// load only in a trusted workspace.
18 pub fn trust_workspace(workspace: &Path) {
19 std::fs::create_dir_all(workspace).expect("create test workspace");
20 crate::config::save_workspace_trust(workspace).expect("trust test workspace");
21 }
22
23 /// Process-wide state root for unit tests that do not intentionally provide an
24 /// explicit config/settings path.
25 ///
26 /// The production fallback is the user's real home. That is useful at runtime
27 /// and unsafe in a parallel test binary: an unguarded save can otherwise read
28 /// or overwrite the developer's config. Tests that exercise path precedence
29 /// still hold [`lock_test_env`] and provide explicit temporary environment
30 /// values; every other test is confined here — enforced by
31 /// [`guarded_environment_provides_state_paths`], not assumed.
32 pub fn isolated_test_state_root() -> &'static Path {
33 ISOLATED_TEST_STATE_ROOT.get_or_init(|| {
34 let nonce = SystemTime::now()
35 .duration_since(UNIX_EPOCH)
36 .unwrap_or_default()
37 .as_nanos();
38 let root = std::env::temp_dir().join(format!(
39 "codewhale-tui-test-state-{}-{nonce}",
40 std::process::id()
41 ));
42 std::fs::create_dir_all(&root).unwrap_or_else(|error| {
43 panic!(
44 "failed to create isolated unit-test state root {}: {error}",
45 root.display()
46 )
47 });
48 remove_test_roots_at_exit();
49 // Match resolvers that canonicalize their root (macOS aliases /var to
50 // /private/var). Every fence must name the same physical test store.
51 root.canonicalize().expect("canonical test state root")
52 })
53 }
54
55 pub fn test_scratch_dir(prefix: &str) -> PathBuf {
56 let root = TEST_SCRATCH_ROOT.get_or_init(|| {
57 let nonce = SystemTime::now()
58 .duration_since(UNIX_EPOCH)
59 .unwrap_or_default()
60 .as_nanos();
61 let root = std::env::temp_dir().join(format!(
62 "codewhale-test-scratch-{}-{nonce}",
63 std::process::id()
64 ));
65 std::fs::create_dir_all(&root).unwrap_or_else(|error| {
66 panic!(
67 "failed to create unit-test scratch root {}: {error}",
68 root.display()
69 )
70 });
71 remove_test_roots_at_exit();
72 root
73 });
74 root.join(format!("{prefix}-{}", uuid::Uuid::new_v4()))
75 }
76
77 static ISOLATED_TEST_STATE_ROOT: OnceLock<PathBuf> = OnceLock::new();
78 static TEST_SCRATCH_ROOT: OnceLock<PathBuf> = OnceLock::new();
79
80 fn remove_test_roots_at_exit() {
81 unsafe extern "C" {
82 fn atexit(callback: extern "C" fn()) -> std::ffi::c_int;
83 }
84 extern "C" fn remove_roots() {
85 for root in [ISOLATED_TEST_STATE_ROOT.get(), TEST_SCRATCH_ROOT.get()]
86 .into_iter()
87 .flatten()
88 {
89 remove_test_root(root);
90 }
91 }
92 static REGISTERED: std::sync::Once = std::sync::Once::new();
93 REGISTERED.call_once(|| unsafe {
94 atexit(remove_roots);
95 });
96 }
97
98 fn remove_test_root(root: &Path) {
99 if std::fs::remove_dir_all(root).is_err() {
100 #[cfg(unix)]
101 make_directories_writable(root);
102 let _ = std::fs::remove_dir_all(root);
103 }
104 }
105
106 #[cfg(unix)]
107 fn make_directories_writable(path: &Path) {
108 use std::os::unix::fs::PermissionsExt;
109 let Ok(metadata) = std::fs::symlink_metadata(path) else {
110 return;
111 };
112 if !metadata.is_dir() {
113 return;
114 }
115 let mode = metadata.permissions().mode() | 0o700;
116 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
117 if let Ok(entries) = std::fs::read_dir(path) {
118 for entry in entries.flatten() {
119 make_directories_writable(&entry.path());
120 }
121 }
122 }
123
124 /// Where the calling test's state should live when it has not sealed the
125 /// environment itself.
126 ///
127 /// Two different callers land here. A test that never took [`lock_test_env`]
128 /// gets the shared root, exactly as before — those tests already coexist there
129 /// under [`with_test_state_io_lock`]. A test that *holds* the lock but sealed
130 /// nothing gets a private directory instead: before #5359 it resolved the
131 /// developer's real home, so it has never shared the process root, and several
132 /// such tests run full settings transactions. Adding that traffic to the shared
133 /// root pushed the transaction lock past its deadline and hung unrelated
134 /// `config_command_*` tests. Keep them isolated from the developer *and* from
135 /// each other.
136 pub fn unsealed_test_state_root() -> PathBuf {
137 let shared = isolated_test_state_root();
138 if !current_thread_holds_test_env_lock() {
139 return shared.to_path_buf();
140 }
141 // libtest runs each test in a fresh thread. Keep one root for that thread:
142 // a settings save resolves its path more than once, while different tests
143 // must not inherit each other's files.
144 HOLDER_ROOT.with(|cached| {
145 cached
146 .get_or_init(|| {
147 let root = shared.join(format!("env-holder-{:?}", std::thread::current().id()));
148 std::fs::create_dir_all(&root).unwrap_or_else(|error| {
149 panic!(
150 "failed to create per-holder test state root {}: {error}",
151 root.display()
152 )
153 });
154 root
155 })
156 .clone()
157 })
158 }
159
160 thread_local! {
161 static HOLDER_ROOT: OnceLock<PathBuf> = const { OnceLock::new() };
162 }
163
164 /// Where a state resolver must put `name` instead of the user's home: the
165 /// isolated test root when no test has sealed the home (see [`home_is_sealed`]),
166 /// `None` when one has and the resolver should follow the environment as
167 /// production does.
168 ///
169 /// Every resolver that reaches `~/.codewhale` and is reachable from a test
170 /// needs this fence, because incidental callers (an `App` constructor, a
171 /// command dispatch) never think about the home at all. Call it first, under
172 /// `#[cfg(test)]`, so the production path stays byte-for-byte unchanged.
173 ///
174 /// The directory is under the shared isolated root, not the per-holder one
175 /// [`unsealed_test_state_root`] hands to lock holders: these resolvers are
176 /// reached from worker threads as well as the test thread, and a test must see
177 /// one directory from both. The directory exists when this returns, so callers
178 /// need no filesystem call of their own on the fenced branch.
179 pub fn unsealed_state_dir(name: impl AsRef<Path>) -> Option<PathBuf> {
180 if home_is_sealed() {
181 return None;
182 }
183 let dir = isolated_test_state_root().join(name);
184 std::fs::create_dir_all(&dir).unwrap_or_else(|error| {
185 panic!(
186 "failed to create the unsealed test state dir {}: {error}",
187 dir.display()
188 )
189 });
190 Some(dir)
191 }
192
193 fn state_io_lock() -> &'static Mutex<()> {
194 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
195 LOCK.get_or_init(|| Mutex::new(()))
196 }
197
198 /// Serialize read/merge/write operations against the process-wide isolated
199 /// test state root.
200 ///
201 /// Path isolation protects the developer's files, but parallel tests still
202 /// share the same temporary files. Settings persistence is a multi-step
203 /// operation, so it needs this second barrier around the complete I/O
204 /// transaction rather than only around path resolution.
205 pub fn with_test_state_io_lock<T>(operation: impl FnOnce() -> T) -> T {
206 let _guard = match state_io_lock().lock() {
207 Ok(guard) => guard,
208 Err(poisoned) => poisoned.into_inner(),
209 };
210 operation()
211 }
212
213 /// Build a test phase's future inside this call and box it (#6362).
214 ///
215 /// In debug builds every inline `async {}` value gets a stack slot in the
216 /// enclosing poll frame the size of that future's whole state machine, and
217 /// the slots are never reused, so a body that awaits four phases inline
218 /// carries all four state machines on its own frame at once (measured at
219 /// 806 KiB for the runtime-store binding test). Constructing the phase here
220 /// leaves the caller holding a pointer, and the phase's own temporaries die
221 /// with its poll frame.
222 pub fn boxed_phase<'a, T, M, F>(
223 make: M,
224 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = T> + 'a>>
225 where
226 M: FnOnce() -> F,
227 F: std::future::Future<Output = T> + 'a,
228 {
229 Box::pin(make())
230 }
231
232 /// Drive a test future on a thread with libtest's default stack (2 MiB, or
233 /// 4 MiB on Windows where the same frames are larger), whatever
234 /// `RUST_MIN_STACK` says (#6362).
235 ///
236 /// CI exports a 16 MiB `RUST_MIN_STACK` for every test thread, so a test
237 /// that only fits because of that export never learns it overflowed the
238 /// stack a contributor's plain `cargo test` gives it. The future is built on
239 /// the spawned thread (so it need not be `Send`) and pinned before
240 /// `block_on`, exactly as `#[tokio::test]` drives a current-thread runtime;
241 /// a panic inside propagates to the caller unchanged. An overflow still
242 /// aborts the process with "has overflowed its stack": that is the reported
243 /// symptom, not something this helper can turn into a panic.
244 pub fn block_on_default_test_stack<M, F, T>(make: M) -> T
245 where
246 M: FnOnce() -> F + Send + 'static,
247 F: std::future::Future<Output = T>,
248 T: Send + 'static,
249 {
250 #[cfg(windows)]
251 const DEFAULT_TEST_THREAD_STACK: usize = 4 * 1024 * 1024;
252 #[cfg(not(windows))]
253 const DEFAULT_TEST_THREAD_STACK: usize = 2 * 1024 * 1024;
254 std::thread::Builder::new()
255 .name("default-test-stack".into())
256 .stack_size(DEFAULT_TEST_THREAD_STACK)
257 .spawn(move || {
258 let runtime = tokio::runtime::Builder::new_current_thread()
259 .enable_all()
260 .build()
261 .expect("current-thread test runtime");
262 let future = make();
263 tokio::pin!(future);
264 runtime.block_on(future)
265 })
266 .expect("spawn the default-stack test thread")
267 .join()
268 .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
269 }
270
271 /// Whether the calling test actually provided the state-path environment it
272 /// is about to resolve.
273 ///
274 /// Holding [`lock_test_env`] alone is not that: many tests hold the lock only
275 /// to serialize access to unrelated variables (`TERM_PROGRAM`, API keys) and
276 /// have provided no temporary paths at all. Trusting the lock routed those
277 /// tests to the developer's real `~/.codewhale` state, which is exactly the
278 /// leak the isolated root exists to prevent (#5359). A test earns environment
279 /// resolution by holding the lock *and* either setting one of the explicit
280 /// override variables or redirecting `HOME`/`USERPROFILE` through
281 /// [`EnvVarGuard`].
282 pub fn guarded_environment_provides_state_paths() -> bool {
283 if state_from_environment() {
284 return true;
285 }
286 if !current_thread_holds_test_env_lock() {
287 return false;
288 }
289 let guarded_path_is_present = |var: &str| {
290 env_var_currently_guarded(var)
291 && std::env::var_os(var)
292 .is_some_and(|value| value.to_str().is_none_or(|text| !text.trim().is_empty()))
293 };
294 [
295 "CODEWHALE_HOME",
296 "CODEWHALE_CONFIG_PATH",
297 "DEEPSEEK_CONFIG_PATH",
298 "HOME",
299 "USERPROFILE",
300 ]
301 .iter()
302 .any(|var| guarded_path_is_present(var))
303 }
304
305 /// Whether the calling test's live seal pins the user's *home* — the root that
306 /// user state (sessions, snapshots, plugin bundles, logs) resolves under — as
307 /// opposed to merely redirecting a config file.
308 ///
309 /// The owner and workers enrolled through [`join_env_scope`] follow the seal.
310 /// Unrelated parallel tests and workers without that scope use the isolated
311 /// root: following another test's environment would race its restoration to
312 /// the developer's real profile. Pass [`env_scope_ticket`] to workers that need
313 /// their owner's home.
314 ///
315 /// Stricter than [`guarded_environment_provides_state_paths`], which also
316 /// accepts a guarded config-path override: such a test still resolves
317 /// `~/.codewhale` for everything else. `CODEWHALE_HOME` outranks `HOME` when it
318 /// is set, so a guarded `HOME` seals nothing while an unguarded
319 /// `CODEWHALE_HOME` is in the ambient environment.
320 pub fn home_is_sealed() -> bool {
321 if state_from_environment() {
322 return true;
323 }
324 if !current_thread_holds_test_env_lock() {
325 return false;
326 }
327 let present = |var: &str| {
328 std::env::var_os(var)
329 .is_some_and(|value| value.to_str().is_none_or(|text| !text.trim().is_empty()))
330 };
331 if present("CODEWHALE_HOME") {
332 return env_var_currently_guarded("CODEWHALE_HOME");
333 }
334 ["HOME", "USERPROFILE"]
335 .iter()
336 .any(|var| env_var_currently_guarded(var) && present(var))
337 }
338
339 /// Seal the user's home onto a directory the test owns, for the life of one
340 /// test.
341 ///
342 /// This is the one way a test takes the user's state out of play. It pins
343 /// `HOME`, `USERPROFILE` and `CODEWHALE_HOME` through [`EnvVarGuard`] — so
344 /// [`guarded_environment_provides_state_paths`] recognises the seal — and
345 /// removes the aliases that would otherwise route around them
346 /// (`HOMEDRIVE`/`HOMEPATH`, `CODEWHALE_CONFIG_PATH`, `DEEPSEEK_CONFIG_PATH`,
347 /// `DEEPSEEK_HOME`). Pinning `HOME` alone is not a seal: an ambient
348 /// `CODEWHALE_HOME` takes precedence over it, so a test that "scoped" only
349 /// `HOME` still wrote the developer's real profile.
350 ///
351 /// It holds the process-wide environment lock, which is not reentrant: keep
352 /// one seal per test, and build any fixture that takes the lock itself
353 /// (settings, diagnostics harnesses) after it. Anything that reads or writes
354 /// the user's state — instructions, skills, sessions, snapshots, settings,
355 /// credentials — then lands in the seal.
356 pub struct SealedHome {
357 // Drop order matters: restore the environment, then delete the directory,
358 // then release the lock.
359 _vars: Vec<EnvVarGuard>,
360 _dir: Option<tempfile::TempDir>,
361 home: PathBuf,
362 codewhale_home: PathBuf,
363 _lock: TestEnvLock,
364 }
365
366 #[expect(clippy::new_without_default)]
367 impl SealedHome {
368 /// Seal onto fresh, empty directories: `<tmp>/home` and
369 /// `<tmp>/codewhale-home`.
370 pub fn new() -> Self {
371 let lock = lock_test_env();
372 let dir = tempfile::TempDir::new().expect("sealed home tempdir");
373 let home = dir.path().join("home");
374 let codewhale_home = dir.path().join("codewhale-home");
375 std::fs::create_dir_all(&home).expect("sealed home dir");
376 std::fs::create_dir_all(&codewhale_home).expect("sealed codewhale home dir");
377 Self::pin(lock, Some(dir), home, codewhale_home)
378 }
379
380 /// Seal onto a home the test already owns: `HOME` is `home` and the
381 /// Codewhale home is `home/.codewhale`, the layout an unset
382 /// `CODEWHALE_HOME` resolves to. For tests whose fixtures are built under
383 /// one tempdir that also plays the home.
384 pub fn at(home: &Path) -> Self {
385 let lock = lock_test_env();
386 let codewhale_home = home.join(".codewhale");
387 Self::pin(lock, None, home.to_path_buf(), codewhale_home)
388 }
389
390 fn pin(
391 lock: TestEnvLock,
392 dir: Option<tempfile::TempDir>,
393 home: PathBuf,
394 codewhale_home: PathBuf,
395 ) -> Self {
396 // `CODEWHALE_HOME` first: it is dropped first, so the seal never
397 // outlives the override that outranks `HOME`.
398 let vars = vec![
399 EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home),
400 EnvVarGuard::set("HOME", &home),
401 EnvVarGuard::set("USERPROFILE", &home),
402 EnvVarGuard::remove("HOMEDRIVE"),
403 EnvVarGuard::remove("HOMEPATH"),
404 EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"),
405 EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"),
406 EnvVarGuard::remove("DEEPSEEK_HOME"),
407 ];
408 Self {
409 _vars: vars,
410 _dir: dir,
411 home,
412 codewhale_home,
413 _lock: lock,
414 }
415 }
416
417 /// The sealed `HOME` / `USERPROFILE`.
418 pub fn home(&self) -> &Path {
419 &self.home
420 }
421
422 /// The sealed `CODEWHALE_HOME`.
423 pub fn codewhale_home(&self) -> &Path {
424 &self.codewhale_home
425 }
426 }
427
428 /// Find the byte position of the first divergence between two strings,
429 /// returning a windowed view (`±32 bytes` around the divergence) so failures
430 /// in cache-prefix-stability tests show *which* bytes drifted, not just that
431 /// they did. Returns `None` when the strings are byte-identical.
432 pub fn first_divergence(a: &str, b: &str) -> Option<(usize, String, String)> {
433 let a_bytes = a.as_bytes();
434 let b_bytes = b.as_bytes();
435 let max = a_bytes.len().min(b_bytes.len());
436 for i in 0..max {
437 if a_bytes[i] != b_bytes[i] {
438 let lo = i.saturating_sub(32);
439 let a_hi = (i + 32).min(a_bytes.len());
440 let b_hi = (i + 32).min(b_bytes.len());
441 let a_ctx = String::from_utf8_lossy(&a_bytes[lo..a_hi]).into_owned();
442 let b_ctx = String::from_utf8_lossy(&b_bytes[lo..b_hi]).into_owned();
443 return Some((i, a_ctx, b_ctx));
444 }
445 }
446 if a_bytes.len() != b_bytes.len() {
447 return Some((
448 max,
449 format!("(len={})", a_bytes.len()),
450 format!("(len={})", b_bytes.len()),
451 ));
452 }
453 None
454 }
455
456 /// Assert two strings are byte-identical, panicking with a windowed diff
457 /// around the first divergence when they aren't. Used by the prefix-cache
458 /// stability harness (#263, #280) to pin construction surfaces that land in
459 /// DeepSeek's KV cache prefix.
460 #[track_caller]
461 pub fn assert_byte_identical(label: &str, a: &str, b: &str) {
462 if let Some((pos, a_ctx, b_ctx)) = first_divergence(a, b) {
463 panic!(
464 "{label}: prompt construction is non-deterministic — first diff at byte {pos}\n\
465 ── side A (±32B) ──\n{a_ctx:?}\n── side B (±32B) ──\n{b_ctx:?}",
466 );
467 }
468 }
469
470 pub fn read_shell_sentinel(path: &Path) -> String {
471 let bytes = std::fs::read(path).unwrap_or_default();
472 let text = if bytes.starts_with(&[0xFF, 0xFE]) {
473 let units: Vec<u16> = bytes[2..]
474 .as_chunks::<2>()
475 .0
476 .iter()
477 .map(|pair| u16::from_le_bytes(*pair))
478 .collect();
479 String::from_utf16_lossy(&units)
480 } else {
481 String::from_utf8_lossy(&bytes).into_owned()
482 };
483 text.trim_start_matches('\u{feff}')
484 .replace("\r\n", "\n")
485 .replace('"', "")
486 .trim()
487 .to_string()
488 }
489
490 /// Build a syntactically valid, non-secret JWT fixture without embedding a
491 /// high-entropy token-shaped literal in Git history.
492 pub fn future_test_jwt(label: &str) -> String {
493 use base64::Engine as _;
494
495 let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(br#"{"exp":9999999999}"#);
496 format!("test.{payload}.{label}")
497 }
498
499 #[cfg(test)]
500 mod tests {
501 use super::*;
502
503 #[test]
504 fn test_scratch_dirs_are_distinct_under_the_process_root_and_removable() {
505 let first = test_scratch_dir("codewhale-scratch-probe");
506 let second = test_scratch_dir("codewhale-scratch-probe");
507 let root = TEST_SCRATCH_ROOT.get().expect("scratch root initialized");
508
509 assert_ne!(first, second);
510 assert!(root.is_dir());
511 for dir in [&first, &second] {
512 assert_eq!(dir.parent(), Some(root.as_path()));
513 assert!(!dir.exists());
514 }
515
516 let nested = first.join("nested");
517 std::fs::create_dir_all(&nested).expect("create scratch dir");
518 std::fs::write(nested.join("file"), b"x").expect("write scratch file");
519 #[cfg(unix)]
520 {
521 use std::os::unix::fs::PermissionsExt;
522 std::fs::set_permissions(&nested, std::fs::Permissions::from_mode(0o500))
523 .expect("make scratch dir read-only");
524 }
525
526 remove_test_root(&first);
527
528 assert!(!first.exists());
529 assert!(root.is_dir());
530 }
531
532 #[test]
533 fn ambient_codewhale_home_is_not_a_test_seal() {
534 let _lock = lock_test_env();
535 let _ambient = EnvVarGuard::set("CODEWHALE_HOME", "/tmp/ambient-codewhale-home");
536 unregister_guarded_env_key("CODEWHALE_HOME");
537
538 let sealed = guarded_environment_provides_state_paths();
539
540 register_guarded_env_key("CODEWHALE_HOME");
541 assert!(!sealed, "ambient developer state must remain confined");
542 }
543
544 #[test]
545 fn a_config_path_guard_or_a_home_shadowed_by_the_ambient_override_is_not_a_home_seal() {
546 let _lock = lock_test_env();
547 let dir = tempfile::tempdir().expect("tempdir");
548 {
549 // Redirecting the config file leaves `~/.codewhale` in play.
550 let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", dir.path().join("config.toml"));
551 let _no_home_override = EnvVarGuard::remove("CODEWHALE_HOME");
552 assert!(guarded_environment_provides_state_paths());
553 assert!(!home_is_sealed());
554 }
555 {
556 // `CODEWHALE_HOME` outranks `HOME`: guarding only `HOME` while an
557 // ambient `CODEWHALE_HOME` is set seals nothing.
558 let _ambient = EnvVarGuard::set("CODEWHALE_HOME", dir.path().join("ambient"));
559 unregister_guarded_env_key("CODEWHALE_HOME");
560 let _home = EnvVarGuard::set("HOME", dir.path());
561 let sealed = home_is_sealed();
562 register_guarded_env_key("CODEWHALE_HOME");
563 assert!(!sealed, "an ambient CODEWHALE_HOME shadows a guarded HOME");
564 }
565 {
566 let _no_home_override = EnvVarGuard::remove("CODEWHALE_HOME");
567 let _home = EnvVarGuard::set("HOME", dir.path());
568 assert!(home_is_sealed());
569 }
570 }
571
572 #[test]
573 fn removing_overrides_does_not_seal_the_ambient_home() {
574 let _lock = lock_test_env();
575 let _codewhale_home = EnvVarGuard::remove("CODEWHALE_HOME");
576 let _codewhale_config = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
577 let _deepseek_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
578
579 assert!(
580 !guarded_environment_provides_state_paths(),
581 "removing an override must not expose the developer's HOME"
582 );
583 }
584 }
585
585 lines RUST