From d3783357223e56be0a5615e2639e6573ae91fcf0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:17:12 -0800 Subject: [PATCH 1/2] craft-testkit: add the serial module with a reentrant test lock TestLock is a lock a static can hold (TestLock::new is const). The thread that holds it can take it again, and it is released when the last of that thread's guards is dropped, in any order. A panic while it is held does not block the next holder, and a poisoned internal mutex is recovered. Guards are not Send. gpu_lock() is the one lock of the process for GPU tests, and hold_gpu_lock() keeps it until the calling thread ends; a second call on the same thread does nothing more. The module is native only and reads no environment variables. The lock comes from PhotoCraft's crates/testkit/src/gpu.rs and DeckCraft's crates/ui-egui/src/gpu_lock.rs, with the thread-held form from EffectCraft's crates/gpu/src/tests.rs. a_panicked_holder_does_not_block_the_next_test and holders_take_turns keep their names; holders_take_turns now waits on channels instead of sleeping 2 ms. --- Cargo.lock | 4 + Cargo.toml | 1 + crates/testkit/Cargo.toml | 14 ++ crates/testkit/README.md | 48 +++++ crates/testkit/src/lib.rs | 11 ++ crates/testkit/src/serial.rs | 331 +++++++++++++++++++++++++++++++++++ 6 files changed, 409 insertions(+) create mode 100644 crates/testkit/Cargo.toml create mode 100644 crates/testkit/README.md create mode 100644 crates/testkit/src/lib.rs create mode 100644 crates/testkit/src/serial.rs diff --git a/Cargo.lock b/Cargo.lock index 3d8cf4a7b3..7b8d513e3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2569,6 +2569,10 @@ dependencies = [ "kurbo 0.13.1", ] +[[package]] +name = "craft-testkit" +version = "0.1.0" + [[package]] name = "craft-text" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 576efca6f1..fab6b70440 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -138,6 +138,7 @@ craft-stencilcraft-format = { path = "crates/stencilcraft-format" } craft-stencilcraft-document = { path = "crates/stencilcraft-document" } craft-svg-paths = { path = "crates/svg-paths" } craft-stream-codecs = { path = "crates/stream-codecs" } +craft-testkit = { path = "crates/testkit" } craft-text = { path = "crates/text" } craft-texture = { path = "crates/texture" } craft-tga = { path = "crates/tga" } diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml new file mode 100644 index 0000000000..5a67bd19b2 --- /dev/null +++ b/crates/testkit/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-testkit" +description = "Shared test support for the Craft apps: a reentrant test lock and other helpers. Test support only." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +publish = false + +[dependencies] + +[lints] +workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md new file mode 100644 index 0000000000..485496ea77 --- /dev/null +++ b/crates/testkit/README.md @@ -0,0 +1,48 @@ +# craft-testkit + +Shared test support for the Craft apps. The crate is not published, and apps and craft-libs crates +take it under `[dev-dependencies]`. + +## serial + +`serial` is native only. + +- `TestLock::new()` is `const`, so a lock can be a `static`: + `static L: TestLock = TestLock::new(); let _g = L.hold();`. +- The thread that holds a lock can call `hold()` again. The lock is released when the last of that + thread's guards is dropped, in any order. +- A test that panics while it holds a lock does not block the next one, and a poisoned internal + mutex is recovered. +- `gpu_lock()` is the one lock of the process for tests that build a GPU harness or device. + `hold_gpu_lock()` takes it and keeps it until the calling thread ends; a second call on the same + thread does nothing more. +- A guard is not `Send`. The lock covers one process: under nextest each test runs in its own + process. +- The module reads no environment variables and prints nothing. + +The tests use channel handshakes and contain no sleeps or time limits. + +## Origin + +| Module | Source repository | Path | SHA | +|---|---|---|---| +| `serial` | storytold/photocraft | `crates/testkit/src/gpu.rs` | `0d3b1e8523` | +| `serial` | storytold/deckcraft | `crates/ui-egui/src/gpu_lock.rs` | `b0c77ebd6a` | +| `serial` | storytold/effectcraft | `crates/ui-egui/tests/it/gpu_test.rs`, `crates/gpu/src/tests.rs` | `f029bbadb2` | +| `serial` | storytold/pdfcraft | `apps/pdfcraft/src/tests.rs` | `346d803080` | + +`a_panicked_holder_does_not_block_the_next_test` and `holders_take_turns` keep their names from +PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copies slept 2 ms. + +## Migration + +| Consumer | Module | Switched | +|---|---|---| +| PhotoCraft | `serial` | No | +| DeckCraft | `serial` | No | +| EffectCraft | `serial` | No | +| PdfCraft | `serial` | No | + +## Maintainer + +To be agreed in the review of the crate's first pull request. diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs new file mode 100644 index 0000000000..9830ded4ef --- /dev/null +++ b/crates/testkit/src/lib.rs @@ -0,0 +1,11 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! Shared test support for the Craft apps. Test support only: unpublished, and used as a +//! dev-dependency. +//! +//! [`serial`] holds [`serial::TestLock`], a lock that a `static` can hold and that the thread +//! holding it can take again, and [`serial::gpu_lock`], the one lock every GPU test of a process +//! takes. It is native only. + +#[cfg(not(target_arch = "wasm32"))] +pub mod serial; diff --git a/crates/testkit/src/serial.rs b/crates/testkit/src/serial.rs new file mode 100644 index 0000000000..72fa9cff78 --- /dev/null +++ b/crates/testkit/src/serial.rs @@ -0,0 +1,331 @@ +//! Locks that keep the tests of one process out of a section at the same time. +//! +//! `cargo test` runs a binary's tests on parallel threads. A test that must not overlap another +//! one takes a [`TestLock`] for its whole run: +//! +//! ``` +//! use craft_testkit::serial::TestLock; +//! +//! static FILES: TestLock = TestLock::new(); +//! +//! let _files = FILES.hold(); +//! // The rest of the test runs while no other thread holds `FILES`. +//! ``` +//! +//! The thread that holds a lock can take it again. Each [`TestLock::hold`] returns a guard, and the +//! lock is free again when the last of that thread's guards is dropped, in any order. A test that +//! panics while it holds a lock releases the lock as its guards unwind, so the next test is not +//! blocked. A lock works inside one process only: under nextest each test is its own process, and +//! the lock is never contended. Waiting threads take the lock in no particular order. +//! +//! [`gpu_lock`] is the one lock of the process for tests that build a GPU harness or a wgpu device. +//! Several graphics drivers crash when one process drives wgpu devices from more than one thread +//! at once. Take it on the test's first line (`let _gpu = gpu_lock();`) so it is released last. +//! [`hold_gpu_lock`] takes the same lock and keeps it until the calling thread ends. + +use std::cell::RefCell; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::{Condvar, Mutex, MutexGuard, PoisonError}; +use std::thread::{self, ThreadId}; + +/// Which thread holds a [`TestLock`], and how many of its guards are alive. +#[derive(Debug)] +struct State { + owner: Option, + depth: usize, + /// Threads blocked in [`TestLock::hold`], so a test can tell that a thread is waiting. + #[cfg(test)] + waiting: usize, +} + +/// A lock for tests that one thread holds at a time and that the holding thread can take again. +/// +/// [`TestLock::new`] is `const`, so a lock can be a `static`. A panic while the lock is held does +/// not poison it. +#[derive(Debug)] +pub struct TestLock { + state: Mutex, + free: Condvar, +} + +impl TestLock { + /// A lock that no thread holds. + pub const fn new() -> Self { + Self { + state: Mutex::new(State { + owner: None, + depth: 0, + #[cfg(test)] + waiting: 0, + }), + free: Condvar::new(), + } + } + + /// Waits until no other thread holds the lock, then holds it until the returned guard and every + /// other guard of this thread are dropped. A thread that already holds the lock gets another + /// guard at once. + /// + /// A thread that keeps `usize::MAX` guards alive at once (for example by forgetting them) blocks + /// in its next call instead of letting the count wrap. + pub fn hold(&self) -> TestLockGuard<'_> { + let me = thread::current().id(); + let mut state = self.lock_state(); + loop { + match state.owner { + None => { + state.owner = Some(me); + state.depth = 1; + break; + } + Some(owner) if owner == me && state.depth < usize::MAX => { + state.depth += 1; + break; + } + Some(_) => { + #[cfg(test)] + { + state.waiting += 1; + } + state = self.free.wait(state).unwrap_or_else(PoisonError::into_inner); + #[cfg(test)] + { + state.waiting -= 1; + } + } + } + } + drop(state); + TestLockGuard { lock: self, not_send: PhantomData } + } + + fn lock_state(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +impl Default for TestLock { + fn default() -> Self { + Self::new() + } +} + +/// One hold of a [`TestLock`]. The lock is released when the last guard of the holding thread is +/// dropped. A guard is not `Send`: it is dropped on the thread that took it. +#[derive(Debug)] +#[must_use = "the lock is released when the guard is dropped"] +pub struct TestLockGuard<'a> { + lock: &'a TestLock, + not_send: PhantomData>, +} + +impl Drop for TestLockGuard<'_> { + fn drop(&mut self) { + let mut state = self.lock.lock_state(); + state.depth = state.depth.saturating_sub(1); + if state.depth == 0 { + state.owner = None; + drop(state); + self.lock.free.notify_one(); + } + } +} + +static GPU_LOCK: TestLock = TestLock::new(); + +thread_local! { + static HELD_GPU: RefCell>> = const { RefCell::new(None) }; +} + +/// Holds the process's GPU lock for as long as the guard lives. Take it before the test creates a +/// GPU harness or device, and keep it for the whole test, harness included. +pub fn gpu_lock() -> TestLockGuard<'static> { + GPU_LOCK.hold() +} + +/// Holds the process's GPU lock until the calling thread ends. Calling it again on the same thread +/// does nothing more. Called on a long-lived thread, such as a harness's main thread, it keeps +/// every other thread out of [`gpu_lock`] until that thread ends. +/// +/// The lock is released by the thread's local-variable destructors, so it is not released when the +/// process exits or aborts while the thread runs. While the thread's locals are being destroyed, +/// the call returns without taking the lock. +pub fn hold_gpu_lock() { + let _ = HELD_GPU.try_with(|held| { + if let Ok(mut held) = held.try_borrow_mut() + && held.is_none() + { + *held = Some(gpu_lock()); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::mpsc; + + fn owner_and_depth(lock: &TestLock) -> (Option, usize) { + let state = lock.lock_state(); + (state.owner, state.depth) + } + + /// Yields until `ready` is true of the lock's state. + fn until(lock: &TestLock, ready: impl Fn(&State) -> bool) { + while !ready(&lock.lock_state()) { + thread::yield_now(); + } + } + + #[test] + fn a_panicked_holder_does_not_block_the_next_test() { + let holder = thread::spawn(|| { + let _gpu = gpu_lock(); + panic!("a GPU test failed"); + }); + let id = holder.thread().id(); + let _ = holder.join(); + assert_ne!(owner_and_depth(&GPU_LOCK).0, Some(id)); + drop(gpu_lock()); + } + + #[test] + fn poisoned_state_recovers() { + let lock = &TestLock::new(); + let poisoned = thread::scope(|s| { + s.spawn(|| { + let _state = lock.state.lock(); + panic!("poison the state"); + }) + .join() + }); + assert!(poisoned.is_err()); + assert!(lock.state.is_poisoned()); + let outer = lock.hold(); + thread::scope(|s| { + let (tx, rx) = mpsc::channel(); + s.spawn(move || { + let _held = lock.hold(); + tx.send(()).unwrap(); + }); + until(lock, |state| state.waiting == 1); + drop(outer); + rx.recv().unwrap(); + }); + assert_eq!(owner_and_depth(lock), (None, 0)); + } + + #[test] + fn holders_take_turns() { + let lock = &TestLock::new(); + let inside = &AtomicUsize::new(0); + let max = &AtomicUsize::new(0); + let first = lock.hold(); + thread::scope(|s| { + let (entered_tx, entered_rx) = mpsc::channel(); + let releases: Vec<_> = (0..8) + .map(|i| { + let (release_tx, release_rx) = mpsc::channel::<()>(); + let entered_tx = entered_tx.clone(); + s.spawn(move || { + let _held = lock.hold(); + let now = inside.fetch_add(1, Ordering::SeqCst) + 1; + max.fetch_max(now, Ordering::SeqCst); + entered_tx.send(i).unwrap(); + release_rx.recv().unwrap(); + inside.fetch_sub(1, Ordering::SeqCst); + }); + release_tx + }) + .collect(); + until(lock, |state| state.waiting + inside.load(Ordering::SeqCst) == 8); + drop(first); + for _ in 0..8 { + let i: usize = entered_rx.recv().unwrap(); + releases[i].send(()).unwrap(); + } + }); + assert_eq!(max.load(Ordering::SeqCst), 1); + } + + #[test] + fn static_lock_is_const_and_reentrant() { + static LOCK: TestLock = TestLock::new(); + let outer = LOCK.hold(); + let inner = LOCK.hold(); + assert_eq!(owner_and_depth(&LOCK), (Some(thread::current().id()), 2)); + drop(inner); + drop(outer); + assert_eq!(owner_and_depth(&LOCK), (None, 0)); + } + + #[test] + fn nested_guards_drop_in_either_order() { + for outer_first in [true, false] { + let lock = &TestLock::new(); + let outer = lock.hold(); + let inner = lock.hold(); + thread::scope(|s| { + let (tx, rx) = mpsc::channel(); + s.spawn(move || { + let _held = lock.hold(); + tx.send(()).unwrap(); + }); + until(lock, |state| state.waiting == 1); + let (first, second) = if outer_first { (outer, inner) } else { (inner, outer) }; + drop(first); + assert_eq!(owner_and_depth(lock), (Some(thread::current().id()), 1), "outer_first: {outer_first}"); + drop(second); + rx.recv().unwrap(); + }); + assert_eq!(owner_and_depth(lock), (None, 0)); + } + } + + #[test] + fn gpu_thread_hold_is_idempotent_and_releases_at_exit() { + let holder = thread::spawn(|| { + let early = gpu_lock(); + hold_gpu_lock(); + hold_gpu_lock(); + let with_early = owner_and_depth(&GPU_LOCK); + drop(early); + let held = owner_and_depth(&GPU_LOCK); + let late = gpu_lock(); + let with_late = owner_and_depth(&GPU_LOCK); + drop(late); + let held_again = owner_and_depth(&GPU_LOCK); + [with_early, held, with_late, held_again] + }); + let id = Some(holder.thread().id()); + let depths = holder.join().unwrap(); + assert_eq!(depths, [(id, 2), (id, 1), (id, 2), (id, 1)]); + assert_ne!(owner_and_depth(&GPU_LOCK).0, id); + drop(gpu_lock()); + } + + #[test] + fn different_locks_are_independent() { + let a = TestLock::new(); + let b = TestLock::new(); + let _a = a.hold(); + assert_eq!(owner_and_depth(&b), (None, 0)); + thread::scope(|s| s.spawn(|| drop(b.hold())).join()).unwrap(); + assert_eq!(owner_and_depth(&b), (None, 0)); + } + + trait AmbiguousIfSend { + fn some_item() {} + } + impl AmbiguousIfSend<()> for T {} + impl AmbiguousIfSend for T {} + + #[test] + fn guard_is_not_send() { + // Compiles only while `TestLockGuard` is not `Send`: for a `Send` guard both impls apply and + // the call is ambiguous. + let _ = as AmbiguousIfSend<_>>::some_item; + } +} From 7938b7f5789b1e7acda21112ac7bfa41d68359b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 19:57:29 -0800 Subject: [PATCH 2/2] craft-testkit: state that every GPU test must take the shared lock --- crates/testkit/src/lib.rs | 3 ++- crates/testkit/src/serial.rs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index ae8cf2442c..77fb0da549 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -26,7 +26,8 @@ //! //! On targets other than `wasm32`, [`serial`] holds [`serial::TestLock`], a lock that a `static` //! can hold and that the thread holding it can take again, and [`serial::gpu_lock`], the one lock -//! every GPU test of a process takes. +//! for GPU tests. Every GPU test in a process must take this lock, because a test that takes a +//! different lock can run at the same time as one that takes this one. //! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! diff --git a/crates/testkit/src/serial.rs b/crates/testkit/src/serial.rs index 72fa9cff78..e8ec0e6572 100644 --- a/crates/testkit/src/serial.rs +++ b/crates/testkit/src/serial.rs @@ -20,7 +20,7 @@ //! //! [`gpu_lock`] is the one lock of the process for tests that build a GPU harness or a wgpu device. //! Several graphics drivers crash when one process drives wgpu devices from more than one thread -//! at once. Take it on the test's first line (`let _gpu = gpu_lock();`) so it is released last. +//! at once. Every such test in a process must take this lock. Take it on the test's first line (`let _gpu = gpu_lock();`) so it is released last. //! [`hold_gpu_lock`] takes the same lock and keeps it until the calling thread ends. use std::cell::RefCell;