1use crate::error::{GraphError, Result};
26use crate::state::Checkpoint;
27use async_trait::async_trait;
28use std::collections::{BTreeSet, HashMap};
29use std::sync::Arc;
30use tokio::sync::RwLock;
31
32#[derive(Debug, Clone, Default, PartialEq, Eq)]
58#[non_exhaustive]
59pub struct RetentionPolicy {
60 pub max_per_thread: Option<usize>,
62 pub max_age: Option<std::time::Duration>,
64 pub pinned: BTreeSet<String>,
66}
67
68impl RetentionPolicy {
69 pub fn keep_last(count: usize) -> Self {
73 Self { max_per_thread: Some(count.max(1)), ..Self::default() }
74 }
75
76 pub fn max_age(age: std::time::Duration) -> Self {
78 Self { max_age: Some(age), ..Self::default() }
79 }
80
81 pub fn with_max_age(mut self, age: std::time::Duration) -> Self {
83 self.max_age = Some(age);
84 self
85 }
86
87 pub fn with_max_per_thread(mut self, count: usize) -> Self {
89 self.max_per_thread = Some(count.max(1));
90 self
91 }
92
93 pub fn pinning<I, S>(mut self, checkpoint_ids: I) -> Self
107 where
108 I: IntoIterator<Item = S>,
109 S: Into<String>,
110 {
111 self.pinned.extend(checkpoint_ids.into_iter().map(Into::into));
112 self
113 }
114
115 pub fn is_unlimited(&self) -> bool {
117 self.max_per_thread.is_none() && self.max_age.is_none()
118 }
119
120 pub fn expired(&self, checkpoints: &[Checkpoint]) -> Vec<String> {
138 if self.is_unlimited() || checkpoints.len() <= 1 {
139 return Vec::new();
140 }
141 let needed = needed_to_resume(checkpoints);
142 let mut ordered: Vec<&Checkpoint> = checkpoints.iter().collect();
143 ordered.sort_by_key(|checkpoint| std::cmp::Reverse(checkpoint.version));
145
146 let cutoff = self.max_age.and_then(|age| {
147 chrono::Duration::from_std(age).ok().map(|age| chrono::Utc::now() - age)
148 });
149
150 ordered
151 .iter()
152 .enumerate()
153 .filter(|(index, checkpoint)| {
154 !needed.contains(&checkpoint.checkpoint_id)
155 && !self.pinned.contains(&checkpoint.checkpoint_id)
156 && (self.max_per_thread.is_some_and(|max| *index >= max)
157 || cutoff.is_some_and(|cutoff| checkpoint.created_at < cutoff))
158 })
159 .map(|(_, checkpoint)| checkpoint.checkpoint_id.clone())
160 .collect()
161 }
162}
163
164pub fn needed_to_resume(checkpoints: &[Checkpoint]) -> BTreeSet<String> {
196 let mut needed = BTreeSet::new();
197 let Some(newest) = checkpoints.iter().max_by_key(|checkpoint| checkpoint.version) else {
198 return needed;
199 };
200 needed.insert(newest.checkpoint_id.clone());
201 needed.extend(newest.open_pauses().unwrap_or_default());
204 needed.extend(
205 checkpoints
206 .iter()
207 .filter(|checkpoint| {
208 checkpoint.metadata.contains_key(crate::governed::EFFECT_METADATA_KEY)
209 })
210 .map(|checkpoint| checkpoint.checkpoint_id.clone()),
211 );
212 needed
213}
214
215#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
240#[non_exhaustive]
241pub enum Durability {
242 Exit,
244 Async,
246 #[default]
248 Sync,
249}
250
251pub fn ensure_newer(checkpoint: &Checkpoint, head: Option<u64>) -> Result<()> {
271 if checkpoint.version == 0 {
272 return Err(GraphError::CheckpointError(format!(
273 "checkpoint '{}' has version 0; versions start at 1. Set it with \
274 Checkpoint::with_version(newest version + 1)",
275 checkpoint.checkpoint_id
276 )));
277 }
278 match head {
279 Some(head) if head >= checkpoint.version => Err(conflict(checkpoint, head)),
280 _ => Ok(()),
281 }
282}
283
284pub fn conflict(checkpoint: &Checkpoint, head: u64) -> GraphError {
296 GraphError::CheckpointConflict {
297 thread_id: checkpoint.thread_id.clone(),
298 version: checkpoint.version,
299 head,
300 }
301}
302
303pub fn duplicate_id(checkpoint_id: &str) -> GraphError {
313 GraphError::CheckpointError(format!(
314 "checkpoint id '{checkpoint_id}' is already stored; every checkpoint needs a unique id"
315 ))
316}
317
318#[async_trait]
320pub trait Checkpointer: Send + Sync {
321 async fn save(&self, checkpoint: &Checkpoint) -> Result<String>;
329
330 async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>>;
332
333 async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>>;
335
336 async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>>;
338
339 async fn list_page(
350 &self,
351 thread_id: &str,
352 before: Option<u64>,
353 limit: usize,
354 ) -> Result<Vec<Checkpoint>> {
355 let mut checkpoints = self.list(thread_id).await?;
356 checkpoints.retain(|checkpoint| before.is_none_or(|before| checkpoint.version < before));
357 checkpoints.sort_by_key(|checkpoint| std::cmp::Reverse(checkpoint.version));
358 checkpoints.truncate(limit);
359 Ok(checkpoints)
360 }
361
362 async fn delete(&self, thread_id: &str) -> Result<()>;
371
372 async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize>;
381}
382
383#[derive(Default)]
384struct MemoryStore {
385 threads: HashMap<String, Vec<Checkpoint>>,
387 ids: HashMap<String, String>,
389}
390
391#[derive(Default)]
407pub struct MemoryCheckpointer {
408 store: Arc<RwLock<MemoryStore>>,
409}
410
411impl MemoryCheckpointer {
412 pub fn new() -> Self {
414 Self::default()
415 }
416}
417
418#[async_trait]
419impl Checkpointer for MemoryCheckpointer {
420 async fn save(&self, checkpoint: &Checkpoint) -> Result<String> {
421 let mut store = self.store.write().await;
422 let head = store
423 .threads
424 .get(&checkpoint.thread_id)
425 .and_then(|thread| thread.last())
426 .map(|newest| newest.version);
427 ensure_newer(checkpoint, head)?;
428 if store.ids.contains_key(&checkpoint.checkpoint_id) {
429 return Err(duplicate_id(&checkpoint.checkpoint_id));
430 }
431 store.ids.insert(checkpoint.checkpoint_id.clone(), checkpoint.thread_id.clone());
432 store.threads.entry(checkpoint.thread_id.clone()).or_default().push(checkpoint.clone());
433 Ok(checkpoint.checkpoint_id.clone())
434 }
435
436 async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>> {
437 let store = self.store.read().await;
438 Ok(store.threads.get(thread_id).and_then(|thread| thread.last()).cloned())
439 }
440
441 async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>> {
442 let store = self.store.read().await;
443 Ok(store.ids.get(checkpoint_id).and_then(|thread_id| {
444 store.threads.get(thread_id)?.iter().find(|c| c.checkpoint_id == checkpoint_id).cloned()
445 }))
446 }
447
448 async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>> {
449 let store = self.store.read().await;
450 Ok(store.threads.get(thread_id).cloned().unwrap_or_default())
451 }
452
453 async fn delete(&self, thread_id: &str) -> Result<()> {
454 let mut store = self.store.write().await;
455 if let Some(thread) = store.threads.remove(thread_id) {
456 for checkpoint in thread {
457 store.ids.remove(&checkpoint.checkpoint_id);
458 }
459 }
460 Ok(())
461 }
462
463 async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize> {
464 let mut store = self.store.write().await;
465 let Some(thread) = store.threads.get_mut(thread_id) else { return Ok(0) };
466 let expired = policy.expired(thread);
467 if expired.is_empty() {
468 return Ok(0);
469 }
470 let before = thread.len();
471 thread.retain(|checkpoint| !expired.contains(&checkpoint.checkpoint_id));
472 let removed = before - thread.len();
473 for checkpoint_id in &expired {
474 store.ids.remove(checkpoint_id);
475 }
476 Ok(removed)
477 }
478}
479
480#[cfg(feature = "sqlite")]
486pub struct SqliteCheckpointer {
487 pool: sqlx::SqlitePool,
488}
489
490#[cfg(feature = "sqlite")]
491fn sqlite_error(error: sqlx::Error) -> GraphError {
492 GraphError::CheckpointError(error.to_string())
493}
494
495#[cfg(feature = "sqlite")]
496fn sqlite_row(row: &sqlx::sqlite::SqliteRow) -> Result<Checkpoint> {
497 use sqlx::Row;
498 let text = |column: &str| row.try_get::<String, _>(column).map_err(sqlite_error);
499 let optional = |column: &str| row.try_get::<Option<String>, _>(column).map_err(sqlite_error);
500 fn json_or_default<T: serde::de::DeserializeOwned + Default>(raw: Option<String>) -> Result<T> {
501 Ok(raw.map(|raw| serde_json::from_str(&raw)).transpose()?.unwrap_or_default())
502 }
503 let attempts = json_or_default(optional("attempts")?)?;
504 let child_ledger = json_or_default(optional("child_ledger")?)?;
505 let pending_writes = json_or_default(optional("pending_writes")?)?;
506 Ok(Checkpoint {
507 checkpoint_id: text("id")?,
508 thread_id: text("thread_id")?,
509 state: serde_json::from_str(&text("state")?)?,
510 step: row.try_get::<i64, _>("step").map_err(sqlite_error)? as usize,
511 pending_nodes: serde_json::from_str(&text("pending_nodes")?)?,
512 metadata: serde_json::from_str(&text("metadata")?)?,
513 created_at: chrono::DateTime::parse_from_rfc3339(&text("created_at")?)
514 .map_err(|e| GraphError::CheckpointError(e.to_string()))?
515 .with_timezone(&chrono::Utc),
516 cleared_interrupt: optional("cleared_interrupt")?,
517 attempts,
518 child_ledger,
519 version: row.try_get::<i64, _>("version").map_err(sqlite_error)? as u64,
520 pending_writes,
521 })
522}
523
524#[cfg(feature = "sqlite")]
525impl SqliteCheckpointer {
526 pub async fn new(database_url: &str) -> Result<Self> {
528 let pool = sqlx::SqlitePool::connect(database_url).await.map_err(sqlite_error)?;
529 Self::from_pool(pool).await
530 }
531
532 pub async fn from_pool(pool: sqlx::SqlitePool) -> Result<Self> {
554 sqlx::query(
555 r#"
556 CREATE TABLE IF NOT EXISTS graph_checkpoints (
557 id TEXT PRIMARY KEY,
558 thread_id TEXT NOT NULL,
559 state TEXT NOT NULL,
560 step INTEGER NOT NULL,
561 pending_nodes TEXT NOT NULL,
562 metadata TEXT,
563 created_at TEXT NOT NULL,
564 cleared_interrupt TEXT,
565 attempts TEXT,
566 child_ledger TEXT,
567 version INTEGER NOT NULL DEFAULT 0,
568 pending_writes TEXT
569 )
570 "#,
571 )
572 .execute(&pool)
573 .await
574 .map_err(sqlite_error)?;
575
576 for alter in [
580 "ALTER TABLE graph_checkpoints ADD COLUMN cleared_interrupt TEXT",
581 "ALTER TABLE graph_checkpoints ADD COLUMN attempts TEXT",
582 "ALTER TABLE graph_checkpoints ADD COLUMN child_ledger TEXT",
583 "ALTER TABLE graph_checkpoints ADD COLUMN version INTEGER NOT NULL DEFAULT 0",
584 "ALTER TABLE graph_checkpoints ADD COLUMN pending_writes TEXT",
585 ] {
586 match sqlx::query(alter).execute(&pool).await {
587 Ok(_) => {}
588 Err(sqlx::Error::Database(error))
589 if error.message().starts_with("duplicate column name") => {}
590 Err(error) => return Err(sqlite_error(error)),
591 }
592 }
593
594 sqlx::query(
596 r#"
597 UPDATE graph_checkpoints SET version = (
598 SELECT COUNT(*) FROM graph_checkpoints AS earlier
599 WHERE earlier.thread_id = graph_checkpoints.thread_id
600 AND (earlier.created_at < graph_checkpoints.created_at
601 OR (earlier.created_at = graph_checkpoints.created_at
602 AND earlier.id <= graph_checkpoints.id))
603 )
604 WHERE version = 0
605 "#,
606 )
607 .execute(&pool)
608 .await
609 .map_err(sqlite_error)?;
610
611 for statement in [
612 "CREATE UNIQUE INDEX IF NOT EXISTS idx_graph_checkpoints_thread_version \
613 ON graph_checkpoints(thread_id, version)",
614 "DROP INDEX IF EXISTS idx_graph_checkpoints_thread",
615 ] {
616 sqlx::query(statement).execute(&pool).await.map_err(sqlite_error)?;
617 }
618
619 Ok(Self { pool })
620 }
621
622 pub async fn in_memory() -> Result<Self> {
624 Self::new(":memory:").await
625 }
626
627 async fn head(&self, thread_id: &str) -> Result<Option<u64>> {
628 let head: Option<i64> =
629 sqlx::query_scalar("SELECT MAX(version) FROM graph_checkpoints WHERE thread_id = ?")
630 .bind(thread_id)
631 .fetch_one(&self.pool)
632 .await
633 .map_err(sqlite_error)?;
634 Ok(head.map(|head| head as u64))
635 }
636}
637
638#[cfg(feature = "sqlite")]
639#[async_trait]
640impl Checkpointer for SqliteCheckpointer {
641 async fn save(&self, checkpoint: &Checkpoint) -> Result<String> {
642 ensure_newer(checkpoint, None)?;
643 let inserted = sqlx::query(
646 "INSERT INTO graph_checkpoints (id, thread_id, state, step, pending_nodes, metadata, created_at, \
647 cleared_interrupt, attempts, child_ledger, version, pending_writes) \
648 SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? \
649 WHERE NOT EXISTS (SELECT 1 FROM graph_checkpoints WHERE thread_id = ? AND version >= ?)",
650 )
651 .bind(&checkpoint.checkpoint_id)
652 .bind(&checkpoint.thread_id)
653 .bind(serde_json::to_string(&checkpoint.state)?)
654 .bind(checkpoint.step as i64)
655 .bind(serde_json::to_string(&checkpoint.pending_nodes)?)
656 .bind(serde_json::to_string(&checkpoint.metadata)?)
657 .bind(checkpoint.created_at.to_rfc3339_opts(chrono::SecondsFormat::Micros, true))
658 .bind(checkpoint.cleared_interrupt.as_deref())
659 .bind(serde_json::to_string(&checkpoint.attempts)?)
660 .bind(serde_json::to_string(&checkpoint.child_ledger)?)
661 .bind(checkpoint.version as i64)
662 .bind(serde_json::to_string(&checkpoint.pending_writes)?)
663 .bind(&checkpoint.thread_id)
664 .bind(checkpoint.version as i64)
665 .execute(&self.pool)
666 .await;
667 match inserted {
668 Ok(result) if result.rows_affected() == 1 => Ok(checkpoint.checkpoint_id.clone()),
669 Ok(_) => {
670 Err(conflict(checkpoint, self.head(&checkpoint.thread_id).await?.unwrap_or(0)))
671 }
672 Err(sqlx::Error::Database(error)) if error.is_unique_violation() => {
673 if error.message().contains("graph_checkpoints.id") {
674 Err(duplicate_id(&checkpoint.checkpoint_id))
675 } else {
676 Err(conflict(checkpoint, self.head(&checkpoint.thread_id).await?.unwrap_or(0)))
677 }
678 }
679 Err(error) => Err(sqlite_error(error)),
680 }
681 }
682
683 async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>> {
684 let row = sqlx::query(
685 "SELECT id, thread_id, state, step, pending_nodes, metadata, created_at, \
686 cleared_interrupt, attempts, child_ledger, version, pending_writes FROM graph_checkpoints WHERE thread_id = ? \
687 ORDER BY version DESC LIMIT 1",
688 )
689 .bind(thread_id)
690 .fetch_optional(&self.pool)
691 .await
692 .map_err(sqlite_error)?;
693 row.as_ref().map(sqlite_row).transpose()
694 }
695
696 async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>> {
697 let row =
698 sqlx::query(
699 "SELECT id, thread_id, state, step, pending_nodes, metadata, created_at, \
700 cleared_interrupt, attempts, child_ledger, version, pending_writes FROM graph_checkpoints WHERE id = ?",
701 )
702 .bind(checkpoint_id)
703 .fetch_optional(&self.pool)
704 .await
705 .map_err(sqlite_error)?;
706 row.as_ref().map(sqlite_row).transpose()
707 }
708
709 async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>> {
710 let rows = sqlx::query(
711 "SELECT id, thread_id, state, step, pending_nodes, metadata, created_at, \
712 cleared_interrupt, attempts, child_ledger, version, pending_writes FROM graph_checkpoints WHERE thread_id = ? ORDER BY version ASC",
713 )
714 .bind(thread_id)
715 .fetch_all(&self.pool)
716 .await
717 .map_err(sqlite_error)?;
718 rows.iter().map(sqlite_row).collect()
719 }
720
721 async fn list_page(
722 &self,
723 thread_id: &str,
724 before: Option<u64>,
725 limit: usize,
726 ) -> Result<Vec<Checkpoint>> {
727 let rows = sqlx::query(
728 "SELECT id, thread_id, state, step, pending_nodes, metadata, created_at, \
729 cleared_interrupt, attempts, child_ledger, version, pending_writes FROM graph_checkpoints WHERE thread_id = ? AND version < ? \
730 ORDER BY version DESC LIMIT ?",
731 )
732 .bind(thread_id)
733 .bind(before.map_or(i64::MAX, |before| before as i64))
734 .bind(i64::try_from(limit).unwrap_or(i64::MAX))
735 .fetch_all(&self.pool)
736 .await
737 .map_err(sqlite_error)?;
738 rows.iter().map(sqlite_row).collect()
739 }
740
741 async fn delete(&self, thread_id: &str) -> Result<()> {
742 sqlx::query("DELETE FROM graph_checkpoints WHERE thread_id = ?")
743 .bind(thread_id)
744 .execute(&self.pool)
745 .await
746 .map_err(sqlite_error)?;
747 Ok(())
748 }
749
750 async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize> {
751 let expired = policy.expired(&self.list(thread_id).await?);
753 let mut removed = 0usize;
754 for checkpoint_id in &expired {
755 let result =
756 sqlx::query("DELETE FROM graph_checkpoints WHERE id = ? AND thread_id = ?")
757 .bind(checkpoint_id)
758 .bind(thread_id)
759 .execute(&self.pool)
760 .await
761 .map_err(sqlite_error)?;
762 removed += result.rows_affected() as usize;
763 }
764 Ok(removed)
765 }
766}
767
768#[cfg(test)]
769mod tests {
770 use super::*;
771 use crate::state::State;
772
773 #[tokio::test]
774 async fn test_memory_checkpointer() {
775 let cp = MemoryCheckpointer::new();
776
777 let checkpoint = Checkpoint::new("thread_1", State::new(), 0, vec!["node_a".to_string()]);
779 let id = cp.save(&checkpoint).await.unwrap();
780 assert!(!id.is_empty());
781
782 let loaded = cp.load("thread_1").await.unwrap();
784 assert!(loaded.is_some());
785 assert_eq!(loaded.unwrap().step, 0);
786
787 let checkpoint2 = Checkpoint::new("thread_1", State::new(), 1, vec!["node_b".to_string()])
789 .with_version(2);
790 cp.save(&checkpoint2).await.unwrap();
791
792 let loaded = cp.load("thread_1").await.unwrap();
794 assert_eq!(loaded.unwrap().step, 1);
795
796 let all = cp.list("thread_1").await.unwrap();
798 assert_eq!(all.len(), 2);
799
800 cp.delete("thread_1").await.unwrap();
802 let loaded = cp.load("thread_1").await.unwrap();
803 assert!(loaded.is_none());
804 }
805}