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: auto-cleanup pipe executions to prevent DB bloat

Louis Beaumontb4afbe9f285b
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index 308c0060d..803bd061b 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -189,6 +189,10 @@ pub trait PipeStore: Send + Sync {
/// Update scheduler state after a run.
async fn upsert_scheduler_state(&self, pipe_name: &str, success: bool) -> Result<()>;
+
+ /// 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>;
}
// ---------------------------------------------------------------------------
@@ -413,7 +417,8 @@ impl PipeManager {
self.on_output_line = Some(cb);
}
- /// Mark orphaned 'running' executions as failed on startup.
+ /// Mark orphaned 'running' executions as failed on startup,
+ /// then prune old executions (keep 50 per pipe).
pub async fn startup_recovery(&self) {
if let Some(ref store) = self.store {
match store.mark_orphaned_running().await {
@@ -429,6 +434,24 @@ impl PipeManager {
warn!("startup recovery failed: {}", e);
}
}
+ // Prune old executions to prevent DB bloat
+ self.cleanup_executions().await;
+ }
+ }
+
+ /// Delete old pipe executions, keeping only the newest 50 per pipe.
+ pub async fn cleanup_executions(&self) {
+ if let Some(ref store) = self.store {
+ match store.cleanup_old_executions(50).await {
+ Ok(count) => {
+ if count > 0 {
+ info!("pipe cleanup: deleted {} old executions", count);
+ }
+ }
+ Err(e) => {
+ warn!("pipe cleanup failed: {}", e);
+ }
+ }
}
}
@@ -893,8 +916,8 @@ impl PipeManager {
.finish_execution(
id,
status,
- &output.stdout,
- &output.stderr,
+ &truncate_string(&output.stdout, 50_000),
+ &truncate_string(&output.stderr, 10_000),
None,
error_type.as_deref(),
error_message.as_deref(),
@@ -1219,8 +1242,8 @@ impl PipeManager {
.finish_execution(
id,
status,
- &output.stdout,
- &output.stderr,
+ &truncate_string(&output.stdout, 50_000),
+ &truncate_string(&output.stderr, 10_000),
None,
error_type.as_deref(),
error_message.as_deref(),
@@ -1602,6 +1625,7 @@ impl PipeManager {
tokio::spawn(async move {
info!("pipe scheduler started");
let mut last_run: HashMap<String, DateTime<Utc>> = HashMap::new();
+ let mut last_cleanup = Instant::now();
// Load last_run from DB on first tick
if let Some(ref store) = store {
@@ -1861,8 +1885,8 @@ impl PipeManager {
.finish_execution(
id,
status,
- &output.stdout,
- &output.stderr,
+ &truncate_string(&output.stdout, 50_000),
+ &truncate_string(&output.stderr, 10_000),
None,
error_type.as_deref(),
error_message.as_deref(),
@@ -1989,6 +2013,20 @@ impl PipeManager {
});
}
+ // Daily cleanup: prune old executions every 24h
+ if last_cleanup.elapsed() >= std::time::Duration::from_secs(86400) {
+ if let Some(ref store) = store {
+ match store.cleanup_old_executions(50).await {
+ Ok(count) if count > 0 => {
+ info!("scheduler cleanup: deleted {} old executions", count);
+ }
+ Err(e) => warn!("scheduler cleanup failed: {}", e),
+ _ => {}
+ }
+ }
+ last_cleanup = Instant::now();
+ }
+
// Sleep 30s between checks
tokio::select! {
_ = tokio::time::sleep(std::time::Duration::from_secs(30)) => {},
diff --git a/crates/screenpipe-server/src/pipe_store.rs b/crates/screenpipe-server/src/pipe_store.rs
index d8709760b..925cabe87 100644
--- a/crates/screenpipe-server/src/pipe_store.rs
+++ b/crates/screenpipe-server/src/pipe_store.rs
@@ -184,6 +184,28 @@ impl PipeStore for SqlitePipeStore {
Ok(())
}
+
+ async fn cleanup_old_executions(&self, keep_per_pipe: i32) -> Result<u32> {
+ // Delete all rows except the newest `keep_per_pipe` per pipe_name.
+ // Uses a CTE to find the cutoff id per pipe.
+ let result = sqlx::query(
+ r#"DELETE FROM pipe_executions
+ WHERE id NOT IN (
+ SELECT id FROM (
+ SELECT id, ROW_NUMBER() OVER (
+ PARTITION BY pipe_name ORDER BY id DESC
+ ) AS rn
+ FROM pipe_executions
+ )
+ WHERE rn <= ?
+ )"#,
+ )
+ .bind(keep_per_pipe)
+ .execute(&self.pool)
+ .await?;
+
+ Ok(result.rows_affected() as u32)
+ }
}
// ---------------------------------------------------------------------------
@@ -571,6 +593,50 @@ mod tests {
assert!(state.last_success_at.is_some());
}
+ #[tokio::test]
+ async fn test_cleanup_old_executions() {
+ let store = setup_test_store().await;
+
+ // Create 5 executions for pipe-a and 3 for pipe-b
+ for _ in 0..5 {
+ store
+ .create_execution("pipe-a", "scheduled", "m", None)
+ .await
+ .unwrap();
+ }
+ for _ in 0..3 {
+ store
+ .create_execution("pipe-b", "scheduled", "m", None)
+ .await
+ .unwrap();
+ }
+
+ // Keep only 2 per pipe — should delete 3 from pipe-a and 1 from pipe-b
+ let deleted = store.cleanup_old_executions(2).await.unwrap();
+ assert_eq!(deleted, 4);
+
+ let execs_a = store.get_executions("pipe-a", 10).await.unwrap();
+ assert_eq!(execs_a.len(), 2);
+
+ let execs_b = store.get_executions("pipe-b", 10).await.unwrap();
+ assert_eq!(execs_b.len(), 2);
+ }
+
+ #[tokio::test]
+ async fn test_cleanup_noop_when_under_limit() {
+ let store = setup_test_store().await;
+ store
+ .create_execution("pipe-a", "manual", "m", None)
+ .await
+ .unwrap();
+
+ let deleted = store.cleanup_old_executions(50).await.unwrap();
+ assert_eq!(deleted, 0);
+
+ let execs = store.get_executions("pipe-a", 10).await.unwrap();
+ assert_eq!(execs.len(), 1);
+ }
+
#[tokio::test]
async fn test_full_execution_lifecycle() {
let store = setup_test_store().await;