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: eliminate DB write contention causing vision stalls
Louis Beaumont39c016cb34d7
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rsindex c4993cb55..e5a0c0261 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -1813,7 +1813,7 @@ impl DatabaseManager {return Ok(vec![]);}- // Read the latest video_chunk OUTSIDE the write transaction.+ // Read the latest video_chunk OUTSIDE the write queue.// This SELECT only needs a shared read lock, not the exclusive write lock.// Moving it out reduces write lock hold time significantly.let video_chunk: Option<(i64, String)> = sqlx::query_as(@@ -1836,66 +1836,48 @@ impl DatabaseManager {let timestamp = timestamp.unwrap_or_else(Utc::now);let ocr_engine_str = format!("{:?}", *ocr_engine);- let mut results = Vec::with_capacity(windows.len());-- // Now acquire the write lock — only INSERTs run inside the transaction.- let mut tx = self.begin_immediate_with_retry().await?;- for (idx, window) in windows.iter().enumerate() {- // Compute full_text for FTS indexing- let full_text = if window.text.is_empty() {- None- } else {- Some(window.text.as_str())- };-- // Insert frame- let frame_id = sqlx::query(- "INSERT INTO frames (video_chunk_id, offset_index, timestamp, name, browser_url, app_name, window_name, focused, device_name, full_text) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",- )- .bind(video_chunk_id)- .bind(offset_index)- .bind(timestamp)- .bind(&file_path)- .bind(window.browser_url.as_deref())- .bind(window.app_name.as_deref())- .bind(window.window_name.as_deref())- .bind(window.focused)- .bind(device_name)- .bind(full_text)- .execute(&mut **tx.conn())- .await?- .last_insert_rowid();+ // Build owned window data for the queue+ let batch_windows: Vec<crate::write_queue::FrameBatchWindow> = windows+ .iter()+ .map(|w| crate::write_queue::FrameBatchWindow {+ app_name: w.app_name.clone(),+ window_name: w.window_name.clone(),+ browser_url: w.browser_url.clone(),+ focused: w.focused,+ text: w.text.clone(),+ text_json: w.text_json.clone(),+ })+ .collect();- // Insert OCR text- let text_length = window.text.len() as i64;- sqlx::query(- "INSERT INTO ocr_text (frame_id, text, text_json, ocr_engine, text_length) VALUES (?1, ?2, ?3, ?4, ?5)",- )- .bind(frame_id)- .bind(&window.text)- .bind(&window.text_json)- .bind(&ocr_engine_str)- .bind(text_length)- .execute(&mut **tx.conn())+ // Submit through the write queue instead of acquiring the write lock directly.+ let result = self+ .write_queue+ .submit(crate::write_queue::WriteOp::InsertFramesBatch {+ video_chunk_id,+ file_path,+ device_name: device_name.to_string(),+ timestamp,+ offset_index,+ ocr_engine_str,+ windows: batch_windows,+ }).await?;- // Dual-write: insert OCR elements into unified elements table- if !window.text_json.is_empty() {- Self::insert_ocr_elements(tx.conn(), frame_id, &window.text_json).await;+ match result {+ crate::write_queue::WriteResult::FrameBatch(results) => {+ debug!(+ "Batch inserted {} frames with OCR for device {}",+ results.len(),+ device_name+ );+ Ok(results)+ }+ _ => {+ tracing::warn!("Unexpected WriteResult variant from InsertFramesBatch");+ Ok(vec![])}-- results.push((frame_id, idx));}-- tx.commit().await?;- debug!(- "Batch inserted {} frames with OCR for device {}",- results.len(),- device_name- );-- Ok(results)}/// Insert multiple frames (each with their own offset and windows) in a singlediff --git a/crates/screenpipe-db/src/lib.rs b/crates/screenpipe-db/src/lib.rsindex 46d4ce648..4e4c59d15 100644--- a/crates/screenpipe-db/src/lib.rs+++ b/crates/screenpipe-db/src/lib.rs@@ -11,6 +11,7 @@ pub(crate) mod write_queue;pub use db::{find_matching_a11y_positions, parse_all_text_positions, DatabaseManager, DeleteTimeRangeResult,+ ImmediateTx,};pub use migration_worker::{create_migration_worker, MigrationCommand, MigrationConfig, MigrationResponse, MigrationStatus,diff --git a/crates/screenpipe-db/src/write_queue.rs b/crates/screenpipe-db/src/write_queue.rsindex f9f43fda5..ad0d58991 100644--- a/crates/screenpipe-db/src/write_queue.rs+++ b/crates/screenpipe-db/src/write_queue.rs@@ -141,6 +141,30 @@ pub(crate) enum WriteOp {chunk_id: i64,batch: Vec<(i64, u32)>,},+ /// Batch insert frames with OCR text. Replaces the direct+ /// `begin_immediate_with_retry` call in `insert_frames_with_ocr_batch`+ /// so that frame inserts go through the coalescing queue.+ InsertFramesBatch {+ video_chunk_id: i64,+ file_path: String,+ device_name: String,+ timestamp: chrono::DateTime<chrono::Utc>,+ offset_index: i64,+ ocr_engine_str: String,+ /// Each entry: (app_name, window_name, browser_url, focused, text, text_json)+ windows: Vec<FrameBatchWindow>,+ },+}++/// Data for a single window in a batch frame insert.+#[derive(Debug, Clone)]+pub(crate) struct FrameBatchWindow {+ pub app_name: Option<String>,+ pub window_name: Option<String>,+ pub browser_url: Option<String>,+ pub focused: bool,+ pub text: String,+ pub text_json: String,}/// Which table to mark as synced.@@ -160,6 +184,8 @@ pub(crate) enum WriteResult {/// For operations that return nothing meaningful.#[allow(dead_code)]Unit,+ /// Result of InsertFramesBatch: Vec of (frame_id, window_index) pairs.+ FrameBatch(Vec<(i64, usize)>),}/// A pending write: the operation plus a channel to send the result back.@@ -659,6 +685,63 @@ async fn execute_single_write(Ok(WriteResult::Unit)}+ WriteOp::InsertFramesBatch {+ video_chunk_id,+ file_path,+ device_name,+ timestamp,+ offset_index,+ ocr_engine_str,+ windows,+ } => {+ let mut results = Vec::with_capacity(windows.len());+ for (idx, window) in windows.iter().enumerate() {+ let full_text = if window.text.is_empty() {+ None+ } else {+ Some(window.text.as_str())+ };++ let frame_id = sqlx::query(+ "INSERT INTO frames (video_chunk_id, offset_index, timestamp, name, browser_url, app_name, window_name, focused, device_name, full_text) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",+ )+ .bind(video_chunk_id)+ .bind(offset_index)+ .bind(timestamp)+ .bind(file_path.as_str())+ .bind(window.browser_url.as_deref())+ .bind(window.app_name.as_deref())+ .bind(window.window_name.as_deref())+ .bind(window.focused)+ .bind(device_name.as_str())+ .bind(full_text)+ .execute(&mut **conn)+ .await?+ .last_insert_rowid();++ // Insert OCR text+ let text_length = window.text.len() as i64;+ sqlx::query(+ "INSERT INTO ocr_text (frame_id, text, text_json, ocr_engine, text_length) VALUES (?1, ?2, ?3, ?4, ?5)",+ )+ .bind(frame_id)+ .bind(&window.text)+ .bind(&window.text_json)+ .bind(ocr_engine_str.as_str())+ .bind(text_length)+ .execute(&mut **conn)+ .await?;++ // Dual-write: insert OCR elements into unified elements table+ if !window.text_json.is_empty() {+ crate::db::DatabaseManager::insert_ocr_elements(conn, frame_id, &window.text_json).await;+ }++ results.push((frame_id, idx));+ }+ Ok(WriteResult::FrameBatch(results))+ }+WriteOp::CompactSnapshots { chunk_id, batch } => {if batch.is_empty() { return Ok(WriteResult::Unit); }let placeholders: Vec<String> = batch.iter().map(|_| "?".to_string()).collect();diff --git a/crates/screenpipe-engine/src/sync_provider.rs b/crates/screenpipe-engine/src/sync_provider.rsindex 798cc40fb..430725bc8 100644--- a/crates/screenpipe-engine/src/sync_provider.rs+++ b/crates/screenpipe-engine/src/sync_provider.rs@@ -453,6 +453,8 @@ impl ScreenpipeSyncProvider {}/// Import a sync chunk from another machine into the local database.+ /// All INSERTs run inside a single transaction to avoid repeated WAL lock+ /// acquisitions. Existence checks (SELECTs) use the read pool.pub async fn import_chunk(&self, chunk: &SyncChunk) -> SyncResult<ImportResult> {let pool = &self.db.pool;let mut imported_frames = 0;@@ -477,9 +479,14 @@ impl ScreenpipeSyncProvider {});}+ // Acquire a single write transaction for ALL inserts+ let mut tx = self.db.begin_immediate_with_retry().await.map_err(|e| {+ SyncError::Database(format!("failed to begin import transaction: {}", e))+ })?;+// Import framesfor frame in &chunk.frames {- // Check if already exists+ // Check if already exists (read-only, uses read pool)let exists: Option<(i64,)> = sqlx::query_as("SELECT id FROM frames WHERE sync_id = ?").bind(&frame.sync_id).fetch_optional(pool)@@ -504,7 +511,7 @@ impl ScreenpipeSyncProvider {.bind(&frame.device_name).bind(&frame.sync_id).bind(&chunk.machine_id)- .fetch_optional(pool)+ .fetch_optional(&mut **tx.conn()).await.map_err(|e| SyncError::Database(format!("failed to create video_chunk: {}", e)))?.unwrap_or(0);@@ -531,14 +538,17 @@ impl ScreenpipeSyncProvider {.bind(&frame.sync_id).bind(&chunk.machine_id).bind(Utc::now().to_rfc3339())- .execute(pool)+ .execute(&mut **tx.conn()).await.map_err(|e| SyncError::Database(format!("failed to insert frame: {}", e)))?;imported_frames += 1;}- // Build sync_id to local frame_id map+ // Yield to let other async tasks progress after frames section+ tokio::task::yield_now().await;++ // Build sync_id to local frame_id map (read-only, uses read pool)let frame_sync_ids: Vec<String> = chunk.frames.iter().map(|f| f.sync_id.clone()).collect();let frame_id_map: std::collections::HashMap<String, i64> = if !frame_sync_ids.is_empty() {sqlx::query_as::<_, (String, i64)>(@@ -564,7 +574,7 @@ impl ScreenpipeSyncProvider {// Import OCRfor ocr in &chunk.ocr_records {if let Some(&frame_id) = frame_id_map.get(&ocr.frame_sync_id) {- // Check if already exists+ // Check if already exists (read-only, uses read pool)let exists: Option<(i64,)> =sqlx::query_as("SELECT 1 FROM ocr_text WHERE sync_id = ?").bind(&ocr.sync_id)@@ -603,7 +613,7 @@ impl ScreenpipeSyncProvider {.bind(window_name).bind(&ocr.sync_id).bind(Utc::now().to_rfc3339())- .execute(pool)+ .execute(&mut **tx.conn()).await.map_err(|e| SyncError::Database(format!("failed to insert OCR: {}", e)))?;@@ -613,9 +623,12 @@ impl ScreenpipeSyncProvider {}}+ // Yield to let other async tasks progress after OCR section+ tokio::task::yield_now().await;+// Import transcriptionsfor trans in &chunk.transcriptions {- // Check if already exists+ // Check if already exists (read-only, uses read pool)let exists: Option<(i64,)> =sqlx::query_as("SELECT 1 FROM audio_transcriptions WHERE sync_id = ?").bind(&trans.sync_id)@@ -643,7 +656,7 @@ impl ScreenpipeSyncProvider {.bind(&trans.sync_id).bind(&trans.sync_id).bind(&chunk.machine_id)- .fetch_one(pool)+ .fetch_one(&mut **tx.conn()).await.map_err(|e| SyncError::Database(format!("failed to create audio_chunk: {}", e)))?;@@ -661,18 +674,21 @@ impl ScreenpipeSyncProvider {.bind(trans.speaker_id).bind(&trans.sync_id).bind(Utc::now().to_rfc3339())- .execute(pool)+ .execute(&mut **tx.conn()).await.map_err(|e| SyncError::Database(format!("failed to insert transcription: {}", e)))?;imported_transcriptions += 1;}+ // Yield to let other async tasks progress after transcriptions section+ tokio::task::yield_now().await;+// Import accessibility records — insert as frames with full_text// (accessibility table was dropped; text now lives in frames.full_text)let mut imported_accessibility = 0;for acc in &chunk.accessibility_records {- // Check if already imported via sync_id on frames+ // Check if already imported via sync_id on frames (read-only, uses read pool)let exists: Option<(i64,)> = sqlx::query_as("SELECT 1 FROM frames WHERE sync_id = ?").bind(&acc.sync_id).fetch_optional(pool)@@ -700,7 +716,7 @@ impl ScreenpipeSyncProvider {.bind(&acc.sync_id).bind(&chunk.machine_id).bind(Utc::now().to_rfc3339())- .execute(pool)+ .execute(&mut **tx.conn()).await.map_err(|e| {SyncError::Database(format!("failed to insert accessibility as frame: {}", e))@@ -709,10 +725,13 @@ impl ScreenpipeSyncProvider {imported_accessibility += 1;}+ // Yield to let other async tasks progress after accessibility section+ tokio::task::yield_now().await;+// Import UI eventslet mut imported_ui_events = 0;for event in &chunk.ui_events {- // Check if already exists+ // Check if already exists (read-only, uses read pool)let exists: Option<(i64,)> =sqlx::query_as("SELECT 1 FROM ui_events WHERE sync_id = ?").bind(&event.sync_id)@@ -764,13 +783,18 @@ impl ScreenpipeSyncProvider {.bind(&event.sync_id).bind(&chunk.machine_id).bind(Utc::now().to_rfc3339())- .execute(pool)+ .execute(&mut **tx.conn()).await.map_err(|e| SyncError::Database(format!("failed to insert ui_event: {}", e)))?;imported_ui_events += 1;}+ // Commit the single transaction for all inserts+ tx.commit().await.map_err(|e| {+ SyncError::Database(format!("failed to commit import transaction: {}", e))+ })?;+Ok(ImportResult {imported_frames,imported_ocr,