1use std::sync::Arc;
14use std::time::Duration;
15
16use chrono::{TimeDelta, Utc};
17
18use uuid::Uuid;
19
20use crate::config::ServerConfig;
21use ironflow_artifacts::blob_store::BlobStore;
22use ironflow_store::entities::{PurgePolicy, PurgeReason};
23use ironflow_store::store::Store;
24use tokio::time::interval;
25use tokio_util::sync::CancellationToken;
26use tracing::{error, info, warn};
27
28#[cfg(feature = "prometheus")]
29use ironflow_core::metric_names::RUNS_PURGED_TOTAL;
30#[cfg(feature = "prometheus")]
31use metrics::counter;
32
33pub const DEFAULT_PURGE_INTERVAL: Duration = Duration::from_secs(86400);
35
36pub const DEFAULT_PURGE_BATCH_SIZE: u32 = 100;
38
39pub const DEFAULT_USAGE_RETENTION_DAYS: u32 = 30;
41
42pub const DEFAULT_SIGNAL_RETENTION_DAYS: u32 = 7;
44
45pub struct RunPurger {
72 store: Arc<dyn Store>,
73 blob_store: Option<Arc<dyn BlobStore>>,
74 pub(crate) policy: PurgePolicy,
75 pub(crate) interval: Duration,
76 batch_size: u32,
77 pub(crate) usage_retention_days: u32,
78 pub(crate) signal_retention_days: u32,
79}
80
81impl RunPurger {
82 pub fn new(store: Arc<dyn Store>, policy: PurgePolicy) -> Self {
84 Self {
85 store,
86 blob_store: None,
87 policy,
88 interval: DEFAULT_PURGE_INTERVAL,
89 batch_size: DEFAULT_PURGE_BATCH_SIZE,
90 usage_retention_days: DEFAULT_USAGE_RETENTION_DAYS,
91 signal_retention_days: DEFAULT_SIGNAL_RETENTION_DAYS,
92 }
93 }
94
95 pub fn from_config(store: Arc<dyn Store>, config: &ServerConfig) -> Self {
120 let policy = PurgePolicy {
121 max_age_days: config.purge_max_age_days,
122 max_runs_per_workflow: config.purge_max_runs_per_workflow,
123 dry_run: config.purge_dry_run,
124 };
125 Self::new(store, policy)
126 .interval(Duration::from_secs(config.purge_interval_secs))
127 .usage_retention_days(config.provider_account_usage_retention_days)
128 .signal_retention_days(config.signal_retention_days)
129 }
130
131 pub fn with_blob_store(mut self, blob_store: Option<Arc<dyn BlobStore>>) -> Self {
136 self.blob_store = blob_store;
137 self
138 }
139
140 pub fn interval(mut self, interval: Duration) -> Self {
142 self.interval = interval;
143 self
144 }
145
146 pub fn batch_size(mut self, batch_size: u32) -> Self {
148 self.batch_size = batch_size;
149 self
150 }
151
152 pub fn usage_retention_days(mut self, days: u32) -> Self {
167 self.usage_retention_days = days;
168 self
169 }
170
171 pub fn signal_retention_days(mut self, days: u32) -> Self {
189 self.signal_retention_days = days;
190 self
191 }
192
193 pub async fn run(self, shutdown: CancellationToken) {
195 let mut ticker = interval(self.interval);
196 ticker.tick().await;
197
198 info!(
199 interval_secs = self.interval.as_secs(),
200 batch_size = self.batch_size,
201 max_age_days = self.policy.max_age_days,
202 max_runs_per_workflow = self.policy.max_runs_per_workflow,
203 dry_run = self.policy.dry_run,
204 usage_retention_days = self.usage_retention_days,
205 signal_retention_days = self.signal_retention_days,
206 "purger started"
207 );
208
209 loop {
210 tokio::select! {
211 _ = shutdown.cancelled() => {
212 info!("purger stopped");
213 return;
214 }
215 _ = ticker.tick() => {
216 self.tick().await;
217 }
218 }
219 }
220 }
221
222 async fn purge_account_usage(&self) {
224 if self.policy.dry_run {
225 return;
226 }
227 let before = Utc::now() - TimeDelta::days(i64::from(self.usage_retention_days));
228 match self.store.purge_provider_account_usage(before).await {
229 Ok(0) => {}
230 Ok(deleted) => info!(deleted, "purged provider account usage history"),
231 Err(err) => error!(error = %err, "failed to purge provider account usage history"),
232 }
233 }
234
235 async fn purge_signals(&self) {
237 if self.policy.dry_run {
238 return;
239 }
240 let before = Utc::now() - TimeDelta::days(i64::from(self.signal_retention_days));
241 match self.store.purge_signals(before).await {
242 Ok(0) => {}
243 Ok(deleted) => info!(deleted, "purged old signals"),
244 Err(err) => error!(error = %err, "failed to purge old signals"),
245 }
246 }
247
248 pub async fn tick(&self) {
252 self.purge_account_usage().await;
253 self.purge_signals().await;
254
255 let purgeable = match self
256 .store
257 .list_purgeable_runs(&self.policy, self.batch_size)
258 .await
259 {
260 Ok(p) => p,
261 Err(err) => {
262 error!(error = %err, "failed to list purgeable runs");
263 return;
264 }
265 };
266
267 if purgeable.is_empty() {
268 return;
269 }
270
271 if self.policy.dry_run {
272 for entry in &purgeable {
273 info!(
274 run_id = %entry.run_id,
275 workflow = %entry.workflow_name,
276 reason = %entry.reason,
277 "[dry-run] would purge run"
278 );
279
280 #[cfg(feature = "prometheus")]
281 counter!(
282 RUNS_PURGED_TOTAL,
283 "workflow" => entry.workflow_name.clone(),
284 "reason" => entry.reason.to_string(),
285 "dry_run" => "true"
286 )
287 .increment(1);
288 }
289
290 return;
291 }
292
293 warn!(
294 count = purgeable.len(),
295 batch_size = self.batch_size,
296 "purging old runs"
297 );
298
299 for entry in &purgeable {
300 self.purge_run(entry.run_id, &entry.workflow_name, &entry.reason)
301 .await;
302 }
303 }
304
305 async fn purge_run(&self, run_id: Uuid, workflow_name: &str, reason: &PurgeReason) {
306 match self.store.delete_run(run_id).await {
307 Ok(storage_keys) => {
308 if let Some(ref blob_store) = self.blob_store {
309 for key in &storage_keys {
310 let refcount = self
311 .store
312 .count_artifacts_by_storage_key(key)
313 .await
314 .unwrap_or(0);
315 if refcount > 0 {
316 continue;
317 }
318 if let Err(err) = blob_store.delete(key).await {
319 error!(
320 run_id = %run_id,
321 storage_key = %key,
322 error = %err,
323 "failed to delete artifact blob"
324 );
325 }
326 }
327 }
328
329 info!(
330 run_id = %run_id,
331 workflow = %workflow_name,
332 reason = %reason,
333 "purged run"
334 );
335
336 #[cfg(feature = "prometheus")]
337 counter!(
338 RUNS_PURGED_TOTAL,
339 "workflow" => workflow_name.to_string(),
340 "reason" => reason.to_string(),
341 "dry_run" => "false"
342 )
343 .increment(1);
344 }
345 Err(err) => {
346 error!(
347 run_id = %run_id,
348 workflow = %workflow_name,
349 error = %err,
350 "failed to delete run during purge"
351 );
352 }
353 }
354 }
355}
356
357#[cfg(test)]
358mod tests {
359 use std::collections::HashMap;
360 use std::time::Duration;
361
362 use chrono::{TimeDelta, Utc};
363 use ironflow_store::entities::{
364 AccountWindowStatus, NewAccountWindow, NewProviderAccount, NewProviderAccountObservation,
365 NewRun, NewSignal, PurgePolicy, RunStatus, SignalFilter, TriggerKind,
366 provider_account_secret_key,
367 };
368 use ironflow_store::memory::InMemoryStore;
369 use ironflow_store::provider_account_store::ProviderAccountStore;
370 use ironflow_store::signal_store::SignalStore;
371 use ironflow_store::store::RunStore;
372 use serde_json::json;
373 use tokio::time::sleep;
374 use uuid::Uuid;
375
376 use super::*;
377
378 fn new_run(name: &str) -> NewRun {
379 NewRun {
380 workflow_name: name.to_string(),
381 trigger: TriggerKind::Manual,
382 payload: json!({}),
383 max_retries: 0,
384 handler_version: None,
385 labels: HashMap::new(),
386 scheduled_at: None,
387 created_by: None,
388 idempotency_key: None,
389 max_cost_usd: None,
390 }
391 }
392
393 async fn create_terminal_run(store: &InMemoryStore, name: &str, status: RunStatus) -> Uuid {
394 let run = store.create_run(new_run(name)).await.unwrap().into_run();
395 store
396 .update_run_status(run.id, RunStatus::Running)
397 .await
398 .unwrap();
399 store.update_run_status(run.id, status).await.unwrap();
400 run.id
401 }
402
403 async fn backdate_run(store: &InMemoryStore, run_id: Uuid, days: i64) {
404 store
405 .set_run_created_at(run_id, Utc::now() - TimeDelta::days(days))
406 .await;
407 }
408
409 fn build(store: Arc<InMemoryStore>, policy: PurgePolicy) -> RunPurger {
410 let store_dyn: Arc<dyn Store> = store;
411 RunPurger::new(store_dyn, policy)
412 }
413
414 #[tokio::test]
415 async fn purger_purges_old_provider_account_usage() {
416 let store = Arc::new(InMemoryStore::new());
417 let id = Uuid::now_v7();
418 store
419 .create_provider_account(NewProviderAccount {
420 id,
421 name: "perso".to_string(),
422 display_name: "Perso".to_string(),
423 kind: "claude_subscription".to_string(),
424 secret_key: provider_account_secret_key(id),
425 enabled: true,
426 priority: 100,
427 tags: Vec::new(),
428 max_concurrency: None,
429 alert_threshold: 0.8,
430 expires_at: Utc::now() + TimeDelta::days(365),
431 plan: None,
432 created_by: None,
433 })
434 .await
435 .unwrap();
436 let window = |days_ago: i64| NewAccountWindow {
437 window: "five_hour".to_string(),
438 utilization: 0.5,
439 resets_at: None,
440 status: AccountWindowStatus::Allowed,
441 model_scope: None,
442 observed_at: Utc::now() - TimeDelta::days(days_ago),
443 };
444 store
445 .record_provider_account_observation(
446 id,
447 NewProviderAccountObservation {
448 windows: vec![window(40), window(1)],
449 auth_failed: false,
450 },
451 )
452 .await
453 .unwrap();
454
455 let policy = PurgePolicy {
456 max_age_days: 90,
457 max_runs_per_workflow: 10000,
458 dry_run: false,
459 };
460 build(store.clone(), policy)
461 .usage_retention_days(30)
462 .tick()
463 .await;
464
465 let history = store
466 .list_provider_account_usage(id, Utc::now() - TimeDelta::days(90))
467 .await
468 .unwrap();
469 assert_eq!(history.len(), 1);
470 }
471
472 #[tokio::test]
473 async fn tick_purges_runs_older_than_max_age() {
474 let store = Arc::new(InMemoryStore::new());
475 let old_id = create_terminal_run(&store, "deploy", RunStatus::Completed).await;
476 backdate_run(&store, old_id, 100).await;
477 let recent_id = create_terminal_run(&store, "deploy", RunStatus::Completed).await;
478
479 let policy = PurgePolicy {
480 max_age_days: 90,
481 max_runs_per_workflow: 10000,
482 dry_run: false,
483 };
484 let purger = build(store.clone(), policy);
485 purger.tick().await;
486
487 assert!(store.get_run(old_id).await.unwrap().is_none());
488 assert!(store.get_run(recent_id).await.unwrap().is_some());
489 }
490
491 #[tokio::test]
492 async fn tick_in_dry_run_does_not_delete() {
493 let store = Arc::new(InMemoryStore::new());
494 let old_id = create_terminal_run(&store, "deploy", RunStatus::Completed).await;
495 backdate_run(&store, old_id, 100).await;
496
497 let policy = PurgePolicy {
498 max_age_days: 90,
499 max_runs_per_workflow: 10000,
500 dry_run: true,
501 };
502 let purger = build(store.clone(), policy);
503 purger.tick().await;
504
505 assert!(store.get_run(old_id).await.unwrap().is_some());
506 }
507
508 #[tokio::test]
509 async fn tick_does_not_purge_non_terminal_runs() {
510 let store = Arc::new(InMemoryStore::new());
511 let pending = store
512 .create_run(new_run("deploy"))
513 .await
514 .unwrap()
515 .into_run();
516 backdate_run(&store, pending.id, 200).await;
517
518 let running = store
519 .create_run(new_run("deploy"))
520 .await
521 .unwrap()
522 .into_run();
523 store
524 .update_run_status(running.id, RunStatus::Running)
525 .await
526 .unwrap();
527 backdate_run(&store, running.id, 200).await;
528
529 let policy = PurgePolicy {
530 max_age_days: 90,
531 max_runs_per_workflow: 10000,
532 dry_run: false,
533 };
534 let purger = build(store.clone(), policy);
535 purger.tick().await;
536
537 assert!(store.get_run(pending.id).await.unwrap().is_some());
538 assert!(store.get_run(running.id).await.unwrap().is_some());
539 }
540
541 #[tokio::test]
542 async fn purge_does_not_delete_blob_when_shared_by_another_artifact() {
543 use ironflow_artifacts::local::LocalBlobStore;
544 use ironflow_artifacts::stream_from_bytes;
545 use ironflow_store::artifact_store::ArtifactStore;
546 use ironflow_store::entities::{NewArtifact, NewStep, StepKind, step_trace_id};
547 use ironflow_store::store::Store;
548 use tempfile::TempDir;
549
550 let dir = TempDir::new().expect("temp dir");
551 let store = Arc::new(InMemoryStore::new());
552 let blob: Arc<dyn BlobStore> = Arc::new(LocalBlobStore::new(dir.path()));
553
554 let run_a = store.create_run(new_run("wf")).await.unwrap().into_run();
556 store
557 .update_run_status(run_a.id, RunStatus::Running)
558 .await
559 .unwrap();
560 store
561 .update_run_status(run_a.id, RunStatus::Completed)
562 .await
563 .unwrap();
564 backdate_run(&store, run_a.id, 100).await;
565
566 let step_a = store
567 .create_step(NewStep {
568 run_id: run_a.id,
569 trace_id: step_trace_id(run_a.id, "build", 0),
570 name: "build".to_string(),
571 kind: StepKind::Shell,
572 position: 0,
573 input: None,
574 is_error_handler: false,
575 })
576 .await
577 .unwrap();
578
579 let run_b = store.create_run(new_run("wf")).await.unwrap().into_run();
580 let step_b = store
581 .create_step(NewStep {
582 run_id: run_b.id,
583 trace_id: step_trace_id(run_b.id, "build", 0),
584 name: "build".to_string(),
585 kind: StepKind::Shell,
586 position: 0,
587 input: None,
588 is_error_handler: false,
589 })
590 .await
591 .unwrap();
592
593 let shared_key = "artifacts/shared/blob";
595 blob.put(shared_key, stream_from_bytes(b"shared".to_vec()))
596 .await
597 .unwrap();
598
599 let id_a = Uuid::now_v7();
600 store
601 .create_artifact(NewArtifact {
602 id: id_a,
603 run_id: run_a.id,
604 step_id: step_a.id,
605 name: "report.txt".to_string(),
606 storage_key: shared_key.to_string(),
607 content_type: "text/plain".to_string(),
608 size_bytes: 6,
609 sha256: "abc".repeat(21),
610 })
611 .await
612 .unwrap();
613
614 let id_b = Uuid::now_v7();
615 store
616 .create_artifact(NewArtifact {
617 id: id_b,
618 run_id: run_b.id,
619 step_id: step_b.id,
620 name: "report.txt".to_string(),
621 storage_key: shared_key.to_string(),
622 content_type: "text/plain".to_string(),
623 size_bytes: 6,
624 sha256: "abc".repeat(21),
625 })
626 .await
627 .unwrap();
628
629 let policy = PurgePolicy {
631 max_age_days: 90,
632 max_runs_per_workflow: 10000,
633 dry_run: false,
634 };
635 let store_dyn: Arc<dyn Store> = store.clone();
636 let purger = RunPurger::new(store_dyn, policy).with_blob_store(Some(blob.clone()));
637 purger.tick().await;
638
639 assert!(
640 store.get_run(run_a.id).await.unwrap().is_none(),
641 "run_a purged"
642 );
643 assert!(
644 store.get_run(run_b.id).await.unwrap().is_some(),
645 "run_b kept"
646 );
647
648 let get_result = blob.get(shared_key).await;
650 assert!(get_result.is_ok(), "shared blob should not be deleted");
651 }
652
653 #[tokio::test]
654 async fn purger_tick_purges_old_signals() {
655 let store = Arc::new(InMemoryStore::new());
656 store
657 .insert_signal(NewSignal {
658 name: "demo.done".to_string(),
659 key: "k1".to_string(),
660 payload: json!({}),
661 idempotency_id: None,
662 })
663 .await
664 .unwrap();
665 sleep(Duration::from_millis(5)).await;
666 let policy = PurgePolicy {
667 max_age_days: 90,
668 max_runs_per_workflow: 1000,
669 dry_run: false,
670 };
671
672 build(store.clone(), policy.clone())
674 .signal_retention_days(1)
675 .tick()
676 .await;
677 let kept = store
678 .list_signals(SignalFilter::default(), 1, 20)
679 .await
680 .unwrap();
681 assert_eq!(kept.total, 1);
682
683 build(store.clone(), policy)
685 .signal_retention_days(0)
686 .tick()
687 .await;
688 let purged = store
689 .list_signals(SignalFilter::default(), 1, 20)
690 .await
691 .unwrap();
692 assert_eq!(purged.total, 0);
693 }
694
695 #[tokio::test]
696 async fn run_stops_on_shutdown() {
697 let store = Arc::new(InMemoryStore::new());
698 let policy = PurgePolicy {
699 max_age_days: 90,
700 max_runs_per_workflow: 1000,
701 dry_run: false,
702 };
703 let purger = build(store, policy);
704 let shutdown = CancellationToken::new();
705 shutdown.cancel();
706
707 tokio::time::timeout(Duration::from_secs(5), purger.run(shutdown))
708 .await
709 .expect("purger stopped");
710 }
711}