use crate::error::{GraphError, Result};
use crate::state::Checkpoint;
use async_trait::async_trait;
use std::collections::{BTreeSet, HashMap};
use std::sync::Arc;
use tokio::sync::RwLock;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RetentionPolicy {
pub max_per_thread: Option<usize>,
pub max_age: Option<std::time::Duration>,
pub pinned: BTreeSet<String>,
}
impl RetentionPolicy {
pub fn keep_last(count: usize) -> Self {
Self { max_per_thread: Some(count.max(1)), ..Self::default() }
}
pub fn max_age(age: std::time::Duration) -> Self {
Self { max_age: Some(age), ..Self::default() }
}
pub fn with_max_age(mut self, age: std::time::Duration) -> Self {
self.max_age = Some(age);
self
}
pub fn with_max_per_thread(mut self, count: usize) -> Self {
self.max_per_thread = Some(count.max(1));
self
}
pub fn pinning<I, S>(mut self, checkpoint_ids: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.pinned.extend(checkpoint_ids.into_iter().map(Into::into));
self
}
pub fn is_unlimited(&self) -> bool {
self.max_per_thread.is_none() && self.max_age.is_none()
}
pub fn expired(&self, checkpoints: &[Checkpoint]) -> Vec<String> {
if self.is_unlimited() || checkpoints.len() <= 1 {
return Vec::new();
}
let needed = needed_to_resume(checkpoints);
let mut ordered: Vec<&Checkpoint> = checkpoints.iter().collect();
ordered.sort_by_key(|checkpoint| std::cmp::Reverse(checkpoint.version));
let cutoff = self.max_age.and_then(|age| {
chrono::Duration::from_std(age).ok().map(|age| chrono::Utc::now() - age)
});
ordered
.iter()
.enumerate()
.filter(|(index, checkpoint)| {
!needed.contains(&checkpoint.checkpoint_id)
&& !self.pinned.contains(&checkpoint.checkpoint_id)
&& (self.max_per_thread.is_some_and(|max| *index >= max)
|| cutoff.is_some_and(|cutoff| checkpoint.created_at < cutoff))
})
.map(|(_, checkpoint)| checkpoint.checkpoint_id.clone())
.collect()
}
}
pub fn needed_to_resume(checkpoints: &[Checkpoint]) -> BTreeSet<String> {
let mut needed = BTreeSet::new();
let Some(newest) = checkpoints.iter().max_by_key(|checkpoint| checkpoint.version) else {
return needed;
};
needed.insert(newest.checkpoint_id.clone());
needed.extend(newest.open_pauses().unwrap_or_default());
needed.extend(
checkpoints
.iter()
.filter(|checkpoint| {
checkpoint.metadata.contains_key(crate::governed::EFFECT_METADATA_KEY)
})
.map(|checkpoint| checkpoint.checkpoint_id.clone()),
);
needed
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Durability {
Exit,
Async,
#[default]
Sync,
}
pub fn ensure_newer(checkpoint: &Checkpoint, head: Option<u64>) -> Result<()> {
if checkpoint.version == 0 {
return Err(GraphError::CheckpointError(format!(
"checkpoint '{}' has version 0; versions start at 1. Set it with \
Checkpoint::with_version(newest version + 1)",
checkpoint.checkpoint_id
)));
}
match head {
Some(head) if head >= checkpoint.version => Err(conflict(checkpoint, head)),
_ => Ok(()),
}
}
pub fn conflict(checkpoint: &Checkpoint, head: u64) -> GraphError {
GraphError::CheckpointConflict {
thread_id: checkpoint.thread_id.clone(),
version: checkpoint.version,
head,
}
}
pub fn duplicate_id(checkpoint_id: &str) -> GraphError {
GraphError::CheckpointError(format!(
"checkpoint id '{checkpoint_id}' is already stored; every checkpoint needs a unique id"
))
}
#[async_trait]
pub trait Checkpointer: Send + Sync {
async fn save(&self, checkpoint: &Checkpoint) -> Result<String>;
async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>>;
async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>>;
async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>>;
async fn list_page(
&self,
thread_id: &str,
before: Option<u64>,
limit: usize,
) -> Result<Vec<Checkpoint>> {
let mut checkpoints = self.list(thread_id).await?;
checkpoints.retain(|checkpoint| before.is_none_or(|before| checkpoint.version < before));
checkpoints.sort_by_key(|checkpoint| std::cmp::Reverse(checkpoint.version));
checkpoints.truncate(limit);
Ok(checkpoints)
}
async fn delete(&self, thread_id: &str) -> Result<()>;
async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize>;
}
#[derive(Default)]
struct MemoryStore {
threads: HashMap<String, Vec<Checkpoint>>,
ids: HashMap<String, String>,
}
#[derive(Default)]
pub struct MemoryCheckpointer {
store: Arc<RwLock<MemoryStore>>,
}
impl MemoryCheckpointer {
pub fn new() -> Self {
Self::default()
}
}
#[async_trait]
impl Checkpointer for MemoryCheckpointer {
async fn save(&self, checkpoint: &Checkpoint) -> Result<String> {
let mut store = self.store.write().await;
let head = store
.threads
.get(&checkpoint.thread_id)
.and_then(|thread| thread.last())
.map(|newest| newest.version);
ensure_newer(checkpoint, head)?;
if store.ids.contains_key(&checkpoint.checkpoint_id) {
return Err(duplicate_id(&checkpoint.checkpoint_id));
}
store.ids.insert(checkpoint.checkpoint_id.clone(), checkpoint.thread_id.clone());
store.threads.entry(checkpoint.thread_id.clone()).or_default().push(checkpoint.clone());
Ok(checkpoint.checkpoint_id.clone())
}
async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>> {
let store = self.store.read().await;
Ok(store.threads.get(thread_id).and_then(|thread| thread.last()).cloned())
}
async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>> {
let store = self.store.read().await;
Ok(store.ids.get(checkpoint_id).and_then(|thread_id| {
store.threads.get(thread_id)?.iter().find(|c| c.checkpoint_id == checkpoint_id).cloned()
}))
}
async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>> {
let store = self.store.read().await;
Ok(store.threads.get(thread_id).cloned().unwrap_or_default())
}
async fn delete(&self, thread_id: &str) -> Result<()> {
let mut store = self.store.write().await;
if let Some(thread) = store.threads.remove(thread_id) {
for checkpoint in thread {
store.ids.remove(&checkpoint.checkpoint_id);
}
}
Ok(())
}
async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize> {
let mut store = self.store.write().await;
let Some(thread) = store.threads.get_mut(thread_id) else { return Ok(0) };
let expired = policy.expired(thread);
if expired.is_empty() {
return Ok(0);
}
let before = thread.len();
thread.retain(|checkpoint| !expired.contains(&checkpoint.checkpoint_id));
let removed = before - thread.len();
for checkpoint_id in &expired {
store.ids.remove(checkpoint_id);
}
Ok(removed)
}
}
#[cfg(feature = "sqlite")]
pub struct SqliteCheckpointer {
pool: sqlx::SqlitePool,
}
#[cfg(feature = "sqlite")]
fn sqlite_error(error: sqlx::Error) -> GraphError {
GraphError::CheckpointError(error.to_string())
}
#[cfg(feature = "sqlite")]
fn sqlite_row(row: &sqlx::sqlite::SqliteRow) -> Result<Checkpoint> {
use sqlx::Row;
let text = |column: &str| row.try_get::<String, _>(column).map_err(sqlite_error);
let optional = |column: &str| row.try_get::<Option<String>, _>(column).map_err(sqlite_error);
fn json_or_default<T: serde::de::DeserializeOwned + Default>(raw: Option<String>) -> Result<T> {
Ok(raw.map(|raw| serde_json::from_str(&raw)).transpose()?.unwrap_or_default())
}
let attempts = json_or_default(optional("attempts")?)?;
let child_ledger = json_or_default(optional("child_ledger")?)?;
let pending_writes = json_or_default(optional("pending_writes")?)?;
Ok(Checkpoint {
checkpoint_id: text("id")?,
thread_id: text("thread_id")?,
state: serde_json::from_str(&text("state")?)?,
step: row.try_get::<i64, _>("step").map_err(sqlite_error)? as usize,
pending_nodes: serde_json::from_str(&text("pending_nodes")?)?,
metadata: serde_json::from_str(&text("metadata")?)?,
created_at: chrono::DateTime::parse_from_rfc3339(&text("created_at")?)
.map_err(|e| GraphError::CheckpointError(e.to_string()))?
.with_timezone(&chrono::Utc),
cleared_interrupt: optional("cleared_interrupt")?,
attempts,
child_ledger,
version: row.try_get::<i64, _>("version").map_err(sqlite_error)? as u64,
pending_writes,
})
}
#[cfg(feature = "sqlite")]
impl SqliteCheckpointer {
pub async fn new(database_url: &str) -> Result<Self> {
let pool = sqlx::SqlitePool::connect(database_url).await.map_err(sqlite_error)?;
Self::from_pool(pool).await
}
pub async fn from_pool(pool: sqlx::SqlitePool) -> Result<Self> {
sqlx::query(
r#"
CREATE TABLE IF NOT EXISTS graph_checkpoints (
id TEXT PRIMARY KEY,
thread_id TEXT NOT NULL,
state TEXT NOT NULL,
step INTEGER NOT NULL,
pending_nodes TEXT NOT NULL,
metadata TEXT,
created_at TEXT NOT NULL,
cleared_interrupt TEXT,
attempts TEXT,
child_ledger TEXT,
version INTEGER NOT NULL DEFAULT 0,
pending_writes TEXT
)
"#,
)
.execute(&pool)
.await
.map_err(sqlite_error)?;
for alter in [
"ALTER TABLE graph_checkpoints ADD COLUMN cleared_interrupt TEXT",
"ALTER TABLE graph_checkpoints ADD COLUMN attempts TEXT",
"ALTER TABLE graph_checkpoints ADD COLUMN child_ledger TEXT",
"ALTER TABLE graph_checkpoints ADD COLUMN version INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE graph_checkpoints ADD COLUMN pending_writes TEXT",
] {
match sqlx::query(alter).execute(&pool).await {
Ok(_) => {}
Err(sqlx::Error::Database(error))
if error.message().starts_with("duplicate column name") => {}
Err(error) => return Err(sqlite_error(error)),
}
}
sqlx::query(
r#"
UPDATE graph_checkpoints SET version = (
SELECT COUNT(*) FROM graph_checkpoints AS earlier
WHERE earlier.thread_id = graph_checkpoints.thread_id
AND (earlier.created_at < graph_checkpoints.created_at
OR (earlier.created_at = graph_checkpoints.created_at
AND earlier.id <= graph_checkpoints.id))
)
WHERE version = 0
"#,
)
.execute(&pool)
.await
.map_err(sqlite_error)?;
for statement in [
"CREATE UNIQUE INDEX IF NOT EXISTS idx_graph_checkpoints_thread_version \
ON graph_checkpoints(thread_id, version)",
"DROP INDEX IF EXISTS idx_graph_checkpoints_thread",
] {
sqlx::query(statement).execute(&pool).await.map_err(sqlite_error)?;
}
Ok(Self { pool })
}
pub async fn in_memory() -> Result<Self> {
Self::new(":memory:").await
}
async fn head(&self, thread_id: &str) -> Result<Option<u64>> {
let head: Option<i64> =
sqlx::query_scalar("SELECT MAX(version) FROM graph_checkpoints WHERE thread_id = ?")
.bind(thread_id)
.fetch_one(&self.pool)
.await
.map_err(sqlite_error)?;
Ok(head.map(|head| head as u64))
}
}
#[cfg(feature = "sqlite")]
#[async_trait]
impl Checkpointer for SqliteCheckpointer {
async fn save(&self, checkpoint: &Checkpoint) -> Result<String> {
ensure_newer(checkpoint, None)?;
let inserted = sqlx::query(
"INSERT INTO graph_checkpoints (id, thread_id, state, step, pending_nodes, metadata, created_at, \
cleared_interrupt, attempts, child_ledger, version, pending_writes) \
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? \
WHERE NOT EXISTS (SELECT 1 FROM graph_checkpoints WHERE thread_id = ? AND version >= ?)",
)
.bind(&checkpoint.checkpoint_id)
.bind(&checkpoint.thread_id)
.bind(serde_json::to_string(&checkpoint.state)?)
.bind(checkpoint.step as i64)
.bind(serde_json::to_string(&checkpoint.pending_nodes)?)
.bind(serde_json::to_string(&checkpoint.metadata)?)
.bind(checkpoint.created_at.to_rfc3339_opts(chrono::SecondsFormat::Micros, true))
.bind(checkpoint.cleared_interrupt.as_deref())
.bind(serde_json::to_string(&checkpoint.attempts)?)
.bind(serde_json::to_string(&checkpoint.child_ledger)?)
.bind(checkpoint.version as i64)
.bind(serde_json::to_string(&checkpoint.pending_writes)?)
.bind(&checkpoint.thread_id)
.bind(checkpoint.version as i64)
.execute(&self.pool)
.await;
match inserted {
Ok(result) if result.rows_affected() == 1 => Ok(checkpoint.checkpoint_id.clone()),
Ok(_) => {
Err(conflict(checkpoint, self.head(&checkpoint.thread_id).await?.unwrap_or(0)))
}
Err(sqlx::Error::Database(error)) if error.is_unique_violation() => {
if error.message().contains("graph_checkpoints.id") {
Err(duplicate_id(&checkpoint.checkpoint_id))
} else {
Err(conflict(checkpoint, self.head(&checkpoint.thread_id).await?.unwrap_or(0)))
}
}
Err(error) => Err(sqlite_error(error)),
}
}
async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>> {
let row = sqlx::query(
"SELECT id, thread_id, state, step, pending_nodes, metadata, created_at, \
cleared_interrupt, attempts, child_ledger, version, pending_writes FROM graph_checkpoints WHERE thread_id = ? \
ORDER BY version DESC LIMIT 1",
)
.bind(thread_id)
.fetch_optional(&self.pool)
.await
.map_err(sqlite_error)?;
row.as_ref().map(sqlite_row).transpose()
}
async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>> {
let row =
sqlx::query(
"SELECT id, thread_id, state, step, pending_nodes, metadata, created_at, \
cleared_interrupt, attempts, child_ledger, version, pending_writes FROM graph_checkpoints WHERE id = ?",
)
.bind(checkpoint_id)
.fetch_optional(&self.pool)
.await
.map_err(sqlite_error)?;
row.as_ref().map(sqlite_row).transpose()
}
async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>> {
let rows = sqlx::query(
"SELECT id, thread_id, state, step, pending_nodes, metadata, created_at, \
cleared_interrupt, attempts, child_ledger, version, pending_writes FROM graph_checkpoints WHERE thread_id = ? ORDER BY version ASC",
)
.bind(thread_id)
.fetch_all(&self.pool)
.await
.map_err(sqlite_error)?;
rows.iter().map(sqlite_row).collect()
}
async fn list_page(
&self,
thread_id: &str,
before: Option<u64>,
limit: usize,
) -> Result<Vec<Checkpoint>> {
let rows = sqlx::query(
"SELECT id, thread_id, state, step, pending_nodes, metadata, created_at, \
cleared_interrupt, attempts, child_ledger, version, pending_writes FROM graph_checkpoints WHERE thread_id = ? AND version < ? \
ORDER BY version DESC LIMIT ?",
)
.bind(thread_id)
.bind(before.map_or(i64::MAX, |before| before as i64))
.bind(i64::try_from(limit).unwrap_or(i64::MAX))
.fetch_all(&self.pool)
.await
.map_err(sqlite_error)?;
rows.iter().map(sqlite_row).collect()
}
async fn delete(&self, thread_id: &str) -> Result<()> {
sqlx::query("DELETE FROM graph_checkpoints WHERE thread_id = ?")
.bind(thread_id)
.execute(&self.pool)
.await
.map_err(sqlite_error)?;
Ok(())
}
async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize> {
let expired = policy.expired(&self.list(thread_id).await?);
let mut removed = 0usize;
for checkpoint_id in &expired {
let result =
sqlx::query("DELETE FROM graph_checkpoints WHERE id = ? AND thread_id = ?")
.bind(checkpoint_id)
.bind(thread_id)
.execute(&self.pool)
.await
.map_err(sqlite_error)?;
removed += result.rows_affected() as usize;
}
Ok(removed)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::state::State;
#[tokio::test]
async fn test_memory_checkpointer() {
let cp = MemoryCheckpointer::new();
let checkpoint = Checkpoint::new("thread_1", State::new(), 0, vec!["node_a".to_string()]);
let id = cp.save(&checkpoint).await.unwrap();
assert!(!id.is_empty());
let loaded = cp.load("thread_1").await.unwrap();
assert!(loaded.is_some());
assert_eq!(loaded.unwrap().step, 0);
let checkpoint2 = Checkpoint::new("thread_1", State::new(), 1, vec!["node_b".to_string()])
.with_version(2);
cp.save(&checkpoint2).await.unwrap();
let loaded = cp.load("thread_1").await.unwrap();
assert_eq!(loaded.unwrap().step, 1);
let all = cp.list("thread_1").await.unwrap();
assert_eq!(all.len(), 2);
cp.delete("thread_1").await.unwrap();
let loaded = cp.load("thread_1").await.unwrap();
assert!(loaded.is_none());
}
}