gpui: Make test-support safe to enable in every build (#65043)

Projects that depend on GPUI rebuild it, and everything above it,
whenever they switch between running their app and running their tests:
`cargo test` turns on `test-support` through dev-dependencies, and
`cargo build` doesn't. Turning `test-support` on in every build would
remove that split, but today the feature changes runtime behavior, so it
can't ship in a production binary. This PR makes it additive where it
mattered.

- **Leak detection is opt-in.** `gpui/test-support` no longer turns on
`leak-detection`, which takes the entity map's write lock on every
handle create and drop. It's now enabled by the `leak-detection` feature
(as `zed/track-project-leak` already does) or by setting
`GPUI_LEAK_DETECTION=1` when building. Without it:
  - `leak_detector_snapshot()` and `assert_no_new_leaks()` are no-ops;
- `WeakEntity::assert_released()` still panics when the entity is alive,
but can't list the live handles.
- **`util::paths::home_dir()`** returns the fixed fake path
(`/Users/zed`) only in `util`'s own tests, not whenever
`util/test-support` is on. No test outside `util` depended on the fake
path.
- **`is_test()` on GPUI contexts.** `App::is_test`, `AsyncApp::is_test`
and `BackgroundExecutor::is_test` (in gpui and scheduler) report whether
the executor is a `TestScheduler`, in every build. Code that must behave
differently under tests should use these instead of `cfg(feature =
"test-support")`, so compiling the feature into an app doesn't change
its behavior. For code with no executor, such as expensive invariant
checks, `scheduler::test_scheduler_created()` reports whether the
process has created a `TestScheduler`, which test harnesses do before
the test body runs.
- **Metal `framebuffer_only(false)`** (needed for offscreen capture) now
only applies in debug builds, so optimized builds that compile
`test-support` keep the faster presentation path.

**Open question:** CI doesn't set `GPUI_LEAK_DETECTION`, so with this
change leak checks outside gpui's own unit tests are skipped in CI. If
we go ahead, the test jobs should set it. I've left that out until we
agree on the approach.

This PR is mainly to see what CI says about crates whose tests read
`home_dir()` (`project`, `worktree`, `workspace`, …), which now see the
real home directory.

Release Notes:

- [GPUI] Made the `test-support` feature safe to enable in production
builds: leak detection is now opt-in via the `leak-detection` feature or
`GPUI_LEAK_DETECTION`, and `App::is_test` reports whether code runs
under the test scheduler
This commit is contained in:
Conrad Irwin
2026-10-01 16:33:50 +00:00
committed by GitHub
parent 1399a804bd
commit 95cd535a5f
12 changed files with 120 additions and 41 deletions
+2 -4
View File
@@ -745,10 +745,8 @@ pub fn builtin_skill_content(skill_file_path: &Path) -> Option<&'static str> {
/// location, so a Zed installation may have skills here even before the
/// rest of Zed's skills support ships.
///
/// In test builds, `paths::home_dir()` is hardcoded to a fixed path
/// (e.g. `/Users/zed`), so all tests using this function operate on the
/// same simulated home directory. Each test should use its own `FakeFs`
/// instance to keep skill setups from leaking across tests.
/// Tests see the real home directory here, so they should resolve this path
/// against their own `FakeFs` instance rather than the real filesystem.
pub fn global_skills_dir() -> PathBuf {
paths::home_dir()
.join(AGENTS_DIR_NAME)
+4 -3
View File
@@ -19,7 +19,6 @@ workspace = true
[features]
default = ["font-kit", "wayland", "x11", "windows-manifest"]
test-support = [
"leak-detection",
"collections/test-support",
"http_client/test-support",
"wayland",
@@ -30,7 +29,9 @@ bench-support = ["profiler", "dep:criterion", "dep:bench_metrics"]
# Preserve the published feature name while consumers migrate to `bench-support`.
bench = ["bench-support"]
inspector = ["gpui_macros/inspector"]
leak-detection = ["backtrace"]
# Tracks every entity handle so tests can assert nothing leaked. Also enabled
# by setting `GPUI_LEAK_DETECTION` when building; see `build.rs`.
leak-detection = []
wayland = []
x11 = [
"scap?/x11",
@@ -49,7 +50,7 @@ path = "src/gpui.rs"
accesskit.workspace = true
anyhow.workspace = true
async-task.workspace = true
backtrace = { workspace = true, optional = true }
backtrace.workspace = true
bitflags.workspace = true
collections.workspace = true
+12
View File
@@ -3,6 +3,18 @@
fn main() {
println!("cargo::rustc-check-cfg=cfg(gles)");
// Leak detection does bookkeeping on every entity handle, so `test-support`
// does not enable it: that feature must stay cheap enough to compile into
// every build. CI sets `GPUI_LEAK_DETECTION`; the `leak-detection` feature
// turns it on explicitly.
println!("cargo::rustc-check-cfg=cfg(gpui_leak_detection)");
println!("cargo::rerun-if-env-changed=GPUI_LEAK_DETECTION");
let requested_by_environment =
std::env::var_os("GPUI_LEAK_DETECTION").is_some_and(|value| !value.is_empty());
if requested_by_environment || std::env::var_os("CARGO_FEATURE_LEAK_DETECTION").is_some() {
println!("cargo::rustc-cfg=gpui_leak_detection");
}
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
if target_os == "windows" {
+22 -5
View File
@@ -839,7 +839,7 @@ pub struct App {
// We need to ensure the leak detector drops last, after all tasks, callbacks and things have been dropped.
// Otherwise it may report false positives.
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
_ref_counts: Arc<RwLock<EntityRefCounts>>,
}
@@ -865,7 +865,7 @@ impl App {
let keyboard_layout = platform.keyboard_layout();
let keyboard_mapper = platform.keyboard_mapper();
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
let _ref_counts = entities.ref_counts_drop_handle();
let app = Rc::new_cyclic(|this| AppCell {
@@ -942,7 +942,7 @@ impl App {
element_arena: RefCell::new(Arena::new(1024 * 1024)),
event_arena: Arena::new(1024 * 1024),
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
_ref_counts,
}),
});
@@ -1035,7 +1035,7 @@ impl App {
/// The returned [`LeakDetectorSnapshot`] can later be passed to
/// [`assert_no_new_leaks`](Self::assert_no_new_leaks) to verify that no
/// entities created after the snapshot are still alive.
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
self.entities.leak_detector_snapshot()
}
@@ -1051,11 +1051,22 @@ impl App {
/// Panics if any new entity handles exist. The panic message lists every
/// leaked entity with its type name, and includes allocation-site backtraces
/// when `LEAK_BACKTRACE` is set.
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
self.entities.assert_no_new_leaks(snapshot)
}
/// Without leak detection compiled in, this records nothing.
#[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
LeakDetectorSnapshot::default()
}
/// Without leak detection compiled in, this checks nothing. Set
/// `GPUI_LEAK_DETECTION` when building to enable it.
#[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
/// Quit the application gracefully.
///
/// Native applications give handlers registered with [`Context::on_app_quit`]
@@ -2041,6 +2052,12 @@ impl App {
&self.background_executor
}
/// Whether this app runs on the deterministic test scheduler. See
/// [`BackgroundExecutor::is_test`].
pub fn is_test(&self) -> bool {
self.background_executor.is_test()
}
/// Obtains a reference to the executor, which can be used to spawn futures.
pub fn foreground_executor(&self) -> &ForegroundExecutor {
if self.quitting {
+6
View File
@@ -160,6 +160,12 @@ impl AsyncApp {
&self.background_executor
}
/// Whether this app runs on the deterministic test scheduler. See
/// [`BackgroundExecutor::is_test`].
pub fn is_test(&self) -> bool {
self.background_executor.is_test()
}
/// Get an executor which can be used to spawn futures in the foreground.
pub fn foreground_executor(&self) -> &ForegroundExecutor {
&self.foreground_executor
+32 -26
View File
@@ -21,7 +21,7 @@ use std::{
use super::Context;
use crate::util::atomic_incr_if_not_zero;
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
use collections::HashMap;
slotmap::new_key_type! {
@@ -63,7 +63,7 @@ pub(crate) struct EntityMap {
pub(crate) struct EntityRefCounts {
counts: SlotMap<EntityId, AtomicUsize>,
dropped_entity_ids: Vec<EntityId>,
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
leak_detector: LeakDetector,
}
@@ -79,7 +79,7 @@ impl EntityMap {
ref_counts: Arc::new(RwLock::new(EntityRefCounts {
counts: SlotMap::with_key(),
dropped_entity_ids: Vec::new(),
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
leak_detector: LeakDetector {
next_handle_id: 0,
entity_handles: HashMap::default(),
@@ -98,7 +98,7 @@ impl EntityMap {
/// The returned [`LeakDetectorSnapshot`] can later be passed to
/// [`assert_no_new_leaks`](Self::assert_no_new_leaks) to verify that no
/// entities created after the snapshot are still alive.
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
self.ref_counts.read().leak_detector.snapshot()
}
@@ -106,7 +106,7 @@ impl EntityMap {
/// Asserts that no entities created after `snapshot` still have alive handles.
///
/// See [`LeakDetector::assert_no_new_leaks`] for details.
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
self.ref_counts
.read()
@@ -268,7 +268,7 @@ pub struct AnyEntity {
pub(crate) entity_id: EntityId,
pub(crate) entity_type: TypeId,
entity_map: Weak<RwLock<EntityRefCounts>>,
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
handle_id: HandleId,
}
@@ -277,12 +277,12 @@ impl AnyEntity {
id: EntityId,
entity_type: TypeId,
entity_map: Weak<RwLock<EntityRefCounts>>,
#[cfg(any(test, feature = "leak-detection"))] type_name: &'static str,
#[cfg(any(test, gpui_leak_detection))] type_name: &'static str,
) -> Self {
Self {
entity_id: id,
entity_type,
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
handle_id: entity_map
.clone()
.upgrade()
@@ -345,7 +345,7 @@ impl Clone for AnyEntity {
entity_id: self.entity_id,
entity_type: self.entity_type,
entity_map: self.entity_map.clone(),
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
handle_id: self
.entity_map
.upgrade()
@@ -374,7 +374,7 @@ impl Drop for AnyEntity {
}
}
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
if let Some(entity_map) = self.entity_map.upgrade() {
entity_map
.write()
@@ -452,7 +452,7 @@ impl<T: 'static> Entity<T> {
id,
TypeId::of::<T>(),
entity_map,
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
std::any::type_name::<T>(),
),
entity_type: PhantomData,
@@ -626,7 +626,7 @@ impl AnyWeakEntity {
entity_id: self.entity_id,
entity_type: self.entity_type,
entity_map: self.entity_ref_counts.clone(),
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
handle_id: self
.entity_ref_counts
.upgrade()
@@ -652,11 +652,12 @@ impl AnyWeakEntity {
///
/// # Debugging Leaks
///
/// If this method panics due to leaked handles, set the `LEAK_BACKTRACE` environment
/// variable to see where the leaked handles were allocated:
/// With leak detection enabled (build with `GPUI_LEAK_DETECTION=1`), a failure
/// lists each leaked handle. Also set the `LEAK_BACKTRACE` environment variable
/// to see where they were allocated:
///
/// ```bash
/// LEAK_BACKTRACE=1 cargo test my_test
/// GPUI_LEAK_DETECTION=1 LEAK_BACKTRACE=1 cargo test my_test
/// ```
///
/// # Panics
@@ -664,8 +665,9 @@ impl AnyWeakEntity {
/// - Panics if any strong handles to the entity are still alive.
/// - Panics if the entity was recently dropped but cleanup hasn't completed yet
/// (resources are retained until the end of the effect cycle).
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, feature = "test-support", gpui_leak_detection))]
pub fn assert_released(&self) {
#[cfg(any(test, gpui_leak_detection))]
self.entity_ref_counts
.upgrade()
.unwrap()
@@ -680,7 +682,9 @@ impl AnyWeakEntity {
.is_some()
{
panic!(
"entity was recently dropped but resources are retained until the end of the effect cycle."
"entity is still alive, or was recently dropped and its resources are retained \
until the end of the effect cycle. Build with GPUI_LEAK_DETECTION=1 to list \
its live handles."
)
}
}
@@ -890,7 +894,7 @@ impl<T: 'static> PartialOrd for WeakEntity<T> {
///
/// Set the `LEAK_BACKTRACE` environment variable to any non-empty value to enable
/// backtrace capture. This helps identify where leaked handles were allocated.
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").is_ok_and(|b| !b.is_empty()));
@@ -898,7 +902,7 @@ static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
///
/// This is distinct from `EntityId` - while multiple handles can point to the same
/// entity (same `EntityId`), each handle has its own unique `HandleId`.
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
pub(crate) struct HandleId {
id: u64,
@@ -953,7 +957,7 @@ pub(crate) struct HandleId {
/// `WeakEntity::upgrade`), `handle_created` is called to register the handle.
/// - When a handle is dropped, `handle_released` removes it from tracking.
/// - `assert_released` verifies that no handles remain for a given entity.
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
pub(crate) struct LeakDetector {
next_handle_id: u64,
entity_handles: HashMap<EntityId, EntityLeakData>,
@@ -964,18 +968,20 @@ pub(crate) struct LeakDetector {
/// Created by [`LeakDetector::snapshot`]. Can later be passed to
/// [`LeakDetector::assert_no_new_leaks`] to verify that no new entity
/// handles remain between the snapshot and the current state.
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, feature = "test-support", gpui_leak_detection))]
#[derive(Default)]
pub struct LeakDetectorSnapshot {
#[cfg(any(test, gpui_leak_detection))]
entity_ids: collections::HashSet<EntityId>,
}
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
struct EntityLeakData {
handles: HashMap<HandleId, Option<backtrace::Backtrace>>,
type_name: &'static str,
}
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
impl LeakDetector {
/// Records that a new handle has been created for the given entity.
///
@@ -1106,7 +1112,7 @@ impl LeakDetector {
}
}
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
impl Drop for LeakDetector {
fn drop(&mut self) {
use std::fmt::Write;
@@ -1141,10 +1147,10 @@ impl Drop for LeakDetector {
}
}
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
struct BacktraceFormatter(backtrace::Backtrace);
#[cfg(any(test, feature = "leak-detection"))]
#[cfg(any(test, gpui_leak_detection))]
impl fmt::Debug for BacktraceFormatter {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use backtrace::{BacktraceFmt, BytesOrWideString, PrintFmt};
+9
View File
@@ -281,6 +281,15 @@ impl BackgroundExecutor {
self.dispatcher.is_main_thread()
}
/// Whether this executor runs on the deterministic test scheduler.
///
/// Available in every build. Use it, rather than `cfg(feature =
/// "test-support")`, for behavior that must differ under tests, so that
/// compiling `test-support` into an application doesn't change it.
pub fn is_test(&self) -> bool {
self.inner.is_test()
}
#[doc(hidden)]
pub fn dispatcher(&self) -> &Arc<dyn PlatformDispatcher> {
&self.dispatcher
+4 -2
View File
@@ -180,8 +180,10 @@ impl MetalRenderer {
// https://developer.apple.com/documentation/metal/managing-your-game-window-for-metal-in-macos
layer.set_opaque(!transparent);
layer.set_maximum_drawable_count(3);
// Allow texture reading for visual tests (captures screenshots without ScreenCaptureKit)
#[cfg(any(test, feature = "test-support"))]
// Allow texture reading for visual tests and UI automation screenshots
// (captures without ScreenCaptureKit). Only debug builds pay the
// presentation cost, even when `test-support` is compiled in.
#[cfg(all(feature = "test-support", debug_assertions))]
layer.set_framebuffer_only(false);
// metal-rs doesn't bind these setters, so view the same object through
// objc2's typed CAMetalLayer binding.
+10
View File
@@ -59,6 +59,11 @@ impl LocalExecutor {
&self.scheduler
}
/// Whether this executor runs on a [`TestScheduler`](crate::TestScheduler).
pub fn is_test(&self) -> bool {
self.scheduler.as_test().is_some()
}
#[track_caller]
pub fn spawn<F>(&self, future: F) -> Task<F::Output>
where
@@ -290,6 +295,11 @@ impl BackgroundExecutor {
&self.scheduler
}
/// Whether this executor runs on a [`TestScheduler`](crate::TestScheduler).
pub fn is_test(&self) -> bool {
self.scheduler.as_test().is_some()
}
/// Spawn a closure on a fresh session pinned to its own [`LocalExecutor`].
/// The closure runs on a new OS thread under `PlatformScheduler`, or on
/// the test scheduler's loop under `TestScheduler`.
+14
View File
@@ -8,6 +8,20 @@ pub use clock::*;
pub use executor::*;
pub use test_scheduler::*;
static TEST_SCHEDULER_CREATED: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
/// Whether this process has created a [`TestScheduler`].
///
/// Test harnesses create one before the test body runs, and applications never
/// do. Code with no executor at hand, such as expensive data-structure invariant
/// checks, can use this to run only in test processes. Code that has an
/// executor should prefer [`BackgroundExecutor::is_test`], which is correct per
/// executor.
pub fn test_scheduler_created() -> bool {
TEST_SCHEDULER_CREATED.load(std::sync::atomic::Ordering::Relaxed)
}
use async_task::Runnable;
use futures::channel::oneshot;
use std::{
+1
View File
@@ -159,6 +159,7 @@ impl TestScheduler {
}
pub fn new(config: TestSchedulerConfig) -> Self {
crate::TEST_SCHEDULER_CREATED.store(true, std::sync::atomic::Ordering::Relaxed);
Self {
rng: Arc::new(Mutex::new(StdRng::seed_from_u64(config.seed))),
state: Arc::new(Mutex::new(SchedulerState {
+4 -1
View File
@@ -20,11 +20,14 @@ use path::rel_path::RelPathBuf;
pub use path::PathStyle;
/// Returns the path to the user's home directory.
///
/// This crate's own tests see a fixed fake path. Every other build, including
/// builds with `test-support`, sees the real home directory.
#[cfg(not(target_family = "wasm"))]
pub fn home_dir() -> &'static PathBuf {
static HOME_DIR: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
HOME_DIR.get_or_init(|| {
if cfg!(any(test, feature = "test-support")) {
if cfg!(test) {
if cfg!(target_os = "macos") {
PathBuf::from("/Users/zed")
} else if cfg!(target_os = "windows") {