Skip to main content

adk_graph/
checkpoint.rs

1//! Checkpointing for persistent graph state.
2//!
3//! A [`Checkpointer`] stores the [`Checkpoint`] a graph run writes after each
4//! super-step, so a run can resume where it stopped, on this process or another.
5//!
6//! # Contract
7//!
8//! Every backend — the ones in this crate and any third-party one — keeps these
9//! rules, and proves it by passing the conformance suite (the `conformance` feature,
10//! `adk_graph::checkpointer_conformance_tests!`):
11//!
12//! | Rule | Behaviour |
13//! |------|-----------|
14//! | Ordering | A thread's checkpoints are ordered by [`Checkpoint::version`], never by time. `load` returns the highest version; `list` returns ascending versions |
15//! | Monotonic versions | `save` stores a checkpoint only when its version is at least 1 and greater than every version stored for the thread; otherwise it fails with [`GraphError::CheckpointConflict`]. Of concurrent saves of one version, exactly one succeeds |
16//! | Unique IDs | A checkpoint ID is stored once; saving a second checkpoint with a stored ID fails |
17//! | Thread isolation | `delete` and `prune` touch only the named thread |
18//! | Retention | `prune` removes what a [`RetentionPolicy`] selects, and never a checkpoint a resume still needs ([`needed_to_resume`]) or the policy pins |
19//! | Fidelity | A loaded checkpoint equals the saved one, with `created_at` to the microsecond |
20//!
21//! The version rule is what keeps two writers from interleaving. A writer continues a
22//! thread from its newest checkpoint, version `n`, and saves `n + 1`; a second writer
23//! that read the same checkpoint saves `n + 1` too and is refused.
24
25use 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/// How many checkpoints to keep for a thread, and for how long.
33///
34/// A long-running thread accumulates one checkpoint per super-step. Without a
35/// policy that grows without bound, which costs storage and slows a `list`.
36///
37/// Whatever the limits say, a policy never selects a checkpoint a resume still
38/// needs ([`needed_to_resume`]) or one it pins:
39///
40/// | Kept | Why |
41/// |------|-----|
42/// | The newest checkpoint | A resume without a checkpoint ID loads it |
43/// | Each pause no run has resumed | A caller holds its ID and resumes it with [`ExecutionConfig::with_resume_from`](crate::node::ExecutionConfig::with_resume_from) |
44/// | Each effect-log entry | A governed node's call is answered from it instead of running again |
45/// | Each ID in [`pinned`](Self::pinned) | The caller asked for it |
46///
47/// # Example
48///
49/// ```
50/// use adk_graph::checkpoint::RetentionPolicy;
51/// use std::time::Duration;
52///
53/// // Keep the last 50 steps, and nothing older than a week.
54/// let policy = RetentionPolicy::keep_last(50).with_max_age(Duration::from_secs(7 * 24 * 3600));
55/// # let _ = policy;
56/// ```
57#[derive(Debug, Clone, Default, PartialEq, Eq)]
58#[non_exhaustive]
59pub struct RetentionPolicy {
60    /// Keep at most this many checkpoints per thread, newest first.
61    pub max_per_thread: Option<usize>,
62    /// Remove checkpoints older than this.
63    pub max_age: Option<std::time::Duration>,
64    /// Checkpoint IDs kept whatever the limits say.
65    pub pinned: BTreeSet<String>,
66}
67
68impl RetentionPolicy {
69    /// Keeps the newest `count` checkpoints for a thread.
70    ///
71    /// A count of zero is raised to one, because the newest is always kept.
72    pub fn keep_last(count: usize) -> Self {
73        Self { max_per_thread: Some(count.max(1)), ..Self::default() }
74    }
75
76    /// Removes checkpoints older than `age`.
77    pub fn max_age(age: std::time::Duration) -> Self {
78        Self { max_age: Some(age), ..Self::default() }
79    }
80
81    /// Adds an age limit to a count limit.
82    pub fn with_max_age(mut self, age: std::time::Duration) -> Self {
83        self.max_age = Some(age);
84        self
85    }
86
87    /// Adds a count limit to an age limit.
88    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    /// Keeps these checkpoints whatever the limits say.
94    ///
95    /// A store that hides checkpoint metadata from the store it wraps, as an encrypting
96    /// one does, pins what [`needed_to_resume`] finds in its own view before delegating.
97    ///
98    /// # Example
99    ///
100    /// ```
101    /// use adk_graph::checkpoint::RetentionPolicy;
102    ///
103    /// let policy = RetentionPolicy::keep_last(1).pinning(["audited-cp"]);
104    /// assert!(policy.pinned.contains("audited-cp"));
105    /// ```
106    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    /// Whether this policy would remove anything.
116    pub fn is_unlimited(&self) -> bool {
117        self.max_per_thread.is_none() && self.max_age.is_none()
118    }
119
120    /// Selects the checkpoint IDs this policy discards from one thread's checkpoints.
121    ///
122    /// Shared by every backend so they cannot disagree about what to keep. Nothing in
123    /// [`needed_to_resume`] or [`pinned`](Self::pinned) is selected.
124    ///
125    /// # Example
126    ///
127    /// ```
128    /// use adk_graph::checkpoint::RetentionPolicy;
129    /// use adk_graph::state::{Checkpoint, State};
130    ///
131    /// let thread: Vec<Checkpoint> = (1..=3)
132    ///     .map(|version| Checkpoint::new("t1", State::new(), 0, vec![]).with_version(version))
133    ///     .collect();
134    /// let expired = RetentionPolicy::keep_last(1).expired(&thread);
135    /// assert_eq!(expired, vec![thread[1].checkpoint_id.clone(), thread[0].checkpoint_id.clone()]);
136    /// ```
137    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        // Newest first, so the count limit counts from the one a resume loads.
144        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
164/// The IDs of one thread's checkpoints that a resume still needs, which no
165/// [`RetentionPolicy`] removes.
166///
167/// | Checkpoint | Needed because |
168/// |------------|----------------|
169/// | The newest, by version | A resume without a checkpoint ID loads it |
170/// | Each one the newest lists in [`OPEN_PAUSES_METADATA_KEY`] | A run paused there and no run has resumed it, so a caller can still resume it by ID |
171/// | Each one carrying [`EFFECT_METADATA_KEY`] | An effect-log entry answers a governed node's call, so a fork or a retry does not run it again |
172///
173/// A checkpoint whose pause has been resumed is not needed: the run that resumed it
174/// continues from its own checkpoints. Checkpoints written before the open-pause list
175/// existed protect only the newest.
176///
177/// # Example
178///
179/// ```
180/// use adk_graph::checkpoint::needed_to_resume;
181/// use adk_graph::record::OPEN_PAUSES_METADATA_KEY;
182/// use adk_graph::state::{Checkpoint, State};
183/// use serde_json::json;
184///
185/// let paused = Checkpoint::new("t1", State::new(), 1, vec!["approve".into()]);
186/// let branch = Checkpoint::new("t1", State::new(), 2, vec![])
187///     .with_version(2)
188///     .with_metadata(OPEN_PAUSES_METADATA_KEY, json!([paused.checkpoint_id]));
189/// let needed = needed_to_resume(&[paused.clone(), branch.clone()]);
190/// assert!(needed.contains(&paused.checkpoint_id) && needed.contains(&branch.checkpoint_id));
191/// ```
192///
193/// [`OPEN_PAUSES_METADATA_KEY`]: crate::record::OPEN_PAUSES_METADATA_KEY
194/// [`EFFECT_METADATA_KEY`]: crate::governed::EFFECT_METADATA_KEY
195pub 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    // A malformed list protects nothing extra rather than blocking every prune; the
202    // newest, which a resume loads, is kept regardless.
203    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/// When a graph run writes the checkpoint of each completed super-step.
216///
217/// | Mode | Checkpoint written | A crash loses |
218/// |------|--------------------|---------------|
219/// | [`Sync`](Self::Sync) (default) | Before the next super-step starts | Nothing that completed |
220/// | [`Async`](Self::Async) | While the next super-step runs | At most the last completed super-step |
221/// | [`Exit`](Self::Exit) | When the run completes, pauses, or fails | Everything since the run started |
222///
223/// Pauses and failures are always written before the run returns, in every mode.
224/// A super-step that runs a node declared [`ToolEffect::NonIdempotent`](adk_core::ToolEffect)
225/// (see [`CompiledGraph::with_node_effect`](crate::graph::CompiledGraph::with_node_effect))
226/// first waits until every earlier checkpoint is written, so a crash during the side
227/// effect never resumes from before an earlier step and repeats it. Nodes that declare
228/// no effect do not force this.
229///
230/// # Example
231///
232/// ```
233/// use adk_graph::checkpoint::Durability;
234/// use adk_graph::node::ExecutionConfig;
235///
236/// let config = ExecutionConfig::new("thread").with_durability(Durability::Async);
237/// assert_eq!(config.durability, Durability::Async);
238/// ```
239#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
240#[non_exhaustive]
241pub enum Durability {
242    /// Writes only when the run exits: completes, pauses, or fails.
243    Exit,
244    /// Writes each checkpoint in the background while the next super-step runs.
245    Async,
246    /// Writes each checkpoint before the next super-step starts.
247    #[default]
248    Sync,
249}
250
251/// Checks a checkpoint's version against the highest version stored for its thread.
252///
253/// Shared by every backend so they refuse the same writes.
254///
255/// # Example
256///
257/// ```
258/// use adk_graph::checkpoint::ensure_newer;
259/// use adk_graph::state::{Checkpoint, State};
260///
261/// let checkpoint = Checkpoint::new("thread", State::new(), 0, vec![]).with_version(3);
262/// assert!(ensure_newer(&checkpoint, Some(2)).is_ok());
263/// assert!(ensure_newer(&checkpoint, Some(3)).is_err());
264/// ```
265///
266/// # Errors
267///
268/// Returns [`GraphError::CheckpointError`] for version 0 and
269/// [`GraphError::CheckpointConflict`] when `head` is not below the version.
270pub 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
284/// The conflict a refused save reports.
285///
286/// # Example
287///
288/// ```
289/// use adk_graph::checkpoint::conflict;
290/// use adk_graph::state::{Checkpoint, State};
291///
292/// let checkpoint = Checkpoint::new("thread", State::new(), 0, vec![]);
293/// assert!(conflict(&checkpoint, 1).to_string().contains("conflicts"));
294/// ```
295pub 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
303/// The error a save reports when the checkpoint ID is already stored.
304///
305/// # Example
306///
307/// ```
308/// use adk_graph::checkpoint::duplicate_id;
309///
310/// assert!(duplicate_id("cp-1").to_string().contains("cp-1"));
311/// ```
312pub 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/// Stores graph checkpoints. See the [module documentation](self) for the contract.
319#[async_trait]
320pub trait Checkpointer: Send + Sync {
321    /// Saves a checkpoint and returns its ID.
322    ///
323    /// # Errors
324    ///
325    /// Returns [`GraphError::CheckpointConflict`] when the thread already holds an
326    /// equal or higher version, and an error when the ID is already stored or the
327    /// backend cannot be written.
328    async fn save(&self, checkpoint: &Checkpoint) -> Result<String>;
329
330    /// Loads the newest checkpoint of a thread: the one with the highest version.
331    async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>>;
332
333    /// Loads a checkpoint by ID.
334    async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>>;
335
336    /// Lists a thread's checkpoints, oldest version first.
337    async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>>;
338
339    /// Lists at most `limit` of a thread's checkpoints, newest version first,
340    /// starting below version `before` when given.
341    ///
342    /// Pass the version of the last checkpoint of one page as `before` to read the
343    /// next. The default filters [`list`](Self::list); backends override it to read
344    /// one page only.
345    ///
346    /// # Errors
347    ///
348    /// Returns an error when the backend cannot be read.
349    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    /// Deletes every checkpoint of a thread, its open pauses included.
363    ///
364    /// Deleting a thread that holds no checkpoints is a no-op. The thread's versions
365    /// start afresh afterwards.
366    ///
367    /// # Errors
368    ///
369    /// Returns an error when the backend cannot be written.
370    async fn delete(&self, thread_id: &str) -> Result<()>;
371
372    /// Removes the checkpoints a retention policy discards from one thread.
373    ///
374    /// Backends select with [`RetentionPolicy::expired`], so nothing a resume still
375    /// needs ([`needed_to_resume`]) is removed. Returns how many were removed.
376    ///
377    /// # Errors
378    ///
379    /// Returns an error when the backend cannot be read or written.
380    async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize>;
381}
382
383#[derive(Default)]
384struct MemoryStore {
385    /// Each thread's checkpoints, ascending by version.
386    threads: HashMap<String, Vec<Checkpoint>>,
387    /// Checkpoint ID to thread.
388    ids: HashMap<String, String>,
389}
390
391/// In-memory checkpointer for development and testing.
392///
393/// # Example
394///
395/// ```
396/// use adk_graph::checkpoint::{Checkpointer, MemoryCheckpointer};
397/// use adk_graph::state::{Checkpoint, State};
398///
399/// # async fn demo() -> adk_graph::Result<()> {
400/// let checkpointer = MemoryCheckpointer::new();
401/// checkpointer.save(&Checkpoint::new("thread", State::new(), 0, vec![])).await?;
402/// assert!(checkpointer.load("thread").await?.is_some());
403/// # Ok(())
404/// # }
405/// ```
406#[derive(Default)]
407pub struct MemoryCheckpointer {
408    store: Arc<RwLock<MemoryStore>>,
409}
410
411impl MemoryCheckpointer {
412    /// Create a new in-memory checkpointer
413    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/// SQLite checkpointer.
481///
482/// Each checkpoint is one row of `graph_checkpoints`. A unique index on
483/// `(thread_id, version)` and a guarded insert enforce the version rule, so two
484/// processes sharing a database file cannot interleave a thread.
485#[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    /// Create a new SQLite checkpointer
527    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    /// Create a SQLite checkpointer from an existing pool.
533    ///
534    /// Use this to share one connection pool with the rest of an application
535    /// instead of opening a second one. The checkpointer writes through the pool
536    /// it is given, so the caller's own queries see its rows.
537    ///
538    /// The schema is applied to the pool's database on every call, so adopting an
539    /// already-initialized database is safe. A database written before checkpoints
540    /// carried versions has its rows numbered in creation order.
541    ///
542    /// `SqlitePool` comes from `sqlx`, so a caller has to depend on a
543    /// semver-compatible `sqlx` to construct one:
544    ///
545    /// ```toml
546    /// sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite"] }
547    /// ```
548    ///
549    /// # Errors
550    ///
551    /// Returns `GraphError::CheckpointError` when the table, a missing column, or
552    /// the index cannot be created on the pool's database.
553    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        // A database created before a column existed keeps its old shape under
577        // CREATE TABLE IF NOT EXISTS, so add each column separately and tolerate only
578        // the duplicate-column error on a database that already has it.
579        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        // Rows written before versions existed are numbered in creation order.
595        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    /// Create an in-memory SQLite checkpointer (for testing)
623    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        // The guard refuses a stale version in the same statement that inserts, and
644        // the unique index refuses a concurrent insert of the same version.
645        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        // The policy decides, not the SQL, so every backend keeps the same set.
752        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        // Create and save checkpoint
778        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        // Load latest
783        let loaded = cp.load("thread_1").await.unwrap();
784        assert!(loaded.is_some());
785        assert_eq!(loaded.unwrap().step, 0);
786
787        // Save another checkpoint
788        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        // Load latest should return step 1
793        let loaded = cp.load("thread_1").await.unwrap();
794        assert_eq!(loaded.unwrap().step, 1);
795
796        // List should return both
797        let all = cp.list("thread_1").await.unwrap();
798        assert_eq!(all.len(), 2);
799
800        // Delete
801        cp.delete("thread_1").await.unwrap();
802        let loaded = cp.load("thread_1").await.unwrap();
803        assert!(loaded.is_none());
804    }
805}