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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix: prevent capture starvation from DB pool contention
Louis Beaumontcbc5625f14a7
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lockindex 0fab58501..1b26f20c7 100755--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -8097,7 +8097,7 @@ dependencies = [[[package]]name = "screenpipe-app"-version = "2.0.525"+version = "2.0.526"dependencies = ["anyhow","arboard",diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 93f86ebdc..30a379ff9 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.0.525"+version = "2.0.526"description = "24/7 memory for your desktop. 100% local."authors = ["you"]license = ""diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rsindex 5b396a12f..fa3a9f529 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -386,18 +386,39 @@ impl DatabaseManager {/// if not committed (preventing dirty connections from poisoning the pool).pub async fn begin_immediate_with_retry(&self) -> Result<ImmediateTx, sqlx::Error> {// Acquire the write semaphore first — this is where serialization happens.- // Only one task can pass this point at a time.- let permit = Arc::clone(&self.write_semaphore)- .acquire_owned()- .await- .map_err(|_| sqlx::Error::PoolClosed)?;+ // Only one task can pass this point at a time. Use a timeout so captures+ // don't block indefinitely when FTS holds the semaphore waiting for a pool+ // connection (which itself may be blocked by streaming queries).+ let permit = match tokio::time::timeout(+ Duration::from_secs(5),+ Arc::clone(&self.write_semaphore).acquire_owned(),+ )+ .await+ {+ Ok(Ok(permit)) => permit,+ Ok(Err(_)) => return Err(sqlx::Error::PoolClosed),+ Err(_) => {+ return Err(sqlx::Error::PoolTimedOut);+ }+ };// With the semaphore held, BEGIN IMMEDIATE should succeed immediately// since no other writer can be active. Retry only for edge cases// (e.g., checkpoint in progress).let max_retries = 3;for attempt in 1..=max_retries {- let mut conn = self.pool.acquire().await?;+ // Short timeout on pool.acquire — with semaphore held, we don't want+ // to block for 30s waiting for a pool connection.+ let mut conn = match tokio::time::timeout(+ Duration::from_secs(3),+ self.pool.acquire(),+ )+ .await+ {+ Ok(Ok(conn)) => conn,+ Ok(Err(e)) => return Err(e),+ Err(_) => return Err(sqlx::Error::PoolTimedOut),+ };match sqlx::query("BEGIN IMMEDIATE").execute(&mut *conn).await {Ok(_) => {return Ok(ImmediateTx {@@ -423,13 +444,35 @@ impl DatabaseManager {/// Low-priority version of `begin_immediate_with_retry` for background tasks/// like the FTS indexer. Returns `None` if the write semaphore is already held,/// so the caller can skip and retry later instead of blocking real-time captures.+ ///+ /// IMPORTANT: pool.acquire has a short timeout to prevent holding the write+ /// semaphore while waiting for a pool connection. Without this, FTS can hold+ /// the semaphore for up to 30s (pool acquire_timeout), starving captures.pub async fn try_begin_immediate(&self) -> Result<Option<ImmediateTx>, sqlx::Error> {let permit = match Arc::clone(&self.write_semaphore).try_acquire_owned() {Ok(permit) => permit,Err(_) => return Ok(None), // Someone else is writing — yield};- let mut conn = self.pool.acquire().await?;+ // Short timeout on pool.acquire — don't hold the write semaphore while+ // waiting for a pool connection. If the pool is saturated (streaming queries),+ // release the semaphore immediately so captures aren't blocked.+ let conn = match tokio::time::timeout(+ Duration::from_millis(500),+ self.pool.acquire(),+ )+ .await+ {+ Ok(Ok(conn)) => conn,+ Ok(Err(e)) => return Err(e),+ Err(_) => {+ // Pool busy — drop semaphore permit so captures can proceed+ drop(permit);+ return Ok(None);+ }+ };++ let mut conn = conn;match sqlx::query("BEGIN IMMEDIATE").execute(&mut *conn).await {Ok(_) => Ok(Some(ImmediateTx {conn: Some(conn),diff --git a/crates/screenpipe-server/src/event_driven_capture.rs b/crates/screenpipe-server/src/event_driven_capture.rsindex a1e9f4c86..c6f3cff84 100644--- a/crates/screenpipe-server/src/event_driven_capture.rs+++ b/crates/screenpipe-server/src/event_driven_capture.rs@@ -322,18 +322,24 @@ pub async fn event_driven_capture_loop(if let Some(trigger) = trigger {if state.can_capture() {- match do_capture(- &db,- &monitor,- monitor_id,- &device_name,- &snapshot_writer,- &tree_walker_config,- &trigger,+ // Timeout prevents the capture loop from blocking indefinitely+ // when the DB pool is saturated (e.g., FTS backfill + streaming).+ let capture_result = tokio::time::timeout(+ Duration::from_secs(5),+ do_capture(+ &db,+ &monitor,+ monitor_id,+ &device_name,+ &snapshot_writer,+ &tree_walker_config,+ &trigger,+ ),)- .await- {- Ok(result) => {+ .await;++ match capture_result {+ Ok(Ok(result)) => {state.mark_captured();// Feed the captured frame to comparer so we don't@@ -358,7 +364,7 @@ pub async fn event_driven_capture_loop(result.duration_ms);}- Err(e) => {+ Ok(Err(e)) => {error!("event capture failed (trigger={}, monitor={}): {}",trigger.as_str(),@@ -366,6 +372,13 @@ pub async fn event_driven_capture_loop(e);}+ Err(_timeout) => {+ warn!(+ "event capture timed out (trigger={}, monitor={}) — DB pool may be saturated",+ trigger.as_str(),+ monitor_id+ );+ }}} else {debug!(