Skip to content

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

fix: cache health check responses and add elements query index

Louis Beaumontf817e2199d8b
diff --git a/crates/screenpipe-db/src/migrations/20260316000000_add_elements_activity_summary_index.sql b/crates/screenpipe-db/src/migrations/20260316000000_add_elements_activity_summary_index.sql
new file mode 100644
index 000000000..f6361ba64
--- /dev/null
+++ b/crates/screenpipe-db/src/migrations/20260316000000_add_elements_activity_summary_index.sql
@@ -0,0 +1,11 @@
+-- Covering index for the activity_summary query:
+-- SELECT DISTINCT e.text, f.app_name, f.timestamp
+-- FROM elements e JOIN frames f ON f.id = e.frame_id
+-- WHERE ... e.text IS NOT NULL AND e.source IN (...) AND e.role IN (...)
+--
+-- The existing idx_elements_frame_source covers (frame_id, source) but the
+-- query also filters on role and needs text. Without this index SQLite does
+-- a full scan + sort on the elements table, taking 1-16 seconds on large DBs.
+CREATE INDEX IF NOT EXISTS idx_elements_source_role_text
+ ON elements(source, role, frame_id)
+ WHERE text IS NOT NULL;
diff --git a/crates/screenpipe-engine/src/routes/health.rs b/crates/screenpipe-engine/src/routes/health.rs
index 1cfadb3ea..1feb60d38 100644
--- a/crates/screenpipe-engine/src/routes/health.rs
+++ b/crates/screenpipe-engine/src/routes/health.rs
@@ -14,11 +14,21 @@ use std::sync::{
Arc,
};
use std::time::Duration;
+use tokio::sync::RwLock;
use tracing::{debug, warn};
use crate::server::AppState;
use crate::ui_recorder::{tree_walker_snapshot, TreeWalkerSnapshot};
+/// Cached health response to avoid recomputing on every poll.
+/// Multiple WebSocket clients + HTTP polls can call /health dozens of
+/// times per second. The response only changes meaningfully every ~1s.
+static HEALTH_CACHE: std::sync::LazyLock<RwLock<(u64, Option<HealthCheckResponse>)>> =
+ std::sync::LazyLock::new(|| RwLock::new((0, None)));
+
+/// Minimum interval between full health recomputations (in seconds).
+const HEALTH_CACHE_TTL_SECS: u64 = 1;
+
use screenpipe_screen::monitor::{
get_cached_monitor_descriptions, get_monitor_by_id, list_monitors, list_monitors_detailed,
MonitorListError,
@@ -34,7 +44,7 @@ pub struct MonitorInfo {
pub is_default: bool,
}
-#[derive(Serialize, OaSchema, Deserialize)]
+#[derive(Serialize, OaSchema, Deserialize, Clone)]
pub struct HealthCheckResponse {
pub status: String,
pub status_code: u16,
@@ -63,7 +73,7 @@ pub struct HealthCheckResponse {
pub audio_db_write_stalled: bool,
}
-#[derive(Serialize, OaSchema, Deserialize)]
+#[derive(Serialize, OaSchema, Deserialize, Clone)]
pub struct PoolHealthInfo {
pub read_pool_size: u32,
pub read_pool_idle: u32,
@@ -71,7 +81,7 @@ pub struct PoolHealthInfo {
pub write_pool_idle: u32,
}
-#[derive(Serialize, OaSchema, Deserialize)]
+#[derive(Serialize, OaSchema, Deserialize, Clone)]
pub struct PipelineHealthInfo {
pub uptime_secs: f64,
pub frames_captured: u64,
@@ -88,7 +98,7 @@ pub struct PipelineHealthInfo {
pub ocr_cache_hit_rate: f64,
}
-#[derive(Serialize, OaSchema, Deserialize)]
+#[derive(Serialize, OaSchema, Deserialize, Clone)]
pub struct AudioPipelineHealthInfo {
pub uptime_secs: f64,
pub chunks_sent: u64,
@@ -134,6 +144,35 @@ pub struct AudioPipelineHealthInfo {
#[oasgen]
pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<HealthCheckResponse> {
+ let now_ts = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
+
+ // Return cached response if still fresh. This prevents thundering-herd
+ // scenarios where dozens of WebSocket clients + HTTP polls recompute the
+ // full health response simultaneously.
+ {
+ let cache = HEALTH_CACHE.read().await;
+ if now_ts.saturating_sub(cache.0) < HEALTH_CACHE_TTL_SECS {
+ if let Some(ref cached) = cache.1 {
+ return JsonResponse(cached.clone());
+ }
+ }
+ }
+
+ let response = health_check_inner(&state).await;
+
+ // Cache the result
+ {
+ let mut cache = HEALTH_CACHE.write().await;
+ *cache = (now_ts, Some(response.clone()));
+ }
+
+ JsonResponse(response)
+}
+
+async fn health_check_inner(state: &Arc<AppState>) -> HealthCheckResponse {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
@@ -479,7 +518,7 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
None
};
- JsonResponse(HealthCheckResponse {
+ HealthCheckResponse {
status: overall_status.to_string(),
status_code,
last_frame_timestamp: last_frame,
@@ -601,7 +640,7 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
},
vision_db_write_stalled,
audio_db_write_stalled,
- })
+ }
}
/// Returns raw vision pipeline metrics snapshot.
@@ -704,3 +743,71 @@ pub async fn api_vision_status() -> JsonResponse<serde_json::Value> {
})),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn dummy_response(status: &str) -> HealthCheckResponse {
+ HealthCheckResponse {
+ status: status.to_string(),
+ status_code: 200,
+ last_frame_timestamp: None,
+ last_audio_timestamp: None,
+ frame_status: "ok".to_string(),
+ audio_status: "ok".to_string(),
+ message: "test".to_string(),
+ verbose_instructions: None,
+ device_status_details: None,
+ monitors: None,
+ pipeline: None,
+ audio_pipeline: None,
+ accessibility: None,
+ pool_stats: None,
+ vision_db_write_stalled: false,
+ audio_db_write_stalled: false,
+ }
+ }
+
+ #[tokio::test]
+ async fn health_cache_fresh_then_stale() {
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
+
+ // Seed the cache with a fresh timestamp
+ {
+ let mut cache = HEALTH_CACHE.write().await;
+ *cache = (now, Some(dummy_response("healthy")));
+ }
+
+ // Reading within TTL should return the cached value
+ {
+ let cache = HEALTH_CACHE.read().await;
+ assert!(now.saturating_sub(cache.0) < HEALTH_CACHE_TTL_SECS);
+ assert_eq!(cache.1.as_ref().unwrap().status, "healthy");
+ }
+
+ // Now seed a stale timestamp
+ let stale_ts = now - HEALTH_CACHE_TTL_SECS - 1;
+ {
+ let mut cache = HEALTH_CACHE.write().await;
+ *cache = (stale_ts, Some(dummy_response("degraded")));
+ }
+
+ // Should be expired
+ {
+ let cache = HEALTH_CACHE.read().await;
+ assert!(now.saturating_sub(cache.0) >= HEALTH_CACHE_TTL_SECS);
+ }
+ }
+
+ #[test]
+ fn health_response_is_cloneable() {
+ let resp = dummy_response("healthy");
+ let cloned = resp.clone();
+ assert_eq!(cloned.status, "healthy");
+ assert_eq!(cloned.status_code, 200);
+ }
+}