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: reduce frame drops — batch DB writes, increase timeout, improve health detection
Louis Beaumontcf16e997a296
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rsindex 3bf614588..fc91ecfb6 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -967,6 +967,92 @@ impl DatabaseManager {Ok(results)}+ /// Insert multiple frames (each with their own offset and windows) in a single+ /// transaction. This acquires the write semaphore once instead of once-per-frame,+ /// reducing contention from ~10 acquisitions/min to ~2/min.+ ///+ /// Returns one Vec<(frame_id, window_idx)> per input frame, in order.+ pub async fn insert_multi_frames_with_ocr_batch(+ &self,+ device_name: &str,+ frames: &[(chrono::DateTime<chrono::Utc>, i64, Vec<FrameWindowData>)],+ ocr_engine: Arc<OcrEngine>,+ ) -> Result<Vec<Vec<(i64, usize)>>, sqlx::Error> {+ if frames.is_empty() {+ return Ok(vec![]);+ }++ // Read the latest video_chunk OUTSIDE the write transaction.+ let video_chunk: Option<(i64, String)> = sqlx::query_as(+ "SELECT id, file_path FROM video_chunks WHERE device_name = ?1 ORDER BY id DESC LIMIT 1",+ )+ .bind(device_name)+ .fetch_optional(&self.pool)+ .await?;++ let (video_chunk_id, file_path) = match video_chunk {+ Some((id, path)) => (id, path),+ None => {+ tracing::warn!(+ "No video chunk found for device '{}' — frames will not be inserted",+ device_name+ );+ return Ok(vec![]);+ }+ };++ let ocr_engine_str = format!("{:?}", *ocr_engine);+ let mut all_results = Vec::with_capacity(frames.len());++ // Single transaction for all frames — one semaphore acquisition.+ let mut tx = self.begin_immediate_with_retry().await?;++ for (timestamp, offset_index, windows) in frames {+ let mut frame_results = Vec::with_capacity(windows.len());+ for (idx, window) in windows.iter().enumerate() {+ let frame_id = sqlx::query(+ "INSERT INTO frames (video_chunk_id, offset_index, timestamp, name, browser_url, app_name, window_name, focused, device_name) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",+ )+ .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)+ .execute(&mut **tx.conn())+ .await?+ .last_insert_rowid();++ 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())+ .await?;++ frame_results.push((frame_id, idx));+ }+ all_results.push(frame_results);+ }++ tx.commit().await?;+ debug!(+ "Multi-frame batch inserted {} frames with OCR for device {}",+ frames.len(),+ device_name+ );++ Ok(all_results)+ }+#[allow(clippy::too_many_arguments)]pub async fn search(&self,diff --git a/crates/screenpipe-server/src/core.rs b/crates/screenpipe-server/src/core.rsindex e56093c71..81c94f4ea 100644--- a/crates/screenpipe-server/src/core.rs+++ b/crates/screenpipe-server/src/core.rs@@ -229,6 +229,26 @@ pub async fn record_video(let mut consecutive_db_errors = 0;const MAX_CONSECUTIVE_DB_ERRORS: u32 = 100; // Threshold before reporting unhealthy state+ // Batch buffer: accumulate frames and flush together in one DB transaction.+ // This reduces write semaphore acquisitions from ~10/min to ~2/min.+ const BATCH_MAX_FRAMES: usize = 5;+ const BATCH_MAX_AGE: Duration = Duration::from_secs(3);+ struct PendingFrame {+ captured_at: chrono::DateTime<chrono::Utc>,+ offset_index: i64,+ windows: Vec<FrameWindowData>,+ image: image::DynamicImage,+ timestamp: std::time::Instant,+ window_metadata: Vec<(+ String,+ Vec<std::collections::HashMap<String, String>>,+ String,+ screenpipe_vision::core::WindowOcrResult,+ )>,+ }+ let mut pending_frames: Vec<PendingFrame> = Vec::with_capacity(BATCH_MAX_FRAMES);+ let mut batch_started_at = std::time::Instant::now();+loop {// Increment and check heartbeatheartbeat_counter += 1;@@ -284,19 +304,21 @@ pub async fn record_video(time_since_last_frame.as_millis());- // Wait for the video encoder to write this frame (up to 5s).+ // Wait for the video encoder to write this frame (up to 30s).// OCR often finishes before video encoding; Notify wakes us immediately// once the frame is recorded instead of blindly sleeping.+ // 30s accommodates DB contention spikes (avg 4-6s, peaks at 30s+)+ // without dropping frames that would otherwise be saved.let frame_write_info = video_capture.frame_write_tracker- .wait_for_offset(frame.frame_number, Duration::from_secs(5))+ .wait_for_offset(frame.frame_number, Duration::from_secs(30)).await;let video_frame_offset = match frame_write_info {Some(info) => info.offset as i64,None => {video_capture.metrics.record_drop();warn!(- "Skipping frame {} - not written to video within 5s timeout",+ "Skipping frame {} - not written to video within 30s timeout",frame.frame_number);continue;@@ -327,55 +349,93 @@ pub async fn record_video(});// Store metadata for realtime events (sent after DB insert)- window_metadata.push((text, sanitized_text_json, text_json, window_result));+ window_metadata.push((text, sanitized_text_json, text_json, window_result.clone()));+ }++ // Accumulate into batch buffer instead of inserting immediately+ if pending_frames.is_empty() {+ batch_started_at = std::time::Instant::now();+ }+ pending_frames.push(PendingFrame {+ captured_at: frame.captured_at,+ offset_index: video_frame_offset,+ windows: batch_windows,+ image: frame.image.clone(),+ timestamp: frame.timestamp,+ window_metadata,+ });+ } else {+ // Queue is empty — short poll sleep.+ // We intentionally do NOT use 1/fps here. The consumer must drain+ // the queue as fast as frames arrive. The *producer* (continuous_capture)+ // is the one that rate-limits capture to the target FPS.+ if heartbeat_counter.is_multiple_of(200) {+ debug!(+ "record_video: No frames in queue for monitor {}",+ monitor_id+ );}+ // Don't sleep if we have pending frames that need flushing+ if pending_frames.is_empty() {+ tokio::time::sleep(Duration::from_millis(50)).await;+ continue;+ }+ }++ // Flush batch when full OR when aged out (even with 1 frame)+ let should_flush = pending_frames.len() >= BATCH_MAX_FRAMES+ || (!pending_frames.is_empty() && batch_started_at.elapsed() >= BATCH_MAX_AGE);++ if should_flush {+ let frames_to_insert: Vec<_> = pending_frames+ .iter()+ .map(|pf| (pf.captured_at, pf.offset_index, pf.windows.clone()))+ .collect();- // Batch insert all frames + OCR in a single transactionlet batch_start = std::time::Instant::now();match db- .insert_frames_with_ocr_batch(+ .insert_multi_frames_with_ocr_batch(&device_name,- Some(frame.captured_at),- video_frame_offset,- &batch_windows,+ &frames_to_insert,Arc::new((*ocr_engine).clone().into()),).await{- Ok(results) => {+ Ok(all_results) => {let batch_duration = batch_start.elapsed();video_capture.metrics.record_db_write(batch_duration);if batch_duration.as_millis() > 200 {warn!(- "Slow DB batch insert: {}ms for {} windows",+ "Slow DB multi-frame batch: {}ms for {} frames",batch_duration.as_millis(),- results.len()+ pending_frames.len());}debug!(- "Batch inserted {} frames in {}ms",- results.len(),+ "Multi-frame batch inserted {} frames in {}ms",+ pending_frames.len(),batch_duration.as_millis());consecutive_db_errors = 0;- // Send realtime events after successful DB insert (always enabled)- {- for (frame_id, idx) in &results {- let (ref text, ref sanitized_text_json, _, window_result) =- window_metadata[*idx];+ // Send realtime events after successful DB insert+ for (frame_idx, frame_results) in all_results.iter().enumerate() {+ let pf = &pending_frames[frame_idx];+ for (frame_id, win_idx) in frame_results {+ let (ref text, ref sanitized_text_json, _, ref window_result) =+ pf.window_metadata[*win_idx];let send_event_start = std::time::Instant::now();match send_event("ocr_result",WindowOcr {- image: Some(frame.image.clone()),+ image: Some(pf.image.clone()),text: text.clone(),text_json: sanitized_text_json.clone(),app_name: window_result.app_name.clone(),window_name: window_result.window_name.clone(),focused: window_result.focused,confidence: window_result.confidence,- timestamp: frame.timestamp,+ timestamp: pf.timestamp,browser_url: window_result.browser_url.clone(),},) {@@ -393,31 +453,16 @@ pub async fn record_video(}}}+ pending_frames.clear();}Err(e) => {- warn!("Failed to batch insert frames: {}", e);+ warn!("Failed to multi-frame batch insert: {}", e);consecutive_db_errors += 1;+ // On error, drop the batch to avoid infinite retry loops+ pending_frames.clear();tokio::time::sleep(Duration::from_millis(100)).await;}}- } else {- // Queue is empty — short poll sleep.- // We intentionally do NOT use 1/fps here. The consumer must drain- // the queue as fast as frames arrive. The *producer* (continuous_capture)- // is the one that rate-limits capture to the target FPS.- //- // Previously this slept for 1/fps (2 seconds at 0.5 FPS) on EVERY- // iteration, including after processing a frame. This caused the- // queue to back up during adaptive FPS bursts (up to 10 FPS),- // leading to frame drops and missing screenshots in the timeline.- if heartbeat_counter.is_multiple_of(200) {- debug!(- "record_video: No frames in queue for monitor {}",- monitor_id- );- }- tokio::time::sleep(Duration::from_millis(50)).await;- continue;}// Check if we're seeing too many consecutive DB errorsdiff --git a/crates/screenpipe-server/src/routes/health.rs b/crates/screenpipe-server/src/routes/health.rsindex f97fc0ef0..01052ac7f 100644--- a/crates/screenpipe-server/src/routes/health.rs+++ b/crates/screenpipe-server/src/routes/health.rs@@ -163,7 +163,9 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<Helet last_audio_ts = audio_snap.last_db_write_ts;let now = Utc::now();- let threshold_secs = 1800u64; // 30 minutes+ // 60 seconds — tight enough to detect real stalls, loose enough to+ // tolerate adaptive FPS (0.1-0.5 fps) and brief DB contention spikes.+ let threshold_secs = 60u64;let frame_status = if state.vision_disabled {"disabled"@@ -207,9 +209,33 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<HeNone};+ // Check pipeline metrics for degradation beyond simple timestamp staleness.+ // High drop rate or DB latency indicates the pipeline is struggling even if+ // frames are still technically arriving.+ let vision_degraded = if !state.vision_disabled && vision_snap.uptime_secs > 120.0 {+ let high_drop_rate = vision_snap.frame_drop_rate > 0.5;+ let high_db_latency = vision_snap.avg_db_latency_ms > 10_000.0;+ if high_drop_rate {+ warn!(+ "health_check: vision drop rate {:.1}% exceeds 50% threshold",+ vision_snap.frame_drop_rate * 100.0+ );+ }+ if high_db_latency {+ warn!(+ "health_check: vision avg DB latency {:.0}ms exceeds 10s threshold",+ vision_snap.avg_db_latency_ms+ );+ }+ high_drop_rate || high_db_latency+ } else {+ false+ };+let (overall_status, message, verbose_instructions, status_code) = if (frame_status == "ok"|| frame_status == "disabled")&& (audio_status == "ok" || audio_status == "disabled")+ && !vision_degraded{("healthy",@@ -222,14 +248,42 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<Heif frame_status != "ok" && frame_status != "disabled" {unhealthy_systems.push("vision");}+ if vision_degraded && !unhealthy_systems.contains(&"vision") {+ unhealthy_systems.push("vision");+ }if audio_status != "ok" && audio_status != "disabled" {unhealthy_systems.push("audio");}+ let mut detail_parts = Vec::new();+ if vision_degraded {+ if vision_snap.frame_drop_rate > 0.5 {+ detail_parts.push(format!(+ "high frame drop rate ({:.0}%)",+ vision_snap.frame_drop_rate * 100.0+ ));+ }+ if vision_snap.avg_db_latency_ms > 10_000.0 {+ detail_parts.push(format!(+ "high DB latency ({:.0}ms)",+ vision_snap.avg_db_latency_ms+ ));+ }+ }+let systems_str = unhealthy_systems.join(", ");+ let msg = if detail_parts.is_empty() {+ format!("some systems are not healthy: {}", systems_str)+ } else {+ format!(+ "some systems are not healthy: {} ({})",+ systems_str,+ detail_parts.join(", ")+ )+ };("degraded",- format!("some systems are not healthy: {}", systems_str),+ msg,Some(get_verbose_instructions(&unhealthy_systems)),503,)diff --git a/crates/screenpipe-vision/src/core.rs b/crates/screenpipe-vision/src/core.rsindex 1e6f1ccea..bc76b1952 100644--- a/crates/screenpipe-vision/src/core.rs+++ b/crates/screenpipe-vision/src/core.rs@@ -114,6 +114,7 @@ pub struct CaptureResult {pub window_ocr_results: Vec<WindowOcrResult>,}+#[derive(Clone)]pub struct WindowOcrResult {pub window_name: String,pub app_name: String,