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
perf: reduce DB write contention — smaller FTS batches, fix semaphore bypass, limit streaming queries, merge audio transactions
Louis Beaumontb71f075c3e4f
diff --git a/Cargo.toml b/Cargo.tomlindex ad0a9621f..f899ac0e3 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -41,7 +41,7 @@ reqwest-middleware = "0.4.1"[patch.crates-io]# enables chinese mirror (hf is banned in china) and native-tls-hf-hub = { git = "https://github.com/neo773/hf-hub", features = ["native-tls"] }+hf-hub = { git = "https://github.com/neo773/hf-hub" }[workspace.metadata.vcpkg]git = "https://github.com/microsoft/vcpkg"diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lockindex aeef34093..a670c3bb9 100755--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -8098,7 +8098,7 @@ dependencies = [[[package]]name = "screenpipe-app"-version = "2.0.485"+version = "2.0.486"dependencies = ["anyhow","arboard",diff --git a/crates/screenpipe-audio/src/transcription/transcription_result.rs b/crates/screenpipe-audio/src/transcription/transcription_result.rsindex b459939e3..86842d286 100644--- a/crates/screenpipe-audio/src/transcription/transcription_result.rs+++ b/crates/screenpipe-audio/src/transcription/transcription_result.rs@@ -115,51 +115,35 @@ pub async fn process_transcription_result(None};- match db.get_or_insert_audio_chunk(&result.path, capture_ts).await {+ match db+ .insert_audio_chunk_and_transcription(+ &result.path,+ &transcription,+ 0,+ &transcription_engine,+ &screenpipe_db::AudioDevice {+ name: result.input.device.name.clone(),+ device_type: match result.input.device.device_type {+ crate::core::device::DeviceType::Input => screenpipe_db::DeviceType::Input,+ crate::core::device::DeviceType::Output => screenpipe_db::DeviceType::Output,+ },+ },+ Some(speaker.id),+ Some(result.start_time),+ Some(result.end_time),+ capture_ts,+ )+ .await+ {Ok(audio_chunk_id) => {- if transcription.is_empty() {- return Ok(Some(audio_chunk_id));- }-- if let Err(e) = db- .insert_audio_transcription(- audio_chunk_id,- &transcription,- 0,- &transcription_engine,- &screenpipe_db::AudioDevice {- name: result.input.device.name.clone(),- device_type: match result.input.device.device_type {- crate::core::device::DeviceType::Input => {- screenpipe_db::DeviceType::Input- }- crate::core::device::DeviceType::Output => {- screenpipe_db::DeviceType::Output- }- },- },- Some(speaker.id),- Some(result.start_time),- Some(result.end_time),- capture_ts,- )- .await- {- error!(- "Failed to insert audio transcription for device {}: {}",- result.input.device, e- );- return Ok(Some(audio_chunk_id));- } else {- debug!(- "Inserted audio transcription for chunk {} from device {} using {}",- audio_chunk_id, result.input.device, transcription_engine- );- chunk_id = Some(audio_chunk_id);- }+ debug!(+ "Inserted audio chunk+transcription for device {} using {}",+ result.input.device, transcription_engine+ );+ chunk_id = Some(audio_chunk_id);}Err(e) => error!(- "Failed to insert audio chunk for device {}: {}",+ "Failed to insert audio chunk+transcription for device {}: {}",result.input.device, e),}diff --git a/crates/screenpipe-core/src/lib.rs b/crates/screenpipe-core/src/lib.rsindex 9a6abb51b..9e484e688 100644--- a/crates/screenpipe-core/src/lib.rs+++ b/crates/screenpipe-core/src/lib.rs@@ -13,9 +13,6 @@ pub mod pii_removal;#[cfg(feature = "security")]pub use pii_removal::*;-pub mod network;-pub use network::*;-pub use language::{Language, TESSERACT_LANGUAGES};#[cfg(feature = "cloud-sync")]pub mod sync;diff --git a/crates/screenpipe-core/src/network.rs b/crates/screenpipe-core/src/network.rsdeleted file mode 100644index e2cba530f..000000000--- a/crates/screenpipe-core/src/network.rs+++ /dev/null@@ -1,58 +0,0 @@-use rand::Rng;-use std::net::{TcpListener, UdpSocket};--pub fn pick_unused_port() -> Option<u16> {- let mut rng = rand::thread_rng();-- // Try random ports first- for _ in 0..10 {- let port = rng.gen_range(15000..65535);- if is_port_available(port) {- return Some(port);- }- }-- // If random attempts fail, try to let the OS choose- for _ in 0..5 {- if let Some(port) = get_available_port() {- if is_port_available(port) {- return Some(port);- }- }- }-- None-}--fn is_port_available(port: u16) -> bool {- is_tcp_port_available(port) && is_udp_port_available(port)-}--fn is_tcp_port_available(port: u16) -> bool {- TcpListener::bind(("127.0.0.1", port)).is_ok()-}--fn is_udp_port_available(port: u16) -> bool {- UdpSocket::bind(("127.0.0.1", port)).is_ok()-}--fn get_available_port() -> Option<u16> {- TcpListener::bind(("127.0.0.1", 0))- .ok()- .and_then(|listener| listener.local_addr().ok())- .map(|addr| addr.port())-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_pick_unused_port() {- let port = pick_unused_port();- assert!(port.is_some());- let port = port.unwrap();- assert!((15000..65535).contains(&port));- assert!(is_port_available(port));- }-}diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rsindex e8c0b81e2..3c434b936 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -407,6 +407,88 @@ impl DatabaseManager {}}+ /// Combined audio chunk + transcription insert in a single transaction.+ /// This halves the number of BEGIN IMMEDIATE acquisitions compared to+ /// calling get_or_insert_audio_chunk() + insert_audio_transcription() separately.+ #[allow(clippy::too_many_arguments)]+ pub async fn insert_audio_chunk_and_transcription(+ &self,+ file_path: &str,+ transcription: &str,+ offset_index: i64,+ transcription_engine: &str,+ device: &AudioDevice,+ speaker_id: Option<i64>,+ start_time: Option<f64>,+ end_time: Option<f64>,+ timestamp: Option<DateTime<Utc>>,+ ) -> Result<i64, sqlx::Error> {+ // Skip empty transcriptions early (no lock needed)+ let trimmed = transcription.trim();+ if trimmed.is_empty() {+ // Still need to ensure the audio chunk exists+ return self.get_or_insert_audio_chunk(file_path, timestamp).await;+ }++ // Read phase: no write lock needed+ let existing_chunk_id = self.get_audio_chunk_id(file_path).await?;++ if self+ .has_similar_recent_transcription(trimmed, DEDUP_TIME_WINDOW_SECS)+ .await?+ {+ debug!(+ "Skipping duplicate transcription (cross-device): {:?}",+ &trimmed[..trimmed.len().min(50)]+ );+ // Still return the chunk id+ if existing_chunk_id != 0 {+ return Ok(existing_chunk_id);+ }+ // Need to insert the chunk even if transcription is skipped+ return self.insert_audio_chunk(file_path, timestamp).await;+ }++ // Write phase: single transaction for both chunk + transcription+ let ts = timestamp.unwrap_or_else(Utc::now);+ let text_length = transcription.len() as i64;+ let mut tx = self.begin_immediate_with_retry().await?;++ // Insert audio chunk if it doesn't exist yet+ let audio_chunk_id = if existing_chunk_id != 0 {+ existing_chunk_id+ } else {+ sqlx::query("INSERT INTO audio_chunks (file_path, timestamp) VALUES (?1, ?2)")+ .bind(file_path)+ .bind(ts)+ .execute(&mut **tx.conn())+ .await?+ .last_insert_rowid()+ };++ // Insert the transcription+ sqlx::query(+ "INSERT OR IGNORE INTO audio_transcriptions (audio_chunk_id, transcription, offset_index, timestamp, transcription_engine, device, is_input_device, speaker_id, start_time, end_time, text_length) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",+ )+ .bind(audio_chunk_id)+ .bind(transcription)+ .bind(offset_index)+ .bind(ts)+ .bind(transcription_engine)+ .bind(&device.name)+ .bind(device.device_type == DeviceType::Input)+ .bind(speaker_id)+ .bind(start_time)+ .bind(end_time)+ .bind(text_length)+ .execute(&mut **tx.conn())+ .await?;++ tx.commit().await?;++ Ok(audio_chunk_id)+ }+/// Check if a similar transcription exists in the recent time window./// Used for cross-device deduplication.async fn has_similar_recent_transcription(@@ -2078,6 +2160,7 @@ impl DatabaseManager {LEFT JOIN ocr_text ot ON f.id = ot.frame_idWHERE f.timestamp >= ?1 AND f.timestamp <= ?2ORDER BY f.timestamp DESC, f.offset_index DESC+ LIMIT 10000"#;// Get audio data with proper time windows for synchronization@@ -2101,6 +2184,7 @@ impl DatabaseManager {LEFT JOIN speakers s ON at.speaker_id = s.idWHERE at.timestamp >= ?1 AND at.timestamp <= ?2ORDER BY at.timestamp DESC+ LIMIT 10000"#;// Execute queries in parallel@@ -3706,6 +3790,8 @@ LIMIT ? OFFSET ?pub async fn insert_ui_event(&self, event: &InsertUiEvent) -> Result<i64, sqlx::Error> {let text_length = event.text_content.as_ref().map(|s| s.len() as i32);+ let mut tx = self.begin_immediate_with_retry().await?;+let result = sqlx::query(r#"INSERT INTO ui_events (@@ -3752,10 +3838,13 @@ LIMIT ? OFFSET ?.bind(&event.element_automation_id).bind(&event.element_bounds).bind(event.frame_id)- .execute(&self.pool)+ .execute(&mut **tx.conn()).await?;- Ok(result.last_insert_rowid())+ let id = result.last_insert_rowid();+ tx.commit().await?;++ Ok(id)}/// Insert multiple UI events in a batchdiff --git a/crates/screenpipe-db/src/fts_indexer.rs b/crates/screenpipe-db/src/fts_indexer.rsindex 91b84686f..a98dc91af 100644--- a/crates/screenpipe-db/src/fts_indexer.rs+++ b/crates/screenpipe-db/src/fts_indexer.rs@@ -10,9 +10,9 @@ use crate::DatabaseManager;/// Batch size for FTS indexing. Process this many rows per table per cycle./// Kept small to minimize write-lock hold time: each batch acquires-/// BEGIN IMMEDIATE which blocks frame inserts. 500 rows ≈ a few hundred ms-/// vs 2000 rows which could hold the lock for seconds on large monitors.-const FTS_BATCH_SIZE: i64 = 500;+/// BEGIN IMMEDIATE which blocks frame inserts. 100 rows ≈ tens of ms+/// vs 500 rows which could hold the lock for hundreds of ms on large monitors.+const FTS_BATCH_SIZE: i64 = 100;/// Delay between indexing each table to let frame inserts interleave.const FTS_INTER_TABLE_DELAY: Duration = Duration::from_millis(200);@@ -150,9 +150,11 @@ async fn get_last_indexed(db: &DatabaseManager, table_name: &str) -> Result<i64,Ok(result.unwrap_or(0))}-/// Update the last indexed rowid for a table.+/// Update the last indexed rowid for a table, within an existing transaction.+/// This avoids bypassing the write semaphore (which would create a third+/// uncontrolled writer competing at the SQLite level).async fn update_last_indexed(- db: &DatabaseManager,+ conn: &mut sqlx::SqliteConnection,table_name: &str,last_rowid: i64,) -> Result<(), sqlx::Error> {@@ -162,7 +164,7 @@ async fn update_last_indexed().bind(table_name).bind(last_rowid)- .execute(&db.pool)+ .execute(conn).await?;Ok(())}@@ -201,8 +203,8 @@ async fn index_frames_fts(db: &DatabaseManager) -> Result<i64, sqlx::Error> {.execute(&mut **tx.conn()).await?;+ update_last_indexed(&mut **tx.conn(), "frames", max_rowid).await?;tx.commit().await?;- update_last_indexed(db, "frames", max_rowid).await?;Ok(count)}@@ -243,8 +245,8 @@ async fn index_ocr_text_fts(db: &DatabaseManager) -> Result<i64, sqlx::Error> {.execute(&mut **tx.conn()).await?;+ update_last_indexed(&mut **tx.conn(), "ocr_text", max_rowid).await?;tx.commit().await?;- update_last_indexed(db, "ocr_text", max_rowid).await?;Ok(count)}@@ -287,8 +289,8 @@ async fn index_audio_transcriptions_fts(db: &DatabaseManager) -> Result<i64, sql.execute(&mut **tx.conn()).await?;+ update_last_indexed(&mut **tx.conn(), "audio_transcriptions", max_rowid).await?;tx.commit().await?;- update_last_indexed(db, "audio_transcriptions", max_rowid).await?;Ok(count)}@@ -327,8 +329,8 @@ async fn index_accessibility_fts(db: &DatabaseManager) -> Result<i64, sqlx::Erro.execute(&mut **tx.conn()).await?;+ update_last_indexed(&mut **tx.conn(), "accessibility", max_rowid).await?;tx.commit().await?;- update_last_indexed(db, "accessibility", max_rowid).await?;Ok(count)}diff --git a/crates/screenpipe-integrations/src/mod.rs b/crates/screenpipe-integrations/src/mod.rsdeleted file mode 100644index e69de29bb..000000000diff --git a/crates/screenpipe-integrations/src/unstructured_ocr.rs b/crates/screenpipe-integrations/src/unstructured_ocr.rsindex d67b4bdee..917f08a93 100644--- a/crates/screenpipe-integrations/src/unstructured_ocr.rs+++ b/crates/screenpipe-integrations/src/unstructured_ocr.rs@@ -2,17 +2,11 @@ use anyhow::{anyhow, Result};use image::{codecs::png::PngEncoder, DynamicImage, ImageEncoder};use log::error;use reqwest::multipart::{Form, Part};-use reqwest::Client;use screenpipe_core::{Language, TESSERACT_LANGUAGES};use serde_json;-use serde_json::Value;use std::collections::HashMap;use std::env;use std::io::Cursor;-use std::io::Read;-use std::io::Write;-use std::path::PathBuf;-use tempfile::NamedTempFile;use tokio::time::{timeout, Duration};pub async fn perform_ocr_cloud(@@ -117,72 +111,3 @@ fn calculate_overall_confidence(parsed_response: &[HashMap<String, serde_json::V}}-pub async fn unstructured_chunking(text: &str) -> Result<Vec<String>> {- let client = Client::new();- let api_key = match env::var("UNSTRUCTURED_API_KEY") {- Ok(key) => key,- Err(_) => {- error!("UNSTRUCTURED_API_KEY environment variable is not set. Please set it to use the OCR cloud service.");- return Err(anyhow!("Missing API key"));- }- };- // Create temporary file- let mut temp_file = NamedTempFile::new().map_err(|e| anyhow!(e.to_string()))?;- temp_file- .write_all(text.as_bytes())- .map_err(|e| anyhow!(e.to_string()))?;-- // Prepare request- let form = reqwest::multipart::Form::new()- .part("files", {- let mut bytes = vec![];- temp_file.read_to_end(&mut bytes)?;-- let path = PathBuf::from(temp_file.path());-- let file_name = path- .file_name()- .ok_or(anyhow!("Couldn't send files to unstructuredapp API"))?- .to_string_lossy()- .into_owned();-- let mime_type = mime_guess::from_path(path)- .first()- .ok_or(anyhow!("Couldn't determine file's MIME type."))?- .essence_str()- .to_owned();-- Part::bytes(bytes)- .file_name(file_name)- .mime_str(&mime_type)?- })- .text("chunking_strategy", "by_similarity")- .text("similarity_threshold", "0.5")- .text("max_characters", "300")- .text("output_format", "application/json");-- // Send request- let response = client- .post("https://api.unstructuredapp.io/general/v0/general")- .header("accept", "application/json")- .header("unstructured-api-key", &api_key)- .multipart(form)- .send()- .await- .map_err(|e| anyhow!(e.to_string()))?;-- if response.status().is_success() {- let chunks = response- .json::<Vec<Value>>()- .await- .map_err(|e| anyhow!(e.to_string()))?;- let texts: Vec<String> = chunks- .iter()- .filter_map(|chunk| chunk["text"].as_str().map(String::from))- .collect();-- Ok(texts)- } else {- Err(anyhow!("Error: {}", response.status()))- }-}