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: replace DB queries in health check with in-memory atomic reads
Louis Beaumont25460f2290c0
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lockindex e24b28899..63d7dbe81 100755--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -8097,7 +8097,7 @@ dependencies = [[[package]]name = "screenpipe-app"-version = "2.0.487"+version = "2.0.488"dependencies = ["anyhow","arboard",diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 6ff5080bf..a36f299bb 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.0.487"+version = "2.0.488"description = "24/7 memory for your desktop. 100% local."authors = ["you"]license = ""diff --git a/crates/screenpipe-audio/src/metrics.rs b/crates/screenpipe-audio/src/metrics.rsindex 56148f02e..8a5911cf3 100644--- a/crates/screenpipe-audio/src/metrics.rs+++ b/crates/screenpipe-audio/src/metrics.rs@@ -55,6 +55,8 @@ pub struct AudioPipelineMetrics {// --- Timing ---pub started_at: Instant,+ /// Unix timestamp (secs) of most recent DB insert — used by health check to avoid DB queries+ pub last_db_write_ts: AtomicU64,}impl AudioPipelineMetrics {@@ -78,6 +80,7 @@ impl AudioPipelineMetrics {batch_pause_events: AtomicU64::new(0),batch_resume_events: AtomicU64::new(0),started_at: Instant::now(),+ last_db_write_ts: AtomicU64::new(0),}}@@ -128,6 +131,11 @@ impl AudioPipelineMetrics {pub fn record_db_insert(&self, word_count: u64) {self.db_inserted.fetch_add(1, Ordering::Relaxed);self.total_words.fetch_add(word_count, Ordering::Relaxed);+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_secs();+ self.last_db_write_ts.store(now, Ordering::Relaxed);}pub fn record_duplicate_blocked(&self) {@@ -207,6 +215,7 @@ impl AudioPipelineMetrics {} else {0.0},+ last_db_write_ts: self.last_db_write_ts.load(Ordering::Relaxed),}}}@@ -254,4 +263,6 @@ pub struct AudioMetricsSnapshot {pub vad_passthrough_rate: f64,/// Transcribed words per minute of uptimepub words_per_minute: f64,+ /// Unix timestamp (secs) of most recent DB insert (0 = none yet)+ pub last_db_write_ts: u64,}diff --git a/crates/screenpipe-server/src/routes/health.rs b/crates/screenpipe-server/src/routes/health.rsindex df2bf8332..c646b9b77 100644--- a/crates/screenpipe-server/src/routes/health.rs+++ b/crates/screenpipe-server/src/routes/health.rs@@ -9,11 +9,8 @@ use chrono::{TimeZone, Utc};use serde::{Deserialize, Serialize};use serde_json::json;-use std::{- sync::{atomic::Ordering, Arc},- time::Duration,-};-use tracing::{debug, error};+use std::sync::{atomic::Ordering, Arc};+use tracing::debug;use crate::server::AppState;@@ -150,47 +147,43 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He};}- let (last_frame, audio, _last_ui) = match state.db.get_latest_timestamps().await {- Ok((frame, audio, ui)) => (frame, audio, ui),- Err(e) => {- error!("failed to get latest timestamps: {}", e);- (None, None, None)- }+ // Read last-write timestamps from in-memory atomics instead of querying DB.+ // These are updated on every DB write by the vision/audio pipelines.+ let vision_snap = state.vision_metrics.snapshot();+ let audio_snap = state.audio_metrics.snapshot();++ let last_frame_ts = vision_snap.last_db_write_ts;+ let last_frame = if last_frame_ts > 0 {+ Utc.timestamp_opt(last_frame_ts as i64, 0).single()+ } else {+ None};+ let last_audio_ts = audio_snap.last_db_write_ts;+let now = Utc::now();- let threshold = Duration::from_secs(1800); // 30 minutes+ let threshold_secs = 1800u64; // 30 minuteslet frame_status = if state.vision_disabled {"disabled"+ } else if last_frame_ts == 0 {+ "not_started"+ } else if now.timestamp() as u64 - last_frame_ts < threshold_secs {+ "ok"} else {- match last_frame {- Some(timestamp)- if now.signed_duration_since(timestamp)- < chrono::Duration::from_std(threshold).unwrap() =>- {- "ok"- }- Some(_) => "stale",- None => "not_started",- }+ "stale"};let audio_status = if state.audio_disabled {"disabled".to_string()} else if global_audio_active {"ok".to_string()+ } else if last_audio_ts == 0 {+ "not_started".to_string()+ } else if now.timestamp() as u64 - last_audio_ts < threshold_secs {+ "stale".to_string()} else {- match audio {- Some(timestamp)- if now.signed_duration_since(timestamp)- < chrono::Duration::from_std(threshold).unwrap() =>- {- "stale".to_string()- }- Some(_) => "stale".to_string(),- None => "not_started".to_string(),- }+ "stale".to_string()};// Format device statuses as a string for a more detailed view@@ -258,25 +251,24 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<HeNone};- // Build pipeline metrics snapshot+ // Build pipeline metrics from the snapshot already taken abovelet pipeline = if !state.vision_disabled {- let snap = state.vision_metrics.snapshot();- let total_ocr_ops = snap.ocr_cache_hits + snap.ocr_cache_misses;+ let total_ocr_ops = vision_snap.ocr_cache_hits + vision_snap.ocr_cache_misses;Some(PipelineHealthInfo {- uptime_secs: snap.uptime_secs,- frames_captured: snap.frames_captured,- frames_db_written: snap.frames_db_written,- frames_dropped: snap.frames_dropped,- frame_drop_rate: snap.frame_drop_rate,- capture_fps_actual: snap.capture_fps_actual,- avg_ocr_latency_ms: snap.avg_ocr_latency_ms,- avg_db_latency_ms: snap.avg_db_latency_ms,- ocr_queue_depth: snap.ocr_queue_depth,- video_queue_depth: snap.video_queue_depth,- time_to_first_frame_ms: snap.time_to_first_frame_ms,- pipeline_stall_count: snap.pipeline_stall_count,+ uptime_secs: vision_snap.uptime_secs,+ frames_captured: vision_snap.frames_captured,+ frames_db_written: vision_snap.frames_db_written,+ frames_dropped: vision_snap.frames_dropped,+ frame_drop_rate: vision_snap.frame_drop_rate,+ capture_fps_actual: vision_snap.capture_fps_actual,+ avg_ocr_latency_ms: vision_snap.avg_ocr_latency_ms,+ avg_db_latency_ms: vision_snap.avg_db_latency_ms,+ ocr_queue_depth: vision_snap.ocr_queue_depth,+ video_queue_depth: vision_snap.video_queue_depth,+ time_to_first_frame_ms: vision_snap.time_to_first_frame_ms,+ pipeline_stall_count: vision_snap.pipeline_stall_count,ocr_cache_hit_rate: if total_ocr_ops > 0 {- snap.ocr_cache_hits as f64 / total_ocr_ops as f64+ vision_snap.ocr_cache_hits as f64 / total_ocr_ops as f64} else {0.0},@@ -289,11 +281,10 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<Hestatus: overall_status.to_string(),status_code,last_frame_timestamp: last_frame,- last_audio_timestamp: if most_recent_audio_timestamp > 0 {- Some(- Utc.timestamp_opt(most_recent_audio_timestamp as i64, 0)- .unwrap(),- )+ last_audio_timestamp: if last_audio_ts > 0 {+ Utc.timestamp_opt(last_audio_ts as i64, 0).single()+ } else if most_recent_audio_timestamp > 0 {+ Utc.timestamp_opt(most_recent_audio_timestamp as i64, 0).single()} else {None},@@ -305,7 +296,6 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<Hemonitors,pipeline,audio_pipeline: if !state.audio_disabled {- let snap = state.audio_metrics.snapshot();let is_paused = state.audio_manager.transcription_paused@@ -326,36 +316,36 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He};Some(AudioPipelineHealthInfo {- uptime_secs: snap.uptime_secs,- chunks_sent: snap.chunks_sent,- chunks_channel_full: snap.chunks_channel_full,- stream_timeouts: snap.stream_timeouts,- vad_passed: snap.vad_passed,- vad_rejected: snap.vad_rejected,- vad_passthrough_rate: snap.vad_passthrough_rate,- avg_speech_ratio: snap.avg_speech_ratio,- transcriptions_completed: snap.transcriptions_completed,- transcriptions_empty: snap.transcriptions_empty,- transcription_errors: snap.transcription_errors,- db_inserted: snap.db_inserted,- total_words: snap.total_words,- words_per_minute: snap.words_per_minute,+ uptime_secs: audio_snap.uptime_secs,+ chunks_sent: audio_snap.chunks_sent,+ chunks_channel_full: audio_snap.chunks_channel_full,+ stream_timeouts: audio_snap.stream_timeouts,+ vad_passed: audio_snap.vad_passed,+ vad_rejected: audio_snap.vad_rejected,+ vad_passthrough_rate: audio_snap.vad_passthrough_rate,+ avg_speech_ratio: audio_snap.avg_speech_ratio,+ transcriptions_completed: audio_snap.transcriptions_completed,+ transcriptions_empty: audio_snap.transcriptions_empty,+ transcription_errors: audio_snap.transcription_errors,+ db_inserted: audio_snap.db_inserted,+ total_words: audio_snap.total_words,+ words_per_minute: audio_snap.words_per_minute,// Batch/Smart mode- transcription_mode: if snap.segments_deferred > 0- || snap.segments_batch_processed > 0+ transcription_mode: if audio_snap.segments_deferred > 0+ || audio_snap.segments_batch_processed > 0{Some("smart".to_string())} else {Some("realtime".to_string())},transcription_paused: Some(is_paused),- segments_deferred: if snap.segments_deferred > 0 {- Some(snap.segments_deferred)+ segments_deferred: if audio_snap.segments_deferred > 0 {+ Some(audio_snap.segments_deferred)} else {None},- segments_batch_processed: if snap.segments_batch_processed > 0 {- Some(snap.segments_batch_processed)+ segments_batch_processed: if audio_snap.segments_batch_processed > 0 {+ Some(audio_snap.segments_batch_processed)} else {None},diff --git a/crates/screenpipe-vision/src/metrics.rs b/crates/screenpipe-vision/src/metrics.rsindex 9d8bdbcd5..1e8c09607 100644--- a/crates/screenpipe-vision/src/metrics.rs+++ b/crates/screenpipe-vision/src/metrics.rs@@ -52,6 +52,10 @@ pub struct PipelineMetrics {// --- Stalls ---/// Number of times capture was stuck >10s without sending a framepub pipeline_stall_count: AtomicU64,++ // --- Timestamps ---+ /// Unix timestamp (secs) of most recent DB write — used by health check to avoid DB queries+ pub last_db_write_ts: AtomicU64,}impl PipelineMetrics {@@ -72,6 +76,7 @@ impl PipelineMetrics {ocr_queue_depth: AtomicU64::new(0),video_queue_depth: AtomicU64::new(0),pipeline_stall_count: AtomicU64::new(0),+ last_db_write_ts: AtomicU64::new(0),}}@@ -106,6 +111,13 @@ impl PipelineMetrics {self.db_total_latency_us.fetch_add(latency.as_micros() as u64, Ordering::Relaxed);+ // Update last DB write timestamp for health check+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_secs();+ self.last_db_write_ts.store(now, Ordering::Relaxed);+// Record first frame time (only once — compare-and-swap from 0)if count == 0 {let elapsed_us = self.started_at.elapsed().as_micros() as u64;@@ -184,6 +196,7 @@ impl PipelineMetrics {ocr_queue_depth: self.ocr_queue_depth.load(Ordering::Relaxed),video_queue_depth: self.video_queue_depth.load(Ordering::Relaxed),pipeline_stall_count: self.pipeline_stall_count.load(Ordering::Relaxed),+ last_db_write_ts: self.last_db_write_ts.load(Ordering::Relaxed),}}}@@ -216,4 +229,6 @@ pub struct MetricsSnapshot {pub ocr_queue_depth: u64,pub video_queue_depth: u64,pub pipeline_stall_count: u64,+ /// Unix timestamp (secs) of most recent DB write (0 = none yet)+ pub last_db_write_ts: u64,}