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: DB pool starvation + past-day timeline navigation
Louis Beaumonte61501da7377
diff --git a/Cargo.lock b/Cargo.lockindex 24cd46056..77b10ab27 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5512,7 +5512,7 @@ dependencies = [[[package]]name = "screenpipe-audio"-version = "0.3.159"+version = "0.3.160"dependencies = ["anyhow","audiopipe",@@ -5569,7 +5569,7 @@ dependencies = [[[package]]name = "screenpipe-core"-version = "0.3.159"+version = "0.3.160"dependencies = ["accessibility","accessibility-sys",@@ -5611,7 +5611,7 @@ dependencies = [[[package]]name = "screenpipe-db"-version = "0.3.159"+version = "0.3.160"dependencies = ["anyhow","chrono",@@ -5636,7 +5636,7 @@ dependencies = [[[package]]name = "screenpipe-events"-version = "0.3.159"+version = "0.3.160"dependencies = ["anyhow","chrono",@@ -5654,7 +5654,7 @@ dependencies = [[[package]]name = "screenpipe-integrations"-version = "0.3.159"+version = "0.3.160"dependencies = ["anyhow","chrono",@@ -5674,7 +5674,7 @@ dependencies = [[[package]]name = "screenpipe-server"-version = "0.3.159"+version = "0.3.160"dependencies = ["anyhow","async-trait",@@ -5735,7 +5735,7 @@ dependencies = [[[package]]name = "screenpipe-vision"-version = "0.3.159"+version = "0.3.160"dependencies = ["accessibility-sys","anyhow",diff --git a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/timeline.tsxindex 83e8965a2..e6f625c1a 100644--- a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/timeline.tsx@@ -439,6 +439,13 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {debounceTimer = setTimeout(() => {debounceTimer = null;+ // Don't reset if a search/calendar navigation is in progress —+ // onWindowFocus resets currentDate to today, which cancels the+ // cross-date navigation and discards the pending fetch.+ if (isNavigatingRef.current || pendingNavigationRef.current) {+ return;+ }+// Pause any active playbackpausePlayback();@@ -1376,26 +1383,19 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {setCurrentIndex(0);setCurrentDate(targetDate);- // Timeout: if frames haven't arrived after 10s, retry with full-day fetch- // instead of giving up entirely+ // Past-day queries can take 60s+ on large DBs (legacy data with+ // correlated subqueries). The [currentDate, websocket] effect already+ // fires a full-day fetch, so we just need to wait long enough.+ // Give up after 90s — if the query hasn't finished by then, it won't.setTimeout(() => {if (pendingNavigationRef.current && isSameDay(pendingNavigationRef.current, targetDate)) {- console.warn("[navigateDirectToDate] Timeout: retrying with full-day fetch");- clearSentRequestForDate(targetDate);- fetchTimeRange(startOfDay(targetDate), endOfDay(targetDate));-- // Final timeout: give up after another 10s- setTimeout(() => {- if (pendingNavigationRef.current && isSameDay(pendingNavigationRef.current, targetDate)) {- console.warn("[navigateDirectToDate] Final timeout: clearing navigation state");- pendingNavigationRef.current = null;- setSeekingTimestamp(null);- setIsNavigating(false);- isNavigatingRef.current = false;- }- }, 10000);+ console.warn("[navigateDirectToDate] Timeout after 90s: clearing navigation state");+ pendingNavigationRef.current = null;+ setSeekingTimestamp(null);+ setIsNavigating(false);+ isNavigatingRef.current = false;}- }, 10000);+ }, 90000);};const handleDateChange = async (newDate: Date) => {diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsxindex 48e8808b0..2b232109b 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx@@ -571,56 +571,72 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({},fetchTimeRange: async (startTime: Date, endTime: Date) => {- const { websocket, sentRequests } = get();- // Use ISO range as key so narrow-window and full-day fetches get distinct keys- const requestKey = `${startTime.toISOString()}_${endTime.toISOString()}`;-- if (sentRequests.has(requestKey)) {- return;- }+ const sendOrRetry = (attempt: number) => {+ const { websocket, sentRequests } = get();+ // Use ISO range as key so narrow-window and full-day fetches get distinct keys+ const requestKey = `${startTime.toISOString()}_${endTime.toISOString()}`;- if (websocket && websocket.readyState === WebSocket.OPEN) {- websocket.send(- JSON.stringify({- start_time: startTime.toISOString(),- end_time: endTime.toISOString(),- order: "descending",- }),- );-- set((state) => ({- sentRequests: new Set(state.sentRequests).add(requestKey),- }));-- // Start timeout - if no frames arrive, retry- if (requestTimeoutTimer) {- clearTimeout(requestTimeoutTimer);+ if (sentRequests.has(requestKey)) {+ return;}- requestTimeoutTimer = setTimeout(() => {- requestTimeoutTimer = null;- const { frames: currentFrames, pendingDateSwap: stillSwapping } = get();- // Retry if no frames arrived (or still waiting for date swap to complete)- if ((currentFrames.length === 0 || stillSwapping) && requestRetryCount < MAX_REQUEST_RETRIES) {- requestRetryCount++;+ if (websocket && websocket.readyState === WebSocket.OPEN) {+ websocket.send(+ JSON.stringify({+ start_time: startTime.toISOString(),+ end_time: endTime.toISOString(),+ order: "descending",+ }),+ );- // Clear this date from sentRequests to allow retry- set((state) => {- const newSentRequests = new Set(state.sentRequests);- newSentRequests.delete(requestKey);- return { sentRequests: newSentRequests };- });+ set((state) => ({+ sentRequests: new Set(state.sentRequests).add(requestKey),+ }));- // Retry the request- get().fetchTimeRange(startTime, endTime);- } else if ((currentFrames.length === 0 || stillSwapping) && requestRetryCount >= MAX_REQUEST_RETRIES) {- set({- isLoading: false,- message: "No data available for this time range"- });+ // Start timeout - if no frames arrive, retry+ if (requestTimeoutTimer) {+ clearTimeout(requestTimeoutTimer);}- }, REQUEST_TIMEOUT_MS);- }+ requestTimeoutTimer = setTimeout(() => {+ requestTimeoutTimer = null;+ const { frames: currentFrames, pendingDateSwap: stillSwapping } = get();++ // Retry if no frames arrived (or still waiting for date swap to complete)+ if ((currentFrames.length === 0 || stillSwapping) && requestRetryCount < MAX_REQUEST_RETRIES) {+ requestRetryCount++;++ // Clear this date from sentRequests to allow retry+ set((state) => {+ const newSentRequests = new Set(state.sentRequests);+ newSentRequests.delete(requestKey);+ return { sentRequests: newSentRequests };+ });++ // Retry the request+ get().fetchTimeRange(startTime, endTime);+ } else if ((currentFrames.length === 0 || stillSwapping) && requestRetryCount >= MAX_REQUEST_RETRIES) {+ set({+ isLoading: false,+ message: "No data available for this time range"+ });+ }+ }, REQUEST_TIMEOUT_MS);+ } else if (attempt < 5) {+ // WebSocket not open — retry after a short delay instead of silently dropping.+ // This happens during cross-date navigation when the WS may be reconnecting.+ const delay = 500 * (attempt + 1); // 500ms, 1s, 1.5s, 2s, 2.5s+ console.warn(`[fetchTimeRange] WebSocket not open, retrying in ${delay}ms (attempt ${attempt + 1}/5)`);+ setTimeout(() => sendOrRetry(attempt + 1), delay);+ } else {+ console.error("[fetchTimeRange] WebSocket not open after 5 retries, giving up");+ set({+ isLoading: false,+ message: "Connection lost — please try again",+ });+ }+ };++ sendOrRetry(0);},fetchNextDayData: async (date: Date) => {diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 8ed8ab68a..811433ad8 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.2.0"+version = "2.2.1"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 d275a8f2a..9b108a68c 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -126,6 +126,11 @@ pub struct DatabaseManager {/// With FTS handled by inline triggers (not the removed background indexer),/// each write holds the semaphore for only a few milliseconds.write_semaphore: Arc<Semaphore>,+ /// Limits concurrent heavy read queries (e.g. find_video_chunks) to 2.+ /// These queries can take 60+ seconds on large DBs with legacy data,+ /// starving the pool for writes and fast reads. By capping at 2 concurrent+ /// heavy reads, we guarantee 28+ connections remain available for normal ops.+ heavy_read_semaphore: Arc<Semaphore>,}impl DatabaseManager {@@ -183,6 +188,7 @@ impl DatabaseManager {let db_manager = DatabaseManager {pool,write_semaphore: Arc::new(Semaphore::new(1)),+ heavy_read_semaphore: Arc::new(Semaphore::new(2)),};// Checkpoint any stale WAL before running migrations or starting captures.@@ -3114,6 +3120,12 @@ impl DatabaseManager {start: DateTime<Utc>,end: DateTime<Utc>,) -> Result<TimeSeriesChunk, SqlxError> {+ // Acquire a heavy-read permit (max 2 concurrent). This prevents slow+ // queries (60s+ on legacy data) from consuming all pool connections.+ let _permit = self.heavy_read_semaphore.acquire().await.map_err(|_| {+ SqlxError::Protocol("heavy_read_semaphore closed".to_string())+ })?;+// Get frames with OCR data, grouped by minute to handle multiple monitors.// OCR text is truncated to 200 chars for the timeline stream — full text// is fetched on-demand via /frames/{id}/ocr when needed. This reducesdiff --git a/crates/screenpipe-server/src/hot_frame_cache.rs b/crates/screenpipe-server/src/hot_frame_cache.rsindex 5b41a60d8..b350cab64 100644--- a/crates/screenpipe-server/src/hot_frame_cache.rs+++ b/crates/screenpipe-server/src/hot_frame_cache.rs@@ -59,6 +59,10 @@ pub struct HotFrameCache {audio_notify: broadcast::Sender<HotAudio>,/// Ordinal day number — cache is cleared on day rollover.cache_day: RwLock<u32>,+ /// Earliest timestamp the cache covers. Set by warm_from_db (cold start)+ /// and extended by push_frame (live capture). The streaming handler uses+ /// this to skip the DB backfill when the cache already covers the range.+ cache_warm_start: RwLock<Option<DateTime<Utc>>>,}impl Default for HotFrameCache {@@ -78,6 +82,7 @@ impl HotFrameCache {frame_notify: frame_tx,audio_notify: audio_tx,cache_day: RwLock::new(Utc::now().ordinal()),+ cache_warm_start: RwLock::new(None),}}@@ -92,6 +97,7 @@ impl HotFrameCache {);self.frames.write().await.clear();self.audio.write().await.clear();+ *self.cache_warm_start.write().await = None;*day = today;}}@@ -100,6 +106,15 @@ impl HotFrameCache {pub async fn push_frame(&self, frame: HotFrame) {self.maybe_rollover().await;let key = (frame.timestamp, frame.frame_id);+ // Extend cache coverage if this frame is earlier than current warm_start+ {+ let mut ws = self.cache_warm_start.write().await;+ match *ws {+ None => *ws = Some(frame.timestamp),+ Some(existing) if frame.timestamp < existing => *ws = Some(frame.timestamp),+ _ => {}+ }+ }self.frames.write().await.insert(key, frame.clone());// Broadcast to WS handlers — ignore errors (no subscribers = fine)let _ = self.frame_notify.send(frame);@@ -149,6 +164,13 @@ impl HotFrameCache {.collect()}+ /// Earliest timestamp the cache covers (inclusive).+ /// Returns `None` if cache is empty / not yet warmed.+ /// The streaming handler uses this to skip or narrow the DB backfill.+ pub async fn earliest_coverage(&self) -> Option<DateTime<Utc>> {+ *self.cache_warm_start.read().await+ }+/// Check if the cache has data for a given date (today).pub async fn is_today(&self, ts: DateTime<Utc>) -> bool {let day = self.cache_day.read().await;@@ -216,7 +238,15 @@ impl HotFrameCache {}}- info!("hot_frame_cache: warmed with {} frame entries", frame_count);+ // Set cache coverage — use the query start time (not earliest+ // frame) so we know the DB was scanned from `start` even if+ // there were no frames in the early portion of the range.+ *self.cache_warm_start.write().await = Some(start);++ info!(+ "hot_frame_cache: warmed with {} frame entries, coverage from {}",+ frame_count, start+ );}Err(e) => {warn!("hot_frame_cache: failed to warm from DB: {}", e);diff --git a/crates/screenpipe-server/src/routes/streaming.rs b/crates/screenpipe-server/src/routes/streaming.rsindex 43eb5c3e7..d70fd4ec9 100644--- a/crates/screenpipe-server/src/routes/streaming.rs+++ b/crates/screenpipe-server/src/routes/streaming.rs@@ -291,52 +291,87 @@ async fn handle_stream_frames_socket(sorted.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));}+ // Record sent IDs first (fast, no async), then send+ // frames WITHOUT holding the lock. Previously the lock+ // was held across channel sends, blocking the receive+ // loop from processing new WS messages (e.g. past-day+ // navigation requests) for seconds.{let mut sent = sent_ids_clone.lock().await;- for frame in sorted {+ for frame in &sorted {for df in &frame.frame_data {sent.insert(df.frame_id);}- let _ = frame_tx.send(frame).await;}- } // drop lock before spawning backfill-- // Backfill from DB for the full day — the hot cache only- // has frames since last restart (~2h warm window). Frames- // already sent from cache are skipped via sent_frame_ids.- let frame_tx_db = frame_tx.clone();- let db_backfill = db_clone.clone();- let sent_ids_backfill = sent_ids_clone.clone();- tokio::spawn(async move {- match db_backfill.find_video_chunks(start_time, end_time).await {- Ok(mut chunks) => {- if is_descending {- chunks.frames.sort_by_key(|a| {- std::cmp::Reverse((a.timestamp, a.offset_index))- });- } else {- chunks- .frames- .sort_by_key(|a| (a.timestamp, a.offset_index));- }- let mut sent = sent_ids_backfill.lock().await;- for chunk in chunks.frames {- if sent.contains(&chunk.frame_id) {- continue;+ } // lock dropped++ for frame in sorted {+ let _ = frame_tx.send(frame).await;+ }++ // Only backfill from DB if the hot cache doesn't+ // cover the requested range. The cache knows its+ // earliest coverage timestamp from warm_from_db ++ // push_frame. If the cache covers start_time, we+ // skip the 60s+ find_video_chunks query entirely.+ let cache_start = cache_clone.earliest_coverage().await;+ let backfill_needed = match cache_start {+ Some(cs) if cs <= start_time => false,+ Some(cs) => {+ // Cache only covers cs..now, backfill start_time..cs+ info!(+ "partial cache coverage: cache from {}, backfilling {}..{}",+ cs, start_time, cs+ );+ true+ }+ None => true, // no cache coverage at all+ };++ if backfill_needed {+ let backfill_end = cache_start.unwrap_or(end_time);+ let frame_tx_db = frame_tx.clone();+ let db_backfill = db_clone.clone();+ let sent_ids_backfill = sent_ids_clone.clone();+ tokio::spawn(async move {+ match db_backfill+ .find_video_chunks(start_time, backfill_end)+ .await+ {+ Ok(mut chunks) => {+ if is_descending {+ chunks.frames.sort_by_key(|a| {+ std::cmp::Reverse((+ a.timestamp,+ a.offset_index,+ ))+ });+ } else {+ chunks.frames.sort_by_key(|a| {+ (a.timestamp, a.offset_index)+ });}- sent.insert(chunk.frame_id);- let frame = create_time_series_frame(chunk);- if !frame.frame_data.is_empty()- && frame_tx_db.send(frame).await.is_err()- {- break;+ let mut sent = sent_ids_backfill.lock().await;+ for chunk in chunks.frames {+ if sent.contains(&chunk.frame_id) {+ continue;+ }+ sent.insert(chunk.frame_id);+ let frame = create_time_series_frame(chunk);+ if !frame.frame_data.is_empty()+ && frame_tx_db.send(frame).await.is_err()+ {+ break;+ }}+ info!("Today DB backfill complete");}- info!("Today DB backfill complete");+ Err(e) => warn!("Today DB backfill failed: {}", e),}- Err(e) => warn!("Today DB backfill failed: {}", e),- }- });+ });+ } else {+ info!("skipping DB backfill — hot cache covers full range");+ }} else {// Past day — one-shot DB query (acceptable, rare)let frame_tx = frame_tx.clone();@@ -345,7 +380,7 @@ async fn handle_stream_frames_socket(tokio::spawn(async move {let fetch_result = tokio::time::timeout(- std::time::Duration::from_secs(10),+ std::time::Duration::from_secs(120),fetch_and_process_frames_with_tracking(db,start_time,@@ -360,7 +395,7 @@ async fn handle_stream_frames_socket(match fetch_result {Ok(Ok(_)) => info!("Past-day fetch complete"),Ok(Err(e)) => error!("Past-day fetch failed: {}", e),- Err(_) => warn!("Past-day fetch timed out after 10s"),+ Err(_) => warn!("Past-day fetch timed out after 120s"),}});}diff --git a/crates/screenpipe-server/src/server.rs b/crates/screenpipe-server/src/server.rsindex cf74cdcfb..9f80beb03 100644--- a/crates/screenpipe-server/src/server.rs+++ b/crates/screenpipe-server/src/server.rs@@ -323,7 +323,7 @@ impl SCServer {let cache = hot_frame_cache.clone();let db = self.db.clone();tokio::spawn(async move {- cache.warm_from_db(&db, 2).await;+ cache.warm_from_db(&db, 24).await;});}