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: pipes page loads 10x+ faster with batch DB queries

Louis Beaumont8e426dec0010
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index 803bd061b..bbf32fe67 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -193,6 +193,12 @@ pub trait PipeStore: Send + Sync {
/// Delete old executions, keeping only the newest `keep_per_pipe` per pipe.
/// Returns the number of rows deleted.
async fn cleanup_old_executions(&self, keep_per_pipe: i32) -> Result<u32>;
+
+ /// Get scheduler state for all pipes in a single query.
+ async fn get_all_scheduler_states(&self) -> Result<HashMap<String, SchedulerState>>;
+
+ /// Get recent executions for all pipes in a single query.
+ async fn get_all_executions(&self, limit_per_pipe: i32) -> Result<HashMap<String, Vec<PipeExecution>>>;
}
// ---------------------------------------------------------------------------
@@ -615,13 +621,17 @@ impl PipeManager {
};
// locks released
- // Pass 2: query DB for scheduler state (consecutive_failures)
+ // Pass 2: batch-query DB for all scheduler states (1 query instead of N)
+ let states = if let Some(ref store) = self.store {
+ store.get_all_scheduler_states().await.unwrap_or_default()
+ } else {
+ HashMap::new()
+ };
+
let mut result = Vec::with_capacity(partial.len());
for (name, mut status) in partial {
- if let Some(ref store) = self.store {
- if let Ok(Some(state)) = store.get_scheduler_state(&name).await {
- status.consecutive_failures = state.consecutive_failures;
- }
+ if let Some(state) = states.get(&name) {
+ status.consecutive_failures = state.consecutive_failures;
}
result.push(status);
}
@@ -691,15 +701,24 @@ impl PipeManager {
exec_limit: i32,
) -> Vec<(PipeStatus, Vec<PipeExecution>)> {
let statuses = self.list_pipes().await;
- let mut result = Vec::with_capacity(statuses.len());
- for status in statuses {
- let execs = self
- .get_executions(&status.config.name, exec_limit)
+
+ // Batch-fetch all executions in 1 query instead of N
+ let mut all_execs = if let Some(ref store) = self.store {
+ store
+ .get_all_executions(exec_limit)
.await
- .unwrap_or_default();
- result.push((status, execs));
- }
- result
+ .unwrap_or_default()
+ } else {
+ HashMap::new()
+ };
+
+ statuses
+ .into_iter()
+ .map(|status| {
+ let execs = all_execs.remove(&status.config.name).unwrap_or_default();
+ (status, execs)
+ })
+ .collect()
}
/// Run a pipe once (manual trigger or scheduled).
diff --git a/crates/screenpipe-server/src/pipe_store.rs b/crates/screenpipe-server/src/pipe_store.rs
index 925cabe87..c809ef657 100644
--- a/crates/screenpipe-server/src/pipe_store.rs
+++ b/crates/screenpipe-server/src/pipe_store.rs
@@ -206,6 +206,55 @@ impl PipeStore for SqlitePipeStore {
Ok(result.rows_affected() as u32)
}
+
+ async fn get_all_scheduler_states(
+ &self,
+ ) -> Result<std::collections::HashMap<String, SchedulerState>> {
+ let rows = sqlx::query_as::<_, SchedulerStateWithNameRow>(
+ "SELECT pipe_name, last_run_at, last_success_at, consecutive_failures FROM pipe_scheduler_state",
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|r| {
+ let name = r.pipe_name.clone();
+ (name, r.into())
+ })
+ .collect())
+ }
+
+ async fn get_all_executions(
+ &self,
+ limit_per_pipe: i32,
+ ) -> Result<std::collections::HashMap<String, Vec<PipeExecution>>> {
+ // Use ROW_NUMBER to get the newest N executions per pipe in 1 query
+ let rows = sqlx::query_as::<_, PipeExecutionRow>(
+ r#"SELECT id, pipe_name, status, trigger_type, pid, model, provider,
+ started_at, finished_at, stdout, stderr, exit_code,
+ error_type, error_message, duration_ms
+ FROM (
+ SELECT *, ROW_NUMBER() OVER (
+ PARTITION BY pipe_name ORDER BY id DESC
+ ) AS rn
+ FROM pipe_executions
+ )
+ WHERE rn <= ?
+ ORDER BY pipe_name, id DESC"#,
+ )
+ .bind(limit_per_pipe)
+ .fetch_all(&self.pool)
+ .await?;
+
+ let mut map: std::collections::HashMap<String, Vec<PipeExecution>> =
+ std::collections::HashMap::new();
+ for row in rows {
+ let name = row.pipe_name.clone();
+ map.entry(name).or_default().push(row.into());
+ }
+ Ok(map)
+ }
}
// ---------------------------------------------------------------------------
@@ -276,6 +325,30 @@ impl From<SchedulerStateRow> for SchedulerState {
}
}
+#[derive(sqlx::FromRow)]
+struct SchedulerStateWithNameRow {
+ pipe_name: String,
+ last_run_at: Option<String>,
+ last_success_at: Option<String>,
+ consecutive_failures: Option<i32>,
+}
+
+impl From<SchedulerStateWithNameRow> for SchedulerState {
+ fn from(r: SchedulerStateWithNameRow) -> Self {
+ SchedulerState {
+ last_run_at: r
+ .last_run_at
+ .and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok())
+ .map(|dt| dt.with_timezone(&chrono::Utc)),
+ last_success_at: r
+ .last_success_at
+ .and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok())
+ .map(|dt| dt.with_timezone(&chrono::Utc)),
+ consecutive_failures: r.consecutive_failures.unwrap_or(0),
+ }
+ }
+}
+
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
@@ -685,4 +758,51 @@ mod tests {
.unwrap();
assert_eq!(state.consecutive_failures, 0);
}
+
+ // -- Batch query tests ---------------------------------------------------
+
+ #[tokio::test]
+ async fn test_get_all_scheduler_states() {
+ let store = setup_test_store().await;
+ store.upsert_scheduler_state("pipe-a", true).await.unwrap();
+ store.upsert_scheduler_state("pipe-b", false).await.unwrap();
+ store.upsert_scheduler_state("pipe-b", false).await.unwrap();
+
+ let states = store.get_all_scheduler_states().await.unwrap();
+ assert_eq!(states.len(), 2);
+ assert_eq!(states["pipe-a"].consecutive_failures, 0);
+ assert_eq!(states["pipe-b"].consecutive_failures, 2);
+ }
+
+ #[tokio::test]
+ async fn test_get_all_scheduler_states_empty() {
+ let store = setup_test_store().await;
+ let states = store.get_all_scheduler_states().await.unwrap();
+ assert!(states.is_empty());
+ }
+
+ #[tokio::test]
+ async fn test_get_all_executions() {
+ let store = setup_test_store().await;
+ for _ in 0..5 {
+ store.create_execution("pipe-a", "manual", "m", None).await.unwrap();
+ }
+ for _ in 0..3 {
+ store.create_execution("pipe-b", "scheduled", "m", None).await.unwrap();
+ }
+
+ let all = store.get_all_executions(3).await.unwrap();
+ assert_eq!(all.len(), 2);
+ assert_eq!(all["pipe-a"].len(), 3); // limited to 3
+ assert_eq!(all["pipe-b"].len(), 3);
+ // newest first
+ assert!(all["pipe-a"][0].id > all["pipe-a"][1].id);
+ }
+
+ #[tokio::test]
+ async fn test_get_all_executions_empty() {
+ let store = setup_test_store().await;
+ let all = store.get_all_executions(5).await.unwrap();
+ assert!(all.is_empty());
+ }
}