Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(macOS): wrap list_monitors + focus-tracker callbacks in autorelease pool

Louis Beaumont8f8e1e8192a6
diff --git a/crates/screenpipe-engine/src/focus_tracker/darwin.rs b/crates/screenpipe-engine/src/focus_tracker/darwin.rs
index 06801d7ab..f0ffafcba 100644
--- a/crates/screenpipe-engine/src/focus_tracker/darwin.rs
+++ b/crates/screenpipe-engine/src/focus_tracker/darwin.rs
@@ -271,11 +271,21 @@ fn run_workspace_observer(inner: Arc<Inner>) {
// does a cheap CG call + a monitor list lookup.
let inner_activate = Arc::clone(&inner);
let activate_cb = move |_note: &ns::Notification| {
- // Fetch the current monitor list synchronously. This call can
- // block briefly (sck-rs query); the observer thread doesn't need
- // to be snappy — tokio workers aren't starved by it.
- let monitors = futures::executor::block_on(screenpipe_screen::monitor::list_monitors());
- inner_activate.resolve_and_emit(&monitors);
+ // Wrap in autorelease pool — this callback runs on a custom
+ // std::thread driven by CFRunLoopRun, which does NOT drain the
+ // per-thread autorelease pool between iterations (unlike the
+ // main Cocoa event loop). Without this, every notification
+ // retains an NSNotification + any transient NSObjects from
+ // `list_monitors` forever.
+ cidre::objc::ar_pool(|| {
+ // Fetch the current monitor list synchronously. This call
+ // can block briefly (sck-rs query); the observer thread
+ // doesn't need to be snappy — tokio workers aren't starved
+ // by it.
+ let monitors =
+ futures::executor::block_on(screenpipe_screen::monitor::list_monitors());
+ inner_activate.resolve_and_emit(&monitors);
+ });
};
let _activate_guard = nc.add_observer_guard(
ns::workspace::notification::did_activate_app(),
@@ -286,8 +296,12 @@ fn run_workspace_observer(inner: Arc<Inner>) {
let inner_space = Arc::clone(&inner);
let space_cb = move |_note: &ns::Notification| {
- let monitors = futures::executor::block_on(screenpipe_screen::monitor::list_monitors());
- inner_space.resolve_and_emit(&monitors);
+ // Same autorelease-pool wrap as activate_cb above.
+ cidre::objc::ar_pool(|| {
+ let monitors =
+ futures::executor::block_on(screenpipe_screen::monitor::list_monitors());
+ inner_space.resolve_and_emit(&monitors);
+ });
};
let _space_guard = nc.add_observer_guard(
ns::workspace::notification::active_space_did_change(),
diff --git a/crates/screenpipe-screen/src/monitor.rs b/crates/screenpipe-screen/src/monitor.rs
index f25211ca8..b571fac26 100644
--- a/crates/screenpipe-screen/src/monitor.rs
+++ b/crates/screenpipe-screen/src/monitor.rs
@@ -737,39 +737,58 @@ fn update_monitor_cache(monitors: &[SafeMonitor]) {
/// List monitors with detailed error information (permission denied vs no monitors)
#[cfg(target_os = "macos")]
pub async fn list_monitors_detailed() -> std::result::Result<Vec<SafeMonitor>, MonitorListError> {
+ // Wrap the ObjC call paths in an autorelease pool — SckMonitor::all() and
+ // XcapMonitor::all() both allocate autoreleased NSObjects (display
+ // descriptors, NSStrings). Tokio blocking workers are long-lived and
+ // reused; without a per-call drain these accumulate forever.
+ // See monitor::tests::repro_list_monitors_autorelease_leak.
let result: std::result::Result<Vec<SafeMonitor>, MonitorListError> =
tokio::task::spawn_blocking(|| {
- if use_sck_rs() {
- tracing::debug!("Using sck-rs for screen capture (macOS 12.3+)");
- match SckMonitor::all() {
- Ok(monitors) if monitors.is_empty() => Err(MonitorListError::NoMonitorsFound),
- Ok(monitors) => Ok(monitors.into_iter().map(SafeMonitor::from_sck).collect()),
- Err(e) => {
- let err_str = e.to_string();
- if err_str.contains("permission") || err_str.contains("Screen recording") {
- Err(MonitorListError::PermissionDenied)
- } else if err_str.contains("No monitors") {
+ cidre::objc::ar_pool(|| {
+ if use_sck_rs() {
+ tracing::debug!("Using sck-rs for screen capture (macOS 12.3+)");
+ match SckMonitor::all() {
+ Ok(monitors) if monitors.is_empty() => {
Err(MonitorListError::NoMonitorsFound)
- } else {
- Err(MonitorListError::Other(err_str))
+ }
+ Ok(monitors) => {
+ Ok(monitors.into_iter().map(SafeMonitor::from_sck).collect())
+ }
+ Err(e) => {
+ let err_str = e.to_string();
+ if err_str.contains("permission")
+ || err_str.contains("Screen recording")
+ {
+ Err(MonitorListError::PermissionDenied)
+ } else if err_str.contains("No monitors") {
+ Err(MonitorListError::NoMonitorsFound)
+ } else {
+ Err(MonitorListError::Other(err_str))
+ }
}
}
- }
- } else {
- tracing::info!("Using xcap fallback for screen capture (macOS < 12.3)");
- match XcapMonitor::all() {
- Ok(monitors) if monitors.is_empty() => Err(MonitorListError::NoMonitorsFound),
- Ok(monitors) => Ok(monitors.into_iter().map(SafeMonitor::from_xcap).collect()),
- Err(e) => {
- let err_str = e.to_string();
- if err_str.contains("permission") || err_str.contains("Screen recording") {
- Err(MonitorListError::PermissionDenied)
- } else {
- Err(MonitorListError::Other(err_str))
+ } else {
+ tracing::info!("Using xcap fallback for screen capture (macOS < 12.3)");
+ match XcapMonitor::all() {
+ Ok(monitors) if monitors.is_empty() => {
+ Err(MonitorListError::NoMonitorsFound)
+ }
+ Ok(monitors) => {
+ Ok(monitors.into_iter().map(SafeMonitor::from_xcap).collect())
+ }
+ Err(e) => {
+ let err_str = e.to_string();
+ if err_str.contains("permission")
+ || err_str.contains("Screen recording")
+ {
+ Err(MonitorListError::PermissionDenied)
+ } else {
+ Err(MonitorListError::Other(err_str))
+ }
}
}
}
- }
+ })
})
.await
.unwrap_or(Err(MonitorListError::Other("Task panicked".to_string())));
@@ -1058,4 +1077,125 @@ mod tests {
assert!(disabled.load(Ordering::Relaxed));
assert_eq!(failures.load(Ordering::Relaxed), 3);
}
+
+ /// Reproduction for the macOS memory leak reported 2026-04-22
+ /// (user's screenpipe at 13.2 GB RSS after ~48 h).
+ ///
+ /// Hypothesis: `list_monitors_detailed` calls `SckMonitor::all()` inside
+ /// `spawn_blocking` WITHOUT wrapping in `cidre::objc::ar_pool(...)`. Every
+ /// call therefore leaks autoreleased ObjC objects on the tokio blocking
+ /// worker threads (which are long-lived and reused).
+ ///
+ /// This test drives the leak path 2000× twice: once as-written (leaking),
+ /// once wrapped in `ar_pool` (expected not to leak). It reports peak RSS
+ /// (`ru_maxrss`) after each phase. On a leaked build, phase 1 should show
+ /// hundreds of MB of growth; phase 2 should be essentially flat.
+ ///
+ /// Kept `#[ignore]` because it's a perf/memory repro, not a correctness
+ /// test — run with:
+ /// cargo test -p screenpipe-screen --lib monitor::tests::repro_list_monitors_autorelease_leak -- --ignored --nocapture
+ #[cfg(target_os = "macos")]
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ #[ignore = "macOS memory-leak repro; prints RSS deltas"]
+ async fn repro_list_monitors_autorelease_leak() {
+ /// Peak resident memory in bytes (ru_maxrss is bytes on Darwin,
+ /// despite the rusage man page claiming KB).
+ fn peak_rss_bytes() -> u64 {
+ unsafe {
+ let mut ru: libc::rusage = std::mem::zeroed();
+ libc::getrusage(libc::RUSAGE_SELF, &mut ru);
+ ru.ru_maxrss as u64
+ }
+ }
+
+ fn fmt_mb(b: u64) -> String {
+ format!("{:.1} MB", (b as f64) / (1024.0 * 1024.0))
+ }
+
+ // 5 k calls × ~2.4 kB/call ≈ 12 MB growth — enough to rise cleanly
+ // out of noise. Real production hits this path tens of thousands of
+ // times per day across callers (focus-tracker safety-net poll every
+ // 5 s, monitor-watcher backstop every 60 s, focus callbacks, etc.).
+ const N: usize = 5_000;
+
+ let baseline = peak_rss_bytes();
+ eprintln!("[repro] baseline peak RSS: {}", fmt_mb(baseline));
+
+ // ── Phase 1: drive the code path AS-WRITTEN (should leak) ──
+ // We call `SckMonitor::all()` directly on a tokio blocking worker,
+ // matching what `list_monitors_detailed` does today (line ~744).
+ let before_phase1 = peak_rss_bytes();
+ for _ in 0..N {
+ tokio::task::spawn_blocking(|| {
+ // No ar_pool — matches current production path in
+ // list_monitors_detailed on macOS.
+ let _ = sck_rs::Monitor::all();
+ })
+ .await
+ .unwrap();
+ }
+ let after_phase1 = peak_rss_bytes();
+ let delta1 = after_phase1.saturating_sub(before_phase1);
+ eprintln!(
+ "[repro] after {} calls WITHOUT ar_pool: {} (+{} growth)",
+ N,
+ fmt_mb(after_phase1),
+ fmt_mb(delta1)
+ );
+
+ // ── Phase 2: same but wrapped in ar_pool (expected fix) ──
+ let before_phase2 = peak_rss_bytes();
+ for _ in 0..N {
+ tokio::task::spawn_blocking(|| {
+ cidre::objc::ar_pool(|| {
+ let _ = sck_rs::Monitor::all();
+ });
+ })
+ .await
+ .unwrap();
+ }
+ let after_phase2 = peak_rss_bytes();
+ let delta2 = after_phase2.saturating_sub(before_phase2);
+ eprintln!(
+ "[repro] after {} calls WITH ar_pool: {} (+{} growth)",
+ N,
+ fmt_mb(after_phase2),
+ fmt_mb(delta2)
+ );
+
+ eprintln!(
+ "[repro] leak delta (phase1 − phase2): {}",
+ fmt_mb(delta1.saturating_sub(delta2))
+ );
+
+ // Hypothesis: phase 1 leaks, phase 2 doesn't. `ru_maxrss` is peak-only
+ // so phase 2 cannot shrink below phase 1 — we check that phase 2
+ // grew far less than phase 1.
+ //
+ // Thresholds tuned from 2026-04-22 runs on M4 Max:
+ // phase 1 (no ar_pool): ~4–5 MB growth and PLATEAUS (ObjC runtime
+ // dedupes repeated NSString / CFArray instances describing the
+ // same displays, so per-call overhead shrinks after the first
+ // few hundred calls).
+ // phase 2 (ar_pool): 0 MB growth (drained per call).
+ //
+ // The ~5 MB observed here is ONLY the `list_monitors_detailed`
+ // contribution in isolation. The user-report 13 GB / 48 h leak is
+ // almost certainly dominated by OTHER un-pooled cidre/cg callers
+ // (NSWorkspace observer thread in focus_tracker/darwin.rs,
+ // per-notification NSNotification retention, AX tree walks, etc.).
+ // This repro proves the CLASS of bug; it does not reproduce the
+ // full magnitude.
+ assert!(
+ delta1 > 2 * 1024 * 1024,
+ "expected >2 MB growth without ar_pool; got only {} — leak hypothesis not confirmed",
+ fmt_mb(delta1)
+ );
+ assert!(
+ delta1 > 3 * delta2,
+ "phase 1 should leak ≥3× phase 2; got phase1={}, phase2={}",
+ fmt_mb(delta1),
+ fmt_mb(delta2)
+ );
+ }
}