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

perf(capture): release idle monitor capture streams to halve replayd/WGC cost

Louis Beaumont6baba5cd5e17
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index efda45f4f..ff93b2701 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "2.4.21"
+version = "2.4.22"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/crates/screenpipe-db/src/write_queue.rs b/crates/screenpipe-db/src/write_queue.rs
index 653c70c0b..653d56847 100644
--- a/crates/screenpipe-db/src/write_queue.rs
+++ b/crates/screenpipe-db/src/write_queue.rs
@@ -30,9 +30,6 @@ use tracing::{debug, error, info, warn};
/// the write lock too long and starving readers.
const MAX_BATCH_SIZE: usize = 500;
-/// How often the drain loop wakes up to flush buffered writes.
-const DRAIN_INTERVAL: Duration = Duration::from_millis(100);
-
/// Channel capacity. 4096 provides headroom for burst writes without
/// backpressure reaching capture threads.
const CHANNEL_CAPACITY: usize = 4096;
@@ -375,28 +372,17 @@ async fn drain_loop(
write_pool: Pool<Sqlite>,
write_semaphore: Arc<Semaphore>,
) {
- let mut batch: Vec<PendingWrite> = Vec::with_capacity(256);
- let mut interval = tokio::time::interval(DRAIN_INTERVAL);
- interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ let mut batch: Vec<PendingWrite> = Vec::with_capacity(MAX_BATCH_SIZE);
loop {
- // Wait for either: interval tick OR first write arriving
- tokio::select! {
- _ = interval.tick() => {},
- item = rx.recv() => {
- match item {
- Some(pw) => batch.push(pw),
- None => break, // channel closed = shutdown
- }
- }
- }
-
- // Drain all currently buffered writes (non-blocking)
- while batch.len() < MAX_BATCH_SIZE {
- match rx.try_recv() {
- Ok(pw) => batch.push(pw),
- Err(_) => break,
- }
+ // Block until at least one write arrives, then take up to MAX_BATCH_SIZE
+ // in a single atomic call. No periodic wake-ups — the previous
+ // `tokio::select!` + 100ms interval added nothing under load (recv
+ // usually won the race anyway) and cost idle wake-ups otherwise.
+ let n = rx.recv_many(&mut batch, MAX_BATCH_SIZE).await;
+ if n == 0 {
+ // Channel closed — all senders dropped.
+ break;
}
// ── Sleep/wake pause gate ──
@@ -404,12 +390,10 @@ async fn drain_loop(
// until resumed. This prevents WAL corruption from I/O errors
// during sleep transitions.
if WRITE_PAUSED.load(Ordering::SeqCst) {
- if !batch.is_empty() {
- info!(
- "write_queue: paused for sleep, holding {} writes",
- batch.len()
- );
- }
+ info!(
+ "write_queue: paused for sleep, holding {} writes",
+ batch.len()
+ );
let notify = RESUME_NOTIFY.get_or_init(|| tokio::sync::Notify::new());
tokio::select! {
_ = notify.notified() => {
@@ -420,31 +404,23 @@ async fn drain_loop(
WRITE_PAUSED.store(false, Ordering::SeqCst);
}
}
- continue;
- }
-
- if batch.is_empty() {
- continue;
}
- let batch_size = batch.len();
- debug!("write_queue: draining batch of {} writes", batch_size);
-
+ debug!("write_queue: draining batch of {} writes", batch.len());
execute_batch(&write_pool, &write_semaphore, &mut batch).await;
batch.clear();
}
// Shutdown: drain remaining writes
rx.close();
- while let Some(pw) = rx.recv().await {
- batch.push(pw);
- }
- if !batch.is_empty() {
+ let mut tail_batch: Vec<PendingWrite> = Vec::with_capacity(MAX_BATCH_SIZE);
+ while rx.recv_many(&mut tail_batch, MAX_BATCH_SIZE).await > 0 {
debug!(
"write_queue: shutdown — flushing {} remaining writes",
- batch.len()
+ tail_batch.len()
);
- execute_batch(&write_pool, &write_semaphore, &mut batch).await;
+ execute_batch(&write_pool, &write_semaphore, &mut tail_batch).await;
+ tail_batch.clear();
}
debug!("write_queue: drain loop exited");
}
diff --git a/crates/screenpipe-engine/src/event_driven_capture.rs b/crates/screenpipe-engine/src/event_driven_capture.rs
index 39e87154b..04dcd755c 100644
--- a/crates/screenpipe-engine/src/event_driven_capture.rs
+++ b/crates/screenpipe-engine/src/event_driven_capture.rs
@@ -359,6 +359,14 @@ pub async fn event_driven_capture_loop(
// or disappears. Only update when the sorted set actually changes.
let mut cached_excluded_ids: Vec<u32> = Vec::new();
+ // Track whether this monitor is currently in Cold state so we release
+ // its OS-level capture session exactly once per Active/Warm → Cold edge.
+ // Without this, a non-focused monitor's persistent stream keeps the OS
+ // capture service busy at the stream's frame interval forever (replayd
+ // at 2fps on macOS, WGC on Windows) — measurable share of a core per
+ // idle display on multi-monitor setups.
+ let mut was_cold = false;
+
loop {
if stop_signal.load(Ordering::Relaxed) {
info!("event-driven capture stopping for monitor {}", monitor_id);
@@ -379,7 +387,18 @@ pub async fn event_driven_capture_loop(
let mut warm_trigger_override: Option<CaptureTrigger> = None;
{
use crate::focus_aware_controller::CaptureState;
- match focus_controller.state(monitor_id) {
+ let capture_state = focus_controller.state(monitor_id);
+
+ // Fires exactly once per focus-away transition, not every Cold
+ // loop iteration, so the log line is meaningful and we don't
+ // churn sck-rs / WGC locks.
+ let is_cold = matches!(capture_state, CaptureState::Cold);
+ if is_cold && !was_cold {
+ monitor.release_capture_stream();
+ }
+ was_cold = is_cold;
+
+ match capture_state {
CaptureState::Active => { /* fall through to normal capture */ }
CaptureState::Warm => {
// Cheap visual-diff-only cadence: capture only if pixels
diff --git a/crates/screenpipe-screen/src/lib.rs b/crates/screenpipe-screen/src/lib.rs
index c473c1714..64eb21d14 100644
--- a/crates/screenpipe-screen/src/lib.rs
+++ b/crates/screenpipe-screen/src/lib.rs
@@ -56,4 +56,11 @@ pub mod stream_invalidation {
pub fn invalidate_streams() {
sck_rs::stop_all_streams();
}
+
+ /// Stop the persistent SCStream for a single monitor. Used when a monitor
+ /// goes Cold so `replayd` stops capturing frames we're not reading. The
+ /// stream is lazily recreated on the next capture call after focus returns.
+ pub fn invalidate_monitor_stream(monitor_id: u32) {
+ sck_rs::invalidate_monitor_stream(monitor_id);
+ }
}
diff --git a/crates/screenpipe-screen/src/monitor.rs b/crates/screenpipe-screen/src/monitor.rs
index a8f026996..f25211ca8 100644
--- a/crates/screenpipe-screen/src/monitor.rs
+++ b/crates/screenpipe-screen/src/monitor.rs
@@ -643,6 +643,40 @@ impl SafeMonitor {
self.monitor_data.y
}
+ /// Release the OS-level persistent capture session for this monitor.
+ ///
+ /// Called by the capture loop when focus has been absent long enough that
+ /// we don't expect to read frames soon (Cold state). Without this, the
+ /// underlying OS service keeps capturing at the stream's frame interval
+ /// forever — on macOS that's `replayd` at 2fps per idle monitor, which is
+ /// a measurable share of a core on dual-display setups.
+ ///
+ /// The session is lazily recreated on the next `capture_image()` call
+ /// after focus returns. Session-level disable/failure counters on Windows
+ /// are NOT reset — those reflect long-term stability, not transient
+ /// focus state.
+ ///
+ /// Safe to call when no session exists. Cheap.
+ pub fn release_capture_stream(&self) {
+ #[cfg(target_os = "macos")]
+ {
+ crate::stream_invalidation::invalidate_monitor_stream(self.monitor_id);
+ }
+ #[cfg(target_os = "windows")]
+ {
+ if let Ok(mut guard) = self.persistent_capture.lock() {
+ if let Some(mut capture) = guard.take() {
+ capture.stop();
+ tracing::info!(
+ "released persistent WGC session for monitor {}",
+ self.monitor_id
+ );
+ }
+ }
+ }
+ // Linux: xcap captures per-frame, no persistent session to release.
+ }
+
#[cfg(target_os = "windows")]
fn record_persistent_init_failure(
monitor_id: u32,