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: batch archive/retention deletes to prevent write semaphore starvation
louis03019541df5c58d8c8
diff --git a/apps/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/timeline/timeline.tsxindex a6e0a9d5e..d5b5166f4 100644--- a/apps/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx@@ -1322,7 +1322,7 @@ export const TimelineSlider = ({if (scrubberRef) (scrubberRef as React.MutableRefObject<HTMLDivElement | null>).current = el;}}tabIndex={0}- className="w-full overflow-x-auto overflow-y-visible scrollbar-hide bg-gradient-to-t from-black/50 to-black/0 outline-none"+ className="w-full overflow-x-auto overflow-y-visible scrollbar-hide bg-gradient-to-t from-foreground/5 to-transparent outline-none"style={{paddingTop: "60px", // Space for tooltips abovepaddingBottom: "24px", // Space for time axis belowdiff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rsindex e270478eb..c6c5f7c0c 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -4654,6 +4654,22 @@ impl DatabaseManager {})}+ /// Returns the oldest timestamp across frames and audio_transcriptions.+ /// Used by retention to avoid scanning from epoch.+ pub async fn get_oldest_timestamp(&self) -> Result<Option<DateTime<Utc>>, sqlx::Error> {+ let oldest: Option<String> = sqlx::query_scalar(+ r#"SELECT MIN(ts) FROM (+ SELECT MIN(timestamp) AS ts FROM frames+ UNION ALL+ SELECT MIN(timestamp) AS ts FROM audio_transcriptions+ )"#,+ )+ .fetch_one(&self.pool)+ .await?;++ Ok(oldest.and_then(|s| DateTime::parse_from_rfc3339(&s).ok().map(|dt| dt.with_timezone(&Utc))))+ }+/// Delete all locally-stored data that was synced from a specific remote device./// Uses JOINs to find related OCR/transcription records since those tables/// lack a direct machine_id column.diff --git a/crates/screenpipe-engine/src/archive.rs b/crates/screenpipe-engine/src/archive.rsindex 35ef1741b..8285c65ca 100644--- a/crates/screenpipe-engine/src/archive.rs+++ b/crates/screenpipe-engine/src/archive.rs@@ -916,33 +916,70 @@ async fn count_records_in_range(/// Delete data before cutoff and remove orphan media files from disk./// Only deletes video/snapshot files that have been uploaded to cloud/// (cloud_blob_id IS NOT NULL).+///+/// Batches deletes into 1-hour chunks to avoid holding the write semaphore+/// for minutes. A single massive transaction blocks ALL other DB writes+/// (vision capture, audio, etc.) causing PoolTimedOut crashes.async fn do_cleanup(db: &Arc<DatabaseManager>, cutoff: DateTime<Utc>) -> anyhow::Result<()> {- let epoch = DateTime::<Utc>::MIN_UTC;- let result = db.delete_time_range(epoch, cutoff).await?;+ let batch_size = Duration::hours(1);++ let oldest = match db.get_oldest_timestamp().await {+ Ok(Some(ts)) => ts,+ Ok(None) => return Ok(()),+ Err(e) => {+ warn!("archive: failed to get oldest timestamp: {}", e);+ return Ok(());+ }+ };- info!(- "archive: deleted frames={} ocr={} audio={} accessibility={} ui_events={} \- (video_files={} snapshot_files={} audio_files={})",- result.frames_deleted,- result.ocr_deleted,- result.audio_transcriptions_deleted,- result.accessibility_deleted,- result.ui_events_deleted,- result.video_files.len(),- result.snapshot_files.len(),- result.audio_files.len(),- );+ let mut batch_start = oldest;- // Delete orphan media files from disk (only those confirmed uploaded)- for path in result- .video_files- .iter()- .chain(result.audio_files.iter())- .chain(result.snapshot_files.iter())- {- if let Err(e) = tokio::fs::remove_file(path).await {- warn!("archive: failed to delete file {}: {}", path, e);+ while batch_start < cutoff {+ let batch_end = (batch_start + batch_size).min(cutoff);++ match db.delete_time_range(batch_start, batch_end).await {+ Ok(result) => {+ let batch_total = result.frames_deleted+ + result.ocr_deleted+ + result.audio_transcriptions_deleted+ + result.ui_events_deleted;++ if batch_total > 0 {+ info!(+ "archive: batch deleted frames={} ocr={} audio={} accessibility={} ui_events={} \+ (video_files={} snapshot_files={} audio_files={})",+ result.frames_deleted,+ result.ocr_deleted,+ result.audio_transcriptions_deleted,+ result.accessibility_deleted,+ result.ui_events_deleted,+ result.video_files.len(),+ result.snapshot_files.len(),+ result.audio_files.len(),+ );+ }++ // Delete orphan media files from disk (only those confirmed uploaded)+ for path in result+ .video_files+ .iter()+ .chain(result.audio_files.iter())+ .chain(result.snapshot_files.iter())+ {+ if let Err(e) = tokio::fs::remove_file(path).await {+ warn!("archive: failed to delete file {}: {}", path, e);+ }+ }+ }+ Err(e) => {+ warn!("archive: batch delete failed for range {} to {}: {}", batch_start, batch_end, e);+ }}++ batch_start = batch_end;++ // Yield between batches so other writes can acquire the semaphore+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;}Ok(())diff --git a/crates/screenpipe-engine/src/retention.rs b/crates/screenpipe-engine/src/retention.rsindex b1fb07bc9..739000e6f 100644--- a/crates/screenpipe-engine/src/retention.rs+++ b/crates/screenpipe-engine/src/retention.rs@@ -301,38 +301,73 @@ fn spawn_retention_loop(}async fn do_local_cleanup(db: &Arc<DatabaseManager>, cutoff: DateTime<Utc>) -> anyhow::Result<u64> {- let epoch = DateTime::<Utc>::MIN_UTC;- let result = db.delete_time_range_local(epoch, cutoff).await?;-- let total = result.frames_deleted- + result.ocr_deleted- + result.audio_transcriptions_deleted- + result.ui_events_deleted;-- if total > 0 {- info!(- "retention: deleted frames={} ocr={} audio={} ui_events={} \- (video_files={} snapshot_files={} audio_files={})",- result.frames_deleted,- result.ocr_deleted,- result.audio_transcriptions_deleted,- result.ui_events_deleted,- result.video_files.len(),- result.snapshot_files.len(),- result.audio_files.len(),- );- }+ // Delete in 1-hour batches to avoid holding the write semaphore for minutes.+ // The write semaphore has a 10s timeout — a single massive transaction would+ // block ALL other DB writes (vision capture, audio, etc.) causing PoolTimedOut+ // crashes. By batching, each transaction holds the semaphore for only seconds.+ let batch_size = Duration::hours(1);+ let mut total: u64 = 0;++ // Find the oldest data timestamp to avoid scanning from epoch+ let oldest = match db.get_oldest_timestamp().await {+ Ok(Some(ts)) => ts,+ Ok(None) => return Ok(0), // empty DB+ Err(e) => {+ warn!("retention: failed to get oldest timestamp: {}", e);+ return Ok(0);+ }+ };++ let mut batch_start = oldest;++ while batch_start < cutoff {+ let batch_end = (batch_start + batch_size).min(cutoff);++ match db.delete_time_range_local(batch_start, batch_end).await {+ Ok(result) => {+ let batch_total = result.frames_deleted+ + result.ocr_deleted+ + result.audio_transcriptions_deleted+ + result.ui_events_deleted;++ if batch_total > 0 {+ info!(+ "retention: batch deleted frames={} ocr={} audio={} ui_events={} \+ (video_files={} snapshot_files={} audio_files={})",+ result.frames_deleted,+ result.ocr_deleted,+ result.audio_transcriptions_deleted,+ result.ui_events_deleted,+ result.video_files.len(),+ result.snapshot_files.len(),+ result.audio_files.len(),+ );+ }- // Delete media files from disk AFTER successful DB commit- for path in result- .video_files- .iter()- .chain(result.audio_files.iter())- .chain(result.snapshot_files.iter())- {- if let Err(e) = tokio::fs::remove_file(path).await {- warn!("retention: failed to delete file {}: {}", path, e);+ total += batch_total;++ // Delete media files from disk AFTER successful DB commit+ for path in result+ .video_files+ .iter()+ .chain(result.audio_files.iter())+ .chain(result.snapshot_files.iter())+ {+ if let Err(e) = tokio::fs::remove_file(path).await {+ warn!("retention: failed to delete file {}: {}", path, e);+ }+ }+ }+ Err(e) => {+ warn!("retention: batch delete failed for range {} to {}: {}", batch_start, batch_end, e);+ // Continue with next batch instead of aborting entire cleanup+ }}++ batch_start = batch_end;++ // Yield between batches so other writes can acquire the semaphore+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;}Ok(total)