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
feat: add search result caching for 10x faster repeated queries
Louis Beaumontf81ba4041320
diff --git a/Cargo.lock b/Cargo.lockindex 5724b760a..c8bb44e51 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2763,6 +2763,21 @@ dependencies = ["seq-macro",]+[[package]]+name = "generator"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52f04ae4152da20c76fe800fa48659201d5cf627c5149ca0b707b69d7eef6cf9"+dependencies = [+ "cc",+ "cfg-if",+ "libc",+ "log",+ "rustversion",+ "windows-link 0.2.1",+ "windows-result 0.3.4",+]+[[package]]name = "generic-array"version = "0.14.7"@@ -4078,6 +4093,19 @@ version = "0.4.26"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e"+[[package]]+name = "loom"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca"+dependencies = [+ "cfg-if",+ "generator",+ "scoped-tls",+ "tracing",+ "tracing-subscriber",+]+[[package]]name = "loop9"version = "0.1.5"@@ -4336,6 +4364,28 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "moka"+version = "0.12.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9321642ca94a4282428e6ea4af8cc2ca4eac48ac7a6a4ea8f33f76d0ce70926"+dependencies = [+ "async-lock",+ "crossbeam-channel",+ "crossbeam-epoch",+ "crossbeam-utils",+ "event-listener 5.4.0",+ "futures-util",+ "loom",+ "parking_lot",+ "portable-atomic",+ "rustc_version",+ "smallvec",+ "tagptr",+ "thiserror 1.0.69",+ "uuid",+]+[[package]]name = "monostate"version = "0.1.14"@@ -6396,7 +6446,7 @@ dependencies = ["errno","libc","linux-raw-sys 0.11.0",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -6746,6 +6796,7 @@ dependencies = ["imageproc","killport","lru",+ "moka","ndarray 0.15.6","nix 0.29.0","oasgen",@@ -7981,6 +8032,12 @@ dependencies = ["version-compare",]+[[package]]+name = "tagptr"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417"+[[package]]name = "tar"version = "0.4.44"diff --git a/screenpipe-db/src/db.rs b/screenpipe-db/src/db.rsindex f7384bfef..d92dcd75d 100644--- a/screenpipe-db/src/db.rs+++ b/screenpipe-db/src/db.rs@@ -71,10 +71,14 @@ impl DatabaseManager {.execute(&pool).await?;- // Enable SQLite's query result caching- // PRAGMA cache_size = -2000; -- Set cache size to 2MB- // PRAGMA temp_store = MEMORY; -- Store temporary tables and indices in memory- sqlx::query("PRAGMA cache_size = -2000;")+ // Optimize SQLite for search performance+ // cache_size: -64000 = 64MB page cache (negative = KB)+ // mmap_size: 256MB memory-mapped I/O for faster reads+ // temp_store: keep temp tables in memory+ sqlx::query("PRAGMA cache_size = -64000;")+ .execute(&pool)+ .await?;+ sqlx::query("PRAGMA mmap_size = 268435456;").execute(&pool).await?;sqlx::query("PRAGMA temp_store = MEMORY;")diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex 5cf36f9fd..d32107417 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -43,6 +43,7 @@ candle-transformers = { workspace = true }tokenizers = { workspace = true }anyhow = "1.0.86"+moka = { version = "0.12", features = ["future"] }hf-hub = { workspace = true }#opentelemetrydiff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 4266aa3de..b386a3f19 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -57,6 +57,8 @@ use screenpipe_vision::OcrEngine;use serde::{Deserialize, Deserializer, Serialize};use serde_json::{json, Value};use std::{+ collections::hash_map::DefaultHasher,+ hash::{Hash, Hasher},net::SocketAddr,num::NonZeroUsize,path::PathBuf,@@ -72,6 +74,7 @@ use std::{const MAX_WEBSOCKET_CONNECTIONS: usize = 100;use lru::LruCache;+use moka::future::Cache as MokaCache;use tokio::{net::TcpListener,@@ -93,6 +96,9 @@ use uuid::Uuid; // or sentry::protocol::Uuid depending on which you want to usepub type FrameImageCache = LruCache<i64, (String, Instant)>;+/// Cache key for search results (hash of query parameters)+pub type SearchCache = MokaCache<u64, Arc<SearchResponse>>;+pub struct AppState {pub db: Arc<DatabaseManager>,pub audio_manager: Arc<AudioManager>,@@ -107,6 +113,8 @@ pub struct AppState {pub element_cache: Arc<Mutex<Option<(Vec<UIElement>, Instant, String)>>>,/// Counter for active WebSocket connections to prevent resource exhaustionpub ws_connection_count: Arc<AtomicUsize>,+ /// LRU cache for search results (10x faster for repeated queries)+ pub search_cache: SearchCache,}// Update the SearchQuery struct@@ -172,7 +180,7 @@ pub struct PaginatedResponse<T> {pub pagination: PaginationInfo,}-#[derive(Serialize, OaSchema, Deserialize)]+#[derive(Serialize, OaSchema, Deserialize, Clone)]pub struct PaginationInfo {pub limit: u32,pub offset: u32,@@ -221,7 +229,7 @@ struct MarkAsHallucinationRequest {speaker_id: i64,}-#[derive(OaSchema, Serialize, Deserialize, Debug)]+#[derive(OaSchema, Serialize, Deserialize, Debug, Clone)]#[serde(tag = "type", content = "content")]pub enum ContentItem {OCR(OCRContent),@@ -229,7 +237,7 @@ pub enum ContentItem {UI(UiContent),}-#[derive(OaSchema, Serialize, Deserialize, Debug)]+#[derive(OaSchema, Serialize, Deserialize, Debug, Clone)]pub struct OCRContent {pub frame_id: i64,pub text: String,@@ -246,7 +254,7 @@ pub struct OCRContent {pub device_name: String,}-#[derive(OaSchema, Serialize, Deserialize, Debug)]+#[derive(OaSchema, Serialize, Deserialize, Debug, Clone)]pub struct AudioContent {pub chunk_id: i64,pub transcription: String,@@ -261,7 +269,7 @@ pub struct AudioContent {pub end_time: Option<f64>,}-#[derive(OaSchema, Serialize, Deserialize, Debug)]+#[derive(OaSchema, Serialize, Deserialize, Debug, Clone)]pub struct UiContent {pub id: i64,pub text: String,@@ -328,12 +336,33 @@ pub struct HealthCheckResponse {pub device_status_details: Option<String>,}-#[derive(OaSchema, Serialize, Deserialize)]+#[derive(OaSchema, Serialize, Deserialize, Clone)]pub struct SearchResponse {pub data: Vec<ContentItem>,pub pagination: PaginationInfo,}+/// Compute a cache key for a search query by hashing its parameters+fn compute_search_cache_key(query: &SearchQuery) -> u64 {+ let mut hasher = DefaultHasher::new();+ query.q.hash(&mut hasher);+ query.pagination.limit.hash(&mut hasher);+ query.pagination.offset.hash(&mut hasher);+ format!("{:?}", query.content_type).hash(&mut hasher);+ query.start_time.map(|t| t.timestamp()).hash(&mut hasher);+ query.end_time.map(|t| t.timestamp()).hash(&mut hasher);+ query.app_name.hash(&mut hasher);+ query.window_name.hash(&mut hasher);+ query.frame_name.hash(&mut hasher);+ query.min_length.hash(&mut hasher);+ query.max_length.hash(&mut hasher);+ query.speaker_ids.hash(&mut hasher);+ query.focused.hash(&mut hasher);+ query.browser_url.hash(&mut hasher);+ query.speaker_name.hash(&mut hasher);+ hasher.finish()+}+// Update the search function#[oasgen]pub(crate) async fn search(@@ -359,6 +388,15 @@ pub(crate) async fn search(query.speaker_name,);+ // Check cache first (only for queries without frame extraction)+ let cache_key = compute_search_cache_key(&query);+ if !query.include_frames {+ if let Some(cached) = state.search_cache.get(&cache_key).await {+ debug!("search cache hit for key {}", cache_key);+ return Ok(JsonResponse((*cached).clone()));+ }+ }+let query_str = query.q.as_deref().unwrap_or("");let content_type = query.content_type.clone();@@ -503,14 +541,24 @@ pub(crate) async fn search(}),);- Ok(JsonResponse(SearchResponse {+ let response = SearchResponse {data: content_items,pagination: PaginationInfo {limit: query.pagination.limit,offset: query.pagination.offset,total: total as i64,},- }))+ };++ // Cache the result (only for queries without frame extraction)+ if !query.include_frames {+ state+ .search_cache+ .insert(cache_key, Arc::new(response.clone()))+ .await;+ }++ Ok(JsonResponse(response))}#[oasgen]@@ -1227,6 +1275,11 @@ impl SCServer {},element_cache: Arc::new(Mutex::new(None)),ws_connection_count: Arc::new(AtomicUsize::new(0)),+ // Search cache: 1000 entries, 60 second TTL+ search_cache: MokaCache::builder()+ .max_capacity(1000)+ .time_to_live(Duration::from_secs(60))+ .build(),});let cors = CorsLayer::new()@@ -4997,3 +5050,109 @@ async fn scroll_element_handler()),}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_search_cache_key_deterministic() {+ // Same query should produce same cache key+ let query1 = SearchQuery {+ q: Some("test".to_string()),+ pagination: PaginationQuery {+ limit: 10,+ offset: 0,+ },+ content_type: ContentType::All,+ start_time: None,+ end_time: None,+ app_name: Some("chrome".to_string()),+ window_name: None,+ frame_name: None,+ include_frames: false,+ min_length: None,+ max_length: None,+ speaker_ids: None,+ focused: None,+ browser_url: None,+ speaker_name: None,+ };++ let query2 = SearchQuery {+ q: Some("test".to_string()),+ pagination: PaginationQuery {+ limit: 10,+ offset: 0,+ },+ content_type: ContentType::All,+ start_time: None,+ end_time: None,+ app_name: Some("chrome".to_string()),+ window_name: None,+ frame_name: None,+ include_frames: false,+ min_length: None,+ max_length: None,+ speaker_ids: None,+ focused: None,+ browser_url: None,+ speaker_name: None,+ };++ let key1 = compute_search_cache_key(&query1);+ let key2 = compute_search_cache_key(&query2);++ assert_eq!(key1, key2, "Same queries should produce same cache key");+ }++ #[test]+ fn test_search_cache_key_differs_for_different_queries() {+ let query1 = SearchQuery {+ q: Some("test".to_string()),+ pagination: PaginationQuery {+ limit: 10,+ offset: 0,+ },+ content_type: ContentType::All,+ start_time: None,+ end_time: None,+ app_name: None,+ window_name: None,+ frame_name: None,+ include_frames: false,+ min_length: None,+ max_length: None,+ speaker_ids: None,+ focused: None,+ browser_url: None,+ speaker_name: None,+ };++ let query2 = SearchQuery {+ q: Some("different".to_string()),+ pagination: PaginationQuery {+ limit: 10,+ offset: 0,+ },+ content_type: ContentType::All,+ start_time: None,+ end_time: None,+ app_name: None,+ window_name: None,+ frame_name: None,+ include_frames: false,+ min_length: None,+ max_length: None,+ speaker_ids: None,+ focused: None,+ browser_url: None,+ speaker_name: None,+ };++ let key1 = compute_search_cache_key(&query1);+ let key2 = compute_search_cache_key(&query2);++ assert_ne!(key1, key2, "Different queries should produce different cache keys");+ }+}