Skip to main content

adk_graph/
delta.rs

1//! Delta checkpoint compression for graph state.
2//!
3//! This module provides incremental (delta-based) checkpoint storage, reducing
4//! storage growth from quadratic (full snapshots every step) to linear (only
5//! differences between consecutive states are persisted).
6//!
7//! # Architecture
8//!
9//! The core abstraction is the [`Diff`] trait, which defines how to compute and
10//! apply incremental deltas for a given state type. [`DeltaConfig`] controls how
11//! often full snapshots are stored (bounding reconstruction cost), and
12//! [`CheckpointType`] distinguishes between full snapshots and delta records.
13//!
14//! # Example
15//!
16//! ```rust
17//! use adk_graph::delta::{Diff, DeltaConfig, CheckpointType};
18//!
19//! // DeltaConfig with default full_snapshot_interval of 10
20//! let config = DeltaConfig::default();
21//! assert_eq!(config.full_snapshot_interval, 10);
22//!
23//! // CheckpointType distinguishes full vs delta records
24//! let full = CheckpointType::Full;
25//! let delta = CheckpointType::Delta {
26//!     base_checkpoint_id: "ckpt-001".to_string(),
27//! };
28//! ```
29
30use std::collections::HashMap;
31
32use async_trait::async_trait;
33use serde::{Deserialize, Serialize, de::DeserializeOwned};
34use serde_json::Value;
35
36use crate::checkpoint::Checkpointer;
37use crate::error::GraphError;
38use crate::state::{Checkpoint, State};
39
40/// Trait for types that can compute and apply incremental diffs.
41///
42/// Implementors define an associated `Delta` type representing the difference
43/// between two instances. The trait guarantees a round-trip property:
44///
45/// > For any states `s1` and `s2`, `Diff::apply(&s1, &Diff::diff(&s1, &s2)) == s2`.
46///
47/// # Example
48///
49/// ```rust,ignore
50/// use adk_graph::delta::Diff;
51/// use serde::{Serialize, Deserialize};
52///
53/// #[derive(Clone, Debug, PartialEq)]
54/// struct Counter(u64);
55///
56/// #[derive(Clone, Debug, Serialize, Deserialize)]
57/// struct CounterDelta(i64);
58///
59/// impl Diff for Counter {
60///     type Delta = CounterDelta;
61///
62///     fn diff(old: &Self, new: &Self) -> Self::Delta {
63///         CounterDelta(new.0 as i64 - old.0 as i64)
64///     }
65///
66///     fn apply(base: &Self, delta: &Self::Delta) -> Self {
67///         Counter((base.0 as i64 + delta.0) as u64)
68///     }
69/// }
70///
71/// let s1 = Counter(5);
72/// let s2 = Counter(12);
73/// let delta = Counter::diff(&s1, &s2);
74/// assert_eq!(Counter::apply(&s1, &delta), s2);
75/// ```
76pub trait Diff: Sized {
77    /// The delta representation capturing the difference between two states.
78    ///
79    /// Must be serializable for checkpoint storage and sendable across async
80    /// boundaries.
81    type Delta: Clone + Serialize + DeserializeOwned + Send + Sync;
82
83    /// Compute the delta that transforms `old` into `new`.
84    ///
85    /// The returned delta, when applied to `old` via [`Diff::apply`], must
86    /// reproduce `new` exactly.
87    fn diff(old: &Self, new: &Self) -> Self::Delta;
88
89    /// Apply a delta to a base state, producing the resulting state.
90    ///
91    /// This is the inverse of [`Diff::diff`]: applying the delta produced by
92    /// `diff(old, new)` to `old` yields `new`.
93    fn apply(base: &Self, delta: &Self::Delta) -> Self;
94}
95
96/// Configuration for delta-based checkpoint compression.
97///
98/// Controls how frequently full snapshots are stored among the stream of delta
99/// records. A full snapshot is stored every `full_snapshot_interval` steps,
100/// bounding the number of deltas that must be replayed during reconstruction.
101///
102/// # Example
103///
104/// ```rust
105/// use adk_graph::delta::DeltaConfig;
106///
107/// // Default: full snapshot every 10 steps
108/// let config = DeltaConfig::default();
109/// assert_eq!(config.full_snapshot_interval, 10);
110///
111/// // Custom interval
112/// let config = DeltaConfig { full_snapshot_interval: 5 };
113/// assert_eq!(config.full_snapshot_interval, 5);
114/// ```
115#[derive(Debug, Clone)]
116pub struct DeltaConfig {
117    /// Store a full snapshot every N steps.
118    ///
119    /// At step boundaries divisible by this value, a full state snapshot is
120    /// persisted instead of a delta. This bounds reconstruction cost to at most
121    /// `full_snapshot_interval - 1` delta applications.
122    ///
123    /// Default: 10.
124    pub full_snapshot_interval: u32,
125}
126
127impl Default for DeltaConfig {
128    fn default() -> Self {
129        Self { full_snapshot_interval: 10 }
130    }
131}
132
133/// Discriminates between full state snapshots and incremental delta records.
134///
135/// Each persisted checkpoint is tagged with its type so the loader knows whether
136/// to use the payload directly (full) or apply it as a delta on top of a base
137/// checkpoint.
138///
139/// # Example
140///
141/// ```rust
142/// use adk_graph::delta::CheckpointType;
143///
144/// let full = CheckpointType::Full;
145/// assert!(matches!(full, CheckpointType::Full));
146///
147/// let delta = CheckpointType::Delta {
148///     base_checkpoint_id: "ckpt-042".to_string(),
149/// };
150/// if let CheckpointType::Delta { base_checkpoint_id } = &delta {
151///     assert_eq!(base_checkpoint_id, "ckpt-042");
152/// }
153/// ```
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub enum CheckpointType {
156    /// A complete state snapshot — no base required for reconstruction.
157    Full,
158    /// An incremental delta relative to a base checkpoint.
159    Delta {
160        /// The identifier of the checkpoint this delta is relative to.
161        base_checkpoint_id: String,
162    },
163}
164
165/// Delta representation for `Vec<Value>`.
166///
167/// Captures either appended items (when the new vec extends the old one) or a
168/// full replacement (when items were removed or modified in the middle).
169///
170/// # Example
171///
172/// ```rust
173/// use adk_graph::delta::{Diff, VecDelta};
174/// use serde_json::{Value, json};
175///
176/// let old = vec![json!(1), json!(2), json!(3)];
177/// let new = vec![json!(1), json!(2), json!(3), json!(4), json!(5)];
178///
179/// let delta = <Vec<Value> as Diff>::diff(&old, &new);
180/// assert!(!delta.full_replacement);
181/// assert_eq!(delta.start_index, 3);
182/// assert_eq!(delta.items, vec![json!(4), json!(5)]);
183///
184/// let reconstructed = <Vec<Value> as Diff>::apply(&old, &delta);
185/// assert_eq!(reconstructed, new);
186/// ```
187#[derive(Clone, Debug, Serialize, Deserialize)]
188pub struct VecDelta {
189    /// If true, the delta is a full replacement (for non-append-only changes).
190    pub full_replacement: bool,
191    /// Start index for appended items (only used when `full_replacement` is false).
192    pub start_index: usize,
193    /// The items (appended items or full replacement).
194    pub items: Vec<Value>,
195}
196
197impl Diff for Vec<Value> {
198    type Delta = VecDelta;
199
200    /// Compute the delta between two `Vec<Value>` instances.
201    ///
202    /// If `new` is a strict extension of `old` (i.e., `old` is a prefix of `new`),
203    /// the delta captures only the appended items and the start index. Otherwise,
204    /// the delta stores the full new vec as a replacement.
205    ///
206    /// # Example
207    ///
208    /// ```rust
209    /// use adk_graph::delta::Diff;
210    /// use serde_json::{Value, json};
211    ///
212    /// // Append case
213    /// let old = vec![json!("a"), json!("b")];
214    /// let new = vec![json!("a"), json!("b"), json!("c")];
215    /// let delta = <Vec<Value> as Diff>::diff(&old, &new);
216    /// assert!(!delta.full_replacement);
217    ///
218    /// // Modification case (full replacement)
219    /// let old = vec![json!(1), json!(2)];
220    /// let new = vec![json!(1), json!(99)];
221    /// let delta = <Vec<Value> as Diff>::diff(&old, &new);
222    /// assert!(delta.full_replacement);
223    /// ```
224    fn diff(old: &Self, new: &Self) -> Self::Delta {
225        // Check if new is a strict extension of old (old is a prefix of new)
226        if new.len() >= old.len() && old.iter().zip(new.iter()).all(|(a, b)| a == b) {
227            VecDelta {
228                full_replacement: false,
229                start_index: old.len(),
230                items: new[old.len()..].to_vec(),
231            }
232        } else {
233            // Items were removed or modified — store full replacement
234            VecDelta { full_replacement: true, start_index: 0, items: new.clone() }
235        }
236    }
237
238    /// Apply a delta to a base `Vec<Value>`, producing the resulting vec.
239    ///
240    /// If the delta is a full replacement, the base is ignored and the delta's
241    /// items are returned directly. Otherwise, the base is truncated to
242    /// `start_index` and the delta's items are appended.
243    ///
244    /// # Example
245    ///
246    /// ```rust
247    /// use adk_graph::delta::Diff;
248    /// use serde_json::{Value, json};
249    ///
250    /// let old = vec![json!(1), json!(2)];
251    /// let new = vec![json!(1), json!(2), json!(3)];
252    /// let delta = <Vec<Value> as Diff>::diff(&old, &new);
253    /// assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
254    /// ```
255    fn apply(base: &Self, delta: &Self::Delta) -> Self {
256        if delta.full_replacement {
257            delta.items.clone()
258        } else {
259            let mut result = base[..delta.start_index].to_vec();
260            result.extend_from_slice(&delta.items);
261            result
262        }
263    }
264}
265
266/// Delta representation for `HashMap<String, Value>`.
267///
268/// Captures the difference between two maps as three disjoint sets:
269/// - `added`: keys present in the new map but not in the old map
270/// - `removed`: keys present in the old map but not in the new map
271/// - `modified`: keys present in both maps but with different values
272///
273/// # Example
274///
275/// ```rust
276/// use adk_graph::delta::{Diff, MapDelta};
277/// use serde_json::{Value, json};
278/// use std::collections::HashMap;
279///
280/// let old: HashMap<String, Value> = [
281///     ("a".to_string(), json!(1)),
282///     ("b".to_string(), json!(2)),
283/// ].into_iter().collect();
284///
285/// let new: HashMap<String, Value> = [
286///     ("a".to_string(), json!(1)),
287///     ("b".to_string(), json!(99)),
288///     ("c".to_string(), json!(3)),
289/// ].into_iter().collect();
290///
291/// let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
292/// assert_eq!(delta.added.get("c"), Some(&json!(3)));
293/// assert_eq!(delta.removed, Vec::<String>::new());
294/// assert_eq!(delta.modified.get("b"), Some(&json!(99)));
295///
296/// let reconstructed = <HashMap<String, Value> as Diff>::apply(&old, &delta);
297/// assert_eq!(reconstructed, new);
298/// ```
299#[derive(Clone, Debug, Serialize, Deserialize)]
300pub struct MapDelta {
301    /// Keys present in the new map but not in the old map, with their values.
302    pub added: HashMap<String, Value>,
303    /// Keys present in the old map but not in the new map.
304    pub removed: Vec<String>,
305    /// Keys present in both maps but with different values (new values stored).
306    pub modified: HashMap<String, Value>,
307}
308
309impl Diff for HashMap<String, Value> {
310    type Delta = MapDelta;
311
312    /// Compute the delta between two `HashMap<String, Value>` instances.
313    ///
314    /// Classifies each key into one of three categories:
315    /// - **added**: present in `new` but absent from `old`
316    /// - **removed**: present in `old` but absent from `new`
317    /// - **modified**: present in both but with different values
318    ///
319    /// # Example
320    ///
321    /// ```rust
322    /// use adk_graph::delta::Diff;
323    /// use serde_json::{Value, json};
324    /// use std::collections::HashMap;
325    ///
326    /// let old: HashMap<String, Value> = [
327    ///     ("x".to_string(), json!("hello")),
328    ///     ("y".to_string(), json!(42)),
329    /// ].into_iter().collect();
330    ///
331    /// let new: HashMap<String, Value> = [
332    ///     ("x".to_string(), json!("world")),
333    ///     ("z".to_string(), json!(true)),
334    /// ].into_iter().collect();
335    ///
336    /// let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
337    /// assert!(delta.added.contains_key("z"));
338    /// assert!(delta.removed.contains(&"y".to_string()));
339    /// assert!(delta.modified.contains_key("x"));
340    /// ```
341    fn diff(old: &Self, new: &Self) -> Self::Delta {
342        let mut added = HashMap::new();
343        let mut removed = Vec::new();
344        let mut modified = HashMap::new();
345
346        // Find removed and modified keys
347        for (key, old_value) in old {
348            match new.get(key) {
349                None => removed.push(key.clone()),
350                Some(new_value) if new_value != old_value => {
351                    modified.insert(key.clone(), new_value.clone());
352                }
353                _ => {} // unchanged
354            }
355        }
356
357        // Find added keys
358        for (key, new_value) in new {
359            if !old.contains_key(key) {
360                added.insert(key.clone(), new_value.clone());
361            }
362        }
363
364        MapDelta { added, removed, modified }
365    }
366
367    /// Apply a delta to a base `HashMap<String, Value>`, producing the resulting map.
368    ///
369    /// Operations are applied in order: remove keys, insert added keys, update
370    /// modified keys.
371    ///
372    /// # Example
373    ///
374    /// ```rust
375    /// use adk_graph::delta::Diff;
376    /// use serde_json::{Value, json};
377    /// use std::collections::HashMap;
378    ///
379    /// let old: HashMap<String, Value> = [
380    ///     ("a".to_string(), json!(1)),
381    ///     ("b".to_string(), json!(2)),
382    /// ].into_iter().collect();
383    ///
384    /// let new: HashMap<String, Value> = [
385    ///     ("a".to_string(), json!(1)),
386    ///     ("c".to_string(), json!(3)),
387    /// ].into_iter().collect();
388    ///
389    /// let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
390    /// assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
391    /// ```
392    fn apply(base: &Self, delta: &Self::Delta) -> Self {
393        let mut result = base.clone();
394
395        // Remove keys
396        for key in &delta.removed {
397            result.remove(key);
398        }
399
400        // Insert added keys
401        for (key, value) in &delta.added {
402            result.insert(key.clone(), value.clone());
403        }
404
405        // Update modified keys
406        for (key, value) in &delta.modified {
407            result.insert(key.clone(), value.clone());
408        }
409
410        result
411    }
412}
413
414/// An individual edit operation for string diffs.
415///
416/// Represents one segment of a string diff: text that is unchanged, text that
417/// was inserted, or a deletion of characters from the original string.
418///
419/// # Example
420///
421/// ```rust
422/// use adk_graph::delta::StringOp;
423///
424/// let ops = vec![
425///     StringOp::Equal("hello ".to_string()),
426///     StringOp::Delete(5),   // "world" deleted
427///     StringOp::Insert("rust".to_string()),
428/// ];
429/// ```
430#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
431pub enum StringOp {
432    /// A segment of text that is identical in both old and new strings.
433    Equal(String),
434    /// Text that was inserted in the new string (not present in old).
435    Insert(String),
436    /// Number of characters deleted from the old string (not present in new).
437    Delete(usize),
438}
439
440/// Delta representation for `String`.
441///
442/// Captures the difference between two strings as a sequence of edit operations.
443/// When applied to the old string, these operations reconstruct the new string.
444///
445/// Uses the `similar` crate (when the `delta-checkpoint` feature is enabled) to
446/// compute character-level diffs.
447///
448/// # Example
449///
450/// ```rust
451/// use adk_graph::delta::{Diff, StringDelta, StringOp};
452///
453/// let old = "hello world".to_string();
454/// let new = "hello rust".to_string();
455///
456/// let delta = <String as Diff>::diff(&old, &new);
457/// let reconstructed = <String as Diff>::apply(&old, &delta);
458/// assert_eq!(reconstructed, new);
459/// ```
460#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
461pub struct StringDelta {
462    /// The sequence of edit operations that transform the old string into the new.
463    pub ops: Vec<StringOp>,
464}
465
466#[cfg(feature = "delta-checkpoint")]
467impl Diff for String {
468    type Delta = StringDelta;
469
470    /// Compute the delta between two strings using character-level diffing.
471    ///
472    /// Uses `similar::TextDiff::from_chars()` to compute the minimal set of
473    /// edit operations that transform `old` into `new`.
474    ///
475    /// # Example
476    ///
477    /// ```rust
478    /// use adk_graph::delta::{Diff, StringOp};
479    ///
480    /// let old = "abcdef".to_string();
481    /// let new = "abXYef".to_string();
482    ///
483    /// let delta = <String as Diff>::diff(&old, &new);
484    /// // The delta contains: Equal("ab"), Delete(2), Insert("XY"), Equal("ef")
485    /// assert_eq!(<String as Diff>::apply(&old, &delta), new);
486    /// ```
487    fn diff(old: &Self, new: &Self) -> Self::Delta {
488        use similar::{ChangeTag, TextDiff};
489
490        let text_diff = TextDiff::from_chars(old.as_str(), new.as_str());
491        let mut ops = Vec::new();
492
493        for change in text_diff.iter_all_changes() {
494            let value = change.value();
495            match change.tag() {
496                ChangeTag::Equal => {
497                    // Merge consecutive Equal ops
498                    if let Some(StringOp::Equal(s)) = ops.last_mut() {
499                        s.push_str(value);
500                    } else {
501                        ops.push(StringOp::Equal(value.to_string()));
502                    }
503                }
504                ChangeTag::Insert => {
505                    // Merge consecutive Insert ops
506                    if let Some(StringOp::Insert(s)) = ops.last_mut() {
507                        s.push_str(value);
508                    } else {
509                        ops.push(StringOp::Insert(value.to_string()));
510                    }
511                }
512                ChangeTag::Delete => {
513                    // Merge consecutive Delete ops
514                    if let Some(StringOp::Delete(count)) = ops.last_mut() {
515                        *count += value.chars().count();
516                    } else {
517                        ops.push(StringOp::Delete(value.chars().count()));
518                    }
519                }
520            }
521        }
522
523        StringDelta { ops }
524    }
525
526    /// Apply a delta to a base string, producing the resulting string.
527    ///
528    /// Replays the edit operations in order:
529    /// - `Equal(s)`: advance past `s.len()` characters in the base (copy them)
530    /// - `Delete(n)`: skip `n` characters in the base
531    /// - `Insert(s)`: append `s` to the result
532    ///
533    /// # Example
534    ///
535    /// ```rust
536    /// use adk_graph::delta::Diff;
537    ///
538    /// let old = "hello world".to_string();
539    /// let new = "hello rust".to_string();
540    /// let delta = <String as Diff>::diff(&old, &new);
541    /// assert_eq!(<String as Diff>::apply(&old, &delta), new);
542    /// ```
543    fn apply(base: &Self, delta: &Self::Delta) -> Self {
544        let mut result = String::new();
545        let mut chars = base.chars();
546
547        for op in &delta.ops {
548            match op {
549                StringOp::Equal(s) => {
550                    // Advance past the equal characters in base
551                    for _ in 0..s.chars().count() {
552                        if let Some(c) = chars.next() {
553                            result.push(c);
554                        }
555                    }
556                }
557                StringOp::Delete(count) => {
558                    // Skip characters in base
559                    for _ in 0..*count {
560                        chars.next();
561                    }
562                }
563                StringOp::Insert(s) => {
564                    // Append inserted text
565                    result.push_str(s);
566                }
567            }
568        }
569
570        result
571    }
572}
573
574// --- Metadata keys used to tag checkpoint records ---
575
576/// Metadata key indicating the checkpoint type (full or delta).
577const META_CHECKPOINT_TYPE: &str = "__delta_ckpt_type";
578/// Metadata key storing the serialized delta payload for delta checkpoints.
579const META_DELTA_PAYLOAD: &str = "__delta_ckpt_payload";
580/// Metadata key storing the base checkpoint ID for delta checkpoints.
581const META_BASE_CHECKPOINT_ID: &str = "__delta_ckpt_base_id";
582
583/// Metadata value indicating a full snapshot.
584const TYPE_FULL: &str = "full";
585/// Metadata value indicating a delta record.
586const TYPE_DELTA: &str = "delta";
587
588/// Wraps any [`Checkpointer`] with delta compression.
589///
590/// On save, the `DeltaCheckpointer` stores either a full state snapshot or an
591/// incremental delta depending on the step number and the configured
592/// [`DeltaConfig::full_snapshot_interval`]. On load, it reconstructs the full
593/// state by finding the nearest full snapshot and replaying deltas forward.
594///
595/// The `DeltaCheckpointer` exposes the same [`Checkpointer`] trait interface,
596/// making it a drop-in replacement for any existing checkpointer.
597///
598/// # Example
599///
600/// ```rust,ignore
601/// use adk_graph::delta::{DeltaCheckpointer, DeltaConfig};
602/// use adk_graph::checkpoint::MemoryCheckpointer;
603///
604/// let inner = MemoryCheckpointer::new();
605/// let config = DeltaConfig { full_snapshot_interval: 5 };
606/// let checkpointer = DeltaCheckpointer::new(inner, config);
607///
608/// // Use checkpointer as any other Checkpointer implementation
609/// ```
610pub struct DeltaCheckpointer<C: Checkpointer> {
611    inner: C,
612    config: DeltaConfig,
613}
614
615impl<C: Checkpointer> DeltaCheckpointer<C> {
616    /// Create a new `DeltaCheckpointer` wrapping the given inner checkpointer.
617    ///
618    /// # Arguments
619    ///
620    /// * `inner` - The underlying checkpointer used for actual storage.
621    /// * `config` - Configuration controlling full snapshot frequency.
622    pub fn new(inner: C, config: DeltaConfig) -> Self {
623        Self { inner, config }
624    }
625
626    /// Returns a reference to the inner checkpointer.
627    pub fn inner(&self) -> &C {
628        &self.inner
629    }
630
631    /// Returns the delta configuration.
632    pub fn config(&self) -> &DeltaConfig {
633        &self.config
634    }
635
636    /// Determine whether a given step should be a full snapshot.
637    fn is_full_snapshot_step(&self, step: usize) -> bool {
638        step == 0 || (step as u32).is_multiple_of(self.config.full_snapshot_interval)
639    }
640
641    /// Reconstruct full state from a list of checkpoints, ascending by version,
642    /// starting from a full snapshot and replaying deltas forward up to (and
643    /// including) the target version.
644    fn reconstruct_state(
645        checkpoints: &[Checkpoint],
646        target_version: u64,
647    ) -> crate::error::Result<State> {
648        // Find the nearest full snapshot at or before the target
649        let full_snapshot_idx = checkpoints
650            .iter()
651            .enumerate()
652            .rev()
653            .find(|(_, cp)| {
654                cp.version <= target_version
655                    && cp.metadata.get(META_CHECKPOINT_TYPE).and_then(|v| v.as_str())
656                        == Some(TYPE_FULL)
657            })
658            .map(|(idx, _)| idx);
659
660        let full_idx = full_snapshot_idx.ok_or_else(|| {
661            GraphError::CheckpointError(
662                "No full snapshot found for state reconstruction".to_string(),
663            )
664        })?;
665
666        let base_checkpoint = &checkpoints[full_idx];
667        let mut state = base_checkpoint.state.clone();
668
669        // Replay deltas forward from the full snapshot to the target step
670        for cp in &checkpoints[full_idx + 1..] {
671            if cp.version > target_version {
672                break;
673            }
674
675            let cp_type =
676                cp.metadata.get(META_CHECKPOINT_TYPE).and_then(|v| v.as_str()).unwrap_or(TYPE_FULL);
677
678            if cp_type == TYPE_DELTA {
679                // Extract and apply the delta
680                let delta_json = cp.metadata.get(META_DELTA_PAYLOAD).ok_or_else(|| {
681                    GraphError::CheckpointError(format!(
682                        "Delta checkpoint at step {} missing payload",
683                        cp.step
684                    ))
685                })?;
686
687                let delta: MapDelta = serde_json::from_value(delta_json.clone()).map_err(|e| {
688                    GraphError::CheckpointError(format!(
689                        "Failed to deserialize delta at step {}: {e}",
690                        cp.step
691                    ))
692                })?;
693
694                state = <HashMap<String, Value> as Diff>::apply(&state, &delta);
695            } else {
696                // It's a full snapshot — use its state directly
697                state = cp.state.clone();
698            }
699        }
700
701        Ok(state)
702    }
703}
704
705#[async_trait]
706impl<C: Checkpointer> Checkpointer for DeltaCheckpointer<C> {
707    /// Save a checkpoint with delta compression.
708    ///
709    /// If the step is a full snapshot boundary (step == 0 or step %
710    /// full_snapshot_interval == 0), the full state is stored. Otherwise, the
711    /// delta from the previous checkpoint is computed and stored, with the
712    /// checkpoint's `state` field set to an empty map to save space.
713    async fn save(&self, checkpoint: &Checkpoint) -> crate::error::Result<String> {
714        if self.is_full_snapshot_step(checkpoint.step) {
715            // Store full snapshot with type metadata
716            let mut full_checkpoint = checkpoint.clone();
717            full_checkpoint
718                .metadata
719                .insert(META_CHECKPOINT_TYPE.to_string(), Value::String(TYPE_FULL.to_string()));
720            self.inner.save(&full_checkpoint).await
721        } else {
722            // Load the previous checkpoint to compute delta
723            let all_checkpoints = self.inner.list(&checkpoint.thread_id).await?;
724
725            // The previous checkpoint is the thread's newest.
726            let previous = all_checkpoints.last();
727
728            match previous {
729                Some(prev_cp) => {
730                    // Reconstruct the previous state (it might itself be a delta)
731                    let prev_state = Self::reconstruct_state(&all_checkpoints, prev_cp.version)?;
732
733                    // Compute delta from previous state to current state
734                    let delta =
735                        <HashMap<String, Value> as Diff>::diff(&prev_state, &checkpoint.state);
736
737                    // Store the delta checkpoint with minimal state (empty map)
738                    let mut delta_checkpoint = checkpoint.clone();
739                    delta_checkpoint.state = HashMap::new(); // Don't store full state
740                    delta_checkpoint.metadata.insert(
741                        META_CHECKPOINT_TYPE.to_string(),
742                        Value::String(TYPE_DELTA.to_string()),
743                    );
744                    delta_checkpoint.metadata.insert(
745                        META_BASE_CHECKPOINT_ID.to_string(),
746                        Value::String(prev_cp.checkpoint_id.clone()),
747                    );
748                    delta_checkpoint.metadata.insert(
749                        META_DELTA_PAYLOAD.to_string(),
750                        serde_json::to_value(&delta).map_err(|e| {
751                            GraphError::CheckpointError(format!("Failed to serialize delta: {e}"))
752                        })?,
753                    );
754
755                    self.inner.save(&delta_checkpoint).await
756                }
757                None => {
758                    // No previous checkpoint found — store as full snapshot
759                    let mut full_checkpoint = checkpoint.clone();
760                    full_checkpoint.metadata.insert(
761                        META_CHECKPOINT_TYPE.to_string(),
762                        Value::String(TYPE_FULL.to_string()),
763                    );
764                    self.inner.save(&full_checkpoint).await
765                }
766            }
767        }
768    }
769
770    /// Load the latest checkpoint for a thread, reconstructing full state.
771    ///
772    /// Finds the latest checkpoint, then reconstructs the full state by
773    /// replaying deltas from the nearest full snapshot forward.
774    async fn load(&self, thread_id: &str) -> crate::error::Result<Option<Checkpoint>> {
775        let all_checkpoints = self.inner.list(thread_id).await?;
776        if all_checkpoints.is_empty() {
777            return Ok(None);
778        }
779
780        // Get the latest checkpoint
781        let latest = all_checkpoints.last().unwrap();
782
783        // Reconstruct the full state
784        let full_state = Self::reconstruct_state(&all_checkpoints, latest.version)?;
785
786        // Return the latest checkpoint with reconstructed state
787        let mut result = latest.clone();
788        result.state = full_state;
789        Ok(Some(result))
790    }
791
792    /// Load a specific checkpoint by ID, reconstructing full state.
793    ///
794    /// Finds the checkpoint by ID, determines its thread, then reconstructs
795    /// the full state by replaying deltas from the nearest full snapshot.
796    async fn load_by_id(&self, checkpoint_id: &str) -> crate::error::Result<Option<Checkpoint>> {
797        let checkpoint = self.inner.load_by_id(checkpoint_id).await?;
798        match checkpoint {
799            Some(cp) => {
800                let all_checkpoints = self.inner.list(&cp.thread_id).await?;
801                let full_state = Self::reconstruct_state(&all_checkpoints, cp.version)?;
802
803                let mut result = cp;
804                result.state = full_state;
805                Ok(Some(result))
806            }
807            None => Ok(None),
808        }
809    }
810
811    /// List all checkpoints for a thread.
812    ///
813    /// Delegates directly to the inner checkpointer. Note that delta
814    /// checkpoints in the list will have empty state fields — use
815    /// [`load`](Self::load) or [`load_by_id`](Self::load_by_id) to get
816    /// reconstructed state.
817    async fn list(&self, thread_id: &str) -> crate::error::Result<Vec<Checkpoint>> {
818        self.inner.list(thread_id).await
819    }
820
821    /// Delete all checkpoints for a thread.
822    ///
823    /// Delegates directly to the inner checkpointer.
824    async fn delete(&self, thread_id: &str) -> crate::error::Result<()> {
825        self.inner.delete(thread_id).await
826    }
827
828    /// Removes what the policy discards, except the checkpoints a retained delta
829    /// is reconstructed from.
830    ///
831    /// Every checkpoint from the newest full snapshot at or before the oldest
832    /// retained checkpoint onward is kept, so each retained checkpoint still loads.
833    async fn prune(
834        &self,
835        thread_id: &str,
836        policy: &crate::checkpoint::RetentionPolicy,
837    ) -> crate::error::Result<usize> {
838        let all_checkpoints = self.inner.list(thread_id).await?;
839        let expired = policy.expired(&all_checkpoints);
840        let Some(oldest_kept) = all_checkpoints
841            .iter()
842            .filter(|cp| !expired.contains(&cp.checkpoint_id))
843            .map(|cp| cp.version)
844            .min()
845        else {
846            return Ok(0);
847        };
848        let base = all_checkpoints
849            .iter()
850            .filter(|cp| {
851                cp.version <= oldest_kept
852                    && cp.metadata.get(META_CHECKPOINT_TYPE).and_then(|v| v.as_str())
853                        != Some(TYPE_DELTA)
854            })
855            .map(|cp| cp.version)
856            .max()
857            .unwrap_or(0);
858        let removable: Vec<&Checkpoint> =
859            all_checkpoints.iter().filter(|cp| cp.version < base).collect();
860        if removable.is_empty() {
861            return Ok(0);
862        }
863        // The inner store applies a count limit that selects exactly these.
864        let keep = all_checkpoints.len() - removable.len();
865        self.inner.prune(thread_id, &crate::checkpoint::RetentionPolicy::keep_last(keep)).await
866    }
867}
868
869#[cfg(test)]
870mod tests {
871    use super::*;
872
873    #[test]
874    fn delta_config_default_interval_is_10() {
875        let config = DeltaConfig::default();
876        assert_eq!(config.full_snapshot_interval, 10);
877    }
878
879    #[test]
880    fn delta_config_custom_interval() {
881        let config = DeltaConfig { full_snapshot_interval: 25 };
882        assert_eq!(config.full_snapshot_interval, 25);
883    }
884
885    #[test]
886    fn checkpoint_type_full_variant() {
887        let ct = CheckpointType::Full;
888        assert!(matches!(ct, CheckpointType::Full));
889    }
890
891    #[test]
892    fn checkpoint_type_delta_variant() {
893        let ct = CheckpointType::Delta { base_checkpoint_id: "abc-123".to_string() };
894        assert!(matches!(ct, CheckpointType::Delta { .. }));
895        if let CheckpointType::Delta { base_checkpoint_id } = ct {
896            assert_eq!(base_checkpoint_id, "abc-123");
897        }
898    }
899
900    #[test]
901    fn vec_value_diff_append() {
902        use serde_json::json;
903        let old = vec![json!(1), json!(2), json!(3)];
904        let new = vec![json!(1), json!(2), json!(3), json!(4), json!(5)];
905        let delta = <Vec<Value> as Diff>::diff(&old, &new);
906        assert!(!delta.full_replacement);
907        assert_eq!(delta.start_index, 3);
908        assert_eq!(delta.items, vec![json!(4), json!(5)]);
909        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
910    }
911
912    #[test]
913    fn vec_value_diff_identical() {
914        use serde_json::json;
915        let old = vec![json!("a"), json!("b")];
916        let new = vec![json!("a"), json!("b")];
917        let delta = <Vec<Value> as Diff>::diff(&old, &new);
918        assert!(!delta.full_replacement);
919        assert_eq!(delta.start_index, 2);
920        assert!(delta.items.is_empty());
921        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
922    }
923
924    #[test]
925    fn vec_value_diff_shorter_new() {
926        use serde_json::json;
927        let old = vec![json!(1), json!(2), json!(3)];
928        let new = vec![json!(1)];
929        let delta = <Vec<Value> as Diff>::diff(&old, &new);
930        assert!(delta.full_replacement);
931        assert_eq!(delta.items, vec![json!(1)]);
932        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
933    }
934
935    #[test]
936    fn vec_value_diff_modified_element() {
937        use serde_json::json;
938        let old = vec![json!(1), json!(2), json!(3)];
939        let new = vec![json!(1), json!(99), json!(3)];
940        let delta = <Vec<Value> as Diff>::diff(&old, &new);
941        assert!(delta.full_replacement);
942        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
943    }
944
945    #[test]
946    fn vec_value_diff_empty_to_items() {
947        use serde_json::json;
948        let old: Vec<Value> = vec![];
949        let new = vec![json!(1), json!(2)];
950        let delta = <Vec<Value> as Diff>::diff(&old, &new);
951        assert!(!delta.full_replacement);
952        assert_eq!(delta.start_index, 0);
953        assert_eq!(delta.items, vec![json!(1), json!(2)]);
954        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
955    }
956
957    #[test]
958    fn vec_value_diff_items_to_empty() {
959        use serde_json::json;
960        let old = vec![json!(1), json!(2)];
961        let new: Vec<Value> = vec![];
962        let delta = <Vec<Value> as Diff>::diff(&old, &new);
963        assert!(delta.full_replacement);
964        assert!(delta.items.is_empty());
965        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
966    }
967
968    #[test]
969    fn map_value_diff_added_keys() {
970        use serde_json::json;
971        let old: HashMap<String, Value> = [("a".to_string(), json!(1))].into_iter().collect();
972        let new: HashMap<String, Value> =
973            [("a".to_string(), json!(1)), ("b".to_string(), json!(2)), ("c".to_string(), json!(3))]
974                .into_iter()
975                .collect();
976        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
977        assert!(delta.removed.is_empty());
978        assert!(delta.modified.is_empty());
979        assert_eq!(delta.added.len(), 2);
980        assert_eq!(delta.added.get("b"), Some(&json!(2)));
981        assert_eq!(delta.added.get("c"), Some(&json!(3)));
982        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
983    }
984
985    #[test]
986    fn map_value_diff_removed_keys() {
987        use serde_json::json;
988        let old: HashMap<String, Value> =
989            [("a".to_string(), json!(1)), ("b".to_string(), json!(2)), ("c".to_string(), json!(3))]
990                .into_iter()
991                .collect();
992        let new: HashMap<String, Value> = [("a".to_string(), json!(1))].into_iter().collect();
993        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
994        assert!(delta.added.is_empty());
995        assert!(delta.modified.is_empty());
996        assert_eq!(delta.removed.len(), 2);
997        assert!(delta.removed.contains(&"b".to_string()));
998        assert!(delta.removed.contains(&"c".to_string()));
999        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
1000    }
1001
1002    #[test]
1003    fn map_value_diff_modified_keys() {
1004        use serde_json::json;
1005        let old: HashMap<String, Value> =
1006            [("a".to_string(), json!(1)), ("b".to_string(), json!(2))].into_iter().collect();
1007        let new: HashMap<String, Value> =
1008            [("a".to_string(), json!(1)), ("b".to_string(), json!(99))].into_iter().collect();
1009        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
1010        assert!(delta.added.is_empty());
1011        assert!(delta.removed.is_empty());
1012        assert_eq!(delta.modified.len(), 1);
1013        assert_eq!(delta.modified.get("b"), Some(&json!(99)));
1014        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
1015    }
1016
1017    #[test]
1018    fn map_value_diff_mixed_changes() {
1019        use serde_json::json;
1020        let old: HashMap<String, Value> =
1021            [("a".to_string(), json!(1)), ("b".to_string(), json!(2)), ("c".to_string(), json!(3))]
1022                .into_iter()
1023                .collect();
1024        let new: HashMap<String, Value> = [
1025            ("a".to_string(), json!(1)),
1026            ("b".to_string(), json!(99)),
1027            ("d".to_string(), json!(4)),
1028        ]
1029        .into_iter()
1030        .collect();
1031        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
1032        assert_eq!(delta.added.len(), 1);
1033        assert_eq!(delta.added.get("d"), Some(&json!(4)));
1034        assert_eq!(delta.removed, vec!["c".to_string()]);
1035        assert_eq!(delta.modified.len(), 1);
1036        assert_eq!(delta.modified.get("b"), Some(&json!(99)));
1037        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
1038    }
1039
1040    #[test]
1041    fn map_value_diff_identical() {
1042        use serde_json::json;
1043        let old: HashMap<String, Value> =
1044            [("a".to_string(), json!(1)), ("b".to_string(), json!(2))].into_iter().collect();
1045        let new = old.clone();
1046        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
1047        assert!(delta.added.is_empty());
1048        assert!(delta.removed.is_empty());
1049        assert!(delta.modified.is_empty());
1050        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
1051    }
1052
1053    #[test]
1054    fn map_value_diff_empty_to_populated() {
1055        use serde_json::json;
1056        let old: HashMap<String, Value> = HashMap::new();
1057        let new: HashMap<String, Value> =
1058            [("a".to_string(), json!(1)), ("b".to_string(), json!(2))].into_iter().collect();
1059        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
1060        assert_eq!(delta.added.len(), 2);
1061        assert!(delta.removed.is_empty());
1062        assert!(delta.modified.is_empty());
1063        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
1064    }
1065
1066    #[test]
1067    fn map_value_diff_populated_to_empty() {
1068        use serde_json::json;
1069        let old: HashMap<String, Value> =
1070            [("a".to_string(), json!(1)), ("b".to_string(), json!(2))].into_iter().collect();
1071        let new: HashMap<String, Value> = HashMap::new();
1072        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
1073        assert!(delta.added.is_empty());
1074        assert_eq!(delta.removed.len(), 2);
1075        assert!(delta.modified.is_empty());
1076        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
1077    }
1078
1079    #[test]
1080    fn map_value_diff_nested_values() {
1081        use serde_json::json;
1082        let old: HashMap<String, Value> = [
1083            ("config".to_string(), json!({"host": "localhost", "port": 8080})),
1084            ("name".to_string(), json!("app")),
1085        ]
1086        .into_iter()
1087        .collect();
1088        let new: HashMap<String, Value> = [
1089            ("config".to_string(), json!({"host": "prod.example.com", "port": 443})),
1090            ("name".to_string(), json!("app")),
1091            ("version".to_string(), json!("1.0.0")),
1092        ]
1093        .into_iter()
1094        .collect();
1095        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
1096        assert_eq!(delta.added.get("version"), Some(&json!("1.0.0")));
1097        assert!(delta.removed.is_empty());
1098        assert_eq!(
1099            delta.modified.get("config"),
1100            Some(&json!({"host": "prod.example.com", "port": 443}))
1101        );
1102        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
1103    }
1104
1105    #[cfg(feature = "delta-checkpoint")]
1106    #[test]
1107    fn string_diff_identical() {
1108        let old = "hello world".to_string();
1109        let new = "hello world".to_string();
1110        let delta = <String as Diff>::diff(&old, &new);
1111        assert_eq!(delta.ops.len(), 1);
1112        assert_eq!(delta.ops[0], StringOp::Equal("hello world".to_string()));
1113        assert_eq!(<String as Diff>::apply(&old, &delta), new);
1114    }
1115
1116    #[cfg(feature = "delta-checkpoint")]
1117    #[test]
1118    fn string_diff_completely_different() {
1119        let old = "abc".to_string();
1120        let new = "xyz".to_string();
1121        let delta = <String as Diff>::diff(&old, &new);
1122        let reconstructed = <String as Diff>::apply(&old, &delta);
1123        assert_eq!(reconstructed, new);
1124    }
1125
1126    #[cfg(feature = "delta-checkpoint")]
1127    #[test]
1128    fn string_diff_suffix_change() {
1129        let old = "hello world".to_string();
1130        let new = "hello rust".to_string();
1131        let delta = <String as Diff>::diff(&old, &new);
1132        let reconstructed = <String as Diff>::apply(&old, &delta);
1133        assert_eq!(reconstructed, new);
1134    }
1135
1136    #[cfg(feature = "delta-checkpoint")]
1137    #[test]
1138    fn string_diff_prefix_change() {
1139        let old = "hello world".to_string();
1140        let new = "goodbye world".to_string();
1141        let delta = <String as Diff>::diff(&old, &new);
1142        let reconstructed = <String as Diff>::apply(&old, &delta);
1143        assert_eq!(reconstructed, new);
1144    }
1145
1146    #[cfg(feature = "delta-checkpoint")]
1147    #[test]
1148    fn string_diff_middle_insertion() {
1149        let old = "abcdef".to_string();
1150        let new = "abcXYZdef".to_string();
1151        let delta = <String as Diff>::diff(&old, &new);
1152        let reconstructed = <String as Diff>::apply(&old, &delta);
1153        assert_eq!(reconstructed, new);
1154    }
1155
1156    #[cfg(feature = "delta-checkpoint")]
1157    #[test]
1158    fn string_diff_middle_deletion() {
1159        let old = "abcXYZdef".to_string();
1160        let new = "abcdef".to_string();
1161        let delta = <String as Diff>::diff(&old, &new);
1162        let reconstructed = <String as Diff>::apply(&old, &delta);
1163        assert_eq!(reconstructed, new);
1164    }
1165
1166    #[cfg(feature = "delta-checkpoint")]
1167    #[test]
1168    fn string_diff_empty_to_content() {
1169        let old = String::new();
1170        let new = "hello".to_string();
1171        let delta = <String as Diff>::diff(&old, &new);
1172        assert_eq!(delta.ops.len(), 1);
1173        assert_eq!(delta.ops[0], StringOp::Insert("hello".to_string()));
1174        assert_eq!(<String as Diff>::apply(&old, &delta), new);
1175    }
1176
1177    #[cfg(feature = "delta-checkpoint")]
1178    #[test]
1179    fn string_diff_content_to_empty() {
1180        let old = "hello".to_string();
1181        let new = String::new();
1182        let delta = <String as Diff>::diff(&old, &new);
1183        assert_eq!(delta.ops.len(), 1);
1184        assert_eq!(delta.ops[0], StringOp::Delete(5));
1185        assert_eq!(<String as Diff>::apply(&old, &delta), new);
1186    }
1187
1188    #[cfg(feature = "delta-checkpoint")]
1189    #[test]
1190    fn string_diff_both_empty() {
1191        let old = String::new();
1192        let new = String::new();
1193        let delta = <String as Diff>::diff(&old, &new);
1194        assert!(delta.ops.is_empty());
1195        assert_eq!(<String as Diff>::apply(&old, &delta), new);
1196    }
1197
1198    #[cfg(feature = "delta-checkpoint")]
1199    #[test]
1200    fn string_diff_unicode() {
1201        let old = "héllo wörld 🌍".to_string();
1202        let new = "héllo rüst 🦀".to_string();
1203        let delta = <String as Diff>::diff(&old, &new);
1204        let reconstructed = <String as Diff>::apply(&old, &delta);
1205        assert_eq!(reconstructed, new);
1206    }
1207
1208    #[cfg(feature = "delta-checkpoint")]
1209    #[test]
1210    fn string_diff_multiline() {
1211        let old = "line1\nline2\nline3".to_string();
1212        let new = "line1\nmodified\nline3\nline4".to_string();
1213        let delta = <String as Diff>::diff(&old, &new);
1214        let reconstructed = <String as Diff>::apply(&old, &delta);
1215        assert_eq!(reconstructed, new);
1216    }
1217
1218    #[cfg(feature = "delta-checkpoint")]
1219    #[test]
1220    fn string_delta_serialization_round_trip() {
1221        let old = "hello world".to_string();
1222        let new = "hello rust".to_string();
1223        let delta = <String as Diff>::diff(&old, &new);
1224
1225        // Serialize and deserialize the delta
1226        let json = serde_json::to_string(&delta).unwrap();
1227        let deserialized: StringDelta = serde_json::from_str(&json).unwrap();
1228
1229        assert_eq!(<String as Diff>::apply(&old, &deserialized), new);
1230    }
1231
1232    /// Verify the Diff trait can be implemented and round-trips correctly.
1233    #[test]
1234    fn diff_trait_round_trip() {
1235        #[derive(Clone, Debug, PartialEq)]
1236        struct TestState(Vec<i32>);
1237
1238        #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
1239        struct TestDelta {
1240            added: Vec<i32>,
1241            removed_count: usize,
1242        }
1243
1244        impl Diff for TestState {
1245            type Delta = TestDelta;
1246
1247            fn diff(old: &Self, new: &Self) -> Self::Delta {
1248                // Simple: assume new extends or truncates old
1249                if new.0.len() >= old.0.len() {
1250                    TestDelta { added: new.0[old.0.len()..].to_vec(), removed_count: 0 }
1251                } else {
1252                    TestDelta { added: vec![], removed_count: old.0.len() - new.0.len() }
1253                }
1254            }
1255
1256            fn apply(base: &Self, delta: &Self::Delta) -> Self {
1257                let mut result = base.0.clone();
1258                if delta.removed_count > 0 {
1259                    result.truncate(result.len() - delta.removed_count);
1260                }
1261                result.extend_from_slice(&delta.added);
1262                TestState(result)
1263            }
1264        }
1265
1266        let s1 = TestState(vec![1, 2, 3]);
1267        let s2 = TestState(vec![1, 2, 3, 4, 5]);
1268        let delta = TestState::diff(&s1, &s2);
1269        let reconstructed = TestState::apply(&s1, &delta);
1270        assert_eq!(reconstructed, s2);
1271    }
1272
1273    // --- DeltaCheckpointer tests ---
1274
1275    use crate::checkpoint::MemoryCheckpointer;
1276
1277    fn make_state(pairs: &[(&str, i64)]) -> State {
1278        pairs.iter().map(|(k, v)| (k.to_string(), serde_json::json!(v))).collect()
1279    }
1280
1281    #[tokio::test]
1282    async fn delta_checkpointer_first_save_is_full() {
1283        let inner = MemoryCheckpointer::new();
1284        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 5 });
1285
1286        let state = make_state(&[("x", 1)]);
1287        let cp = Checkpoint::new("t1", state.clone(), 0, vec![]).with_version(1);
1288        dc.save(&cp).await.unwrap();
1289
1290        // Load should return the full state
1291        let loaded = dc.load("t1").await.unwrap().unwrap();
1292        assert_eq!(loaded.state, state);
1293        assert_eq!(
1294            loaded.metadata.get(META_CHECKPOINT_TYPE).and_then(|v| v.as_str()),
1295            Some(TYPE_FULL)
1296        );
1297    }
1298
1299    #[tokio::test]
1300    async fn delta_checkpointer_stores_delta_between_full_snapshots() {
1301        let inner = MemoryCheckpointer::new();
1302        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 5 });
1303
1304        // Step 0: full snapshot
1305        let state0 = make_state(&[("x", 1), ("y", 2)]);
1306        let cp0 = Checkpoint::new("t1", state0, 0, vec![]).with_version(1);
1307        dc.save(&cp0).await.unwrap();
1308
1309        // Step 1: should be delta
1310        let state1 = make_state(&[("x", 1), ("y", 3), ("z", 4)]);
1311        let cp1 = Checkpoint::new("t1", state1.clone(), 1, vec![]).with_version(2);
1312        dc.save(&cp1).await.unwrap();
1313
1314        // Load should reconstruct the full state at step 1
1315        let loaded = dc.load("t1").await.unwrap().unwrap();
1316        assert_eq!(loaded.state, state1);
1317        assert_eq!(loaded.step, 1);
1318    }
1319
1320    #[tokio::test]
1321    async fn delta_checkpointer_full_snapshot_at_interval() {
1322        let inner = MemoryCheckpointer::new();
1323        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 3 });
1324
1325        // Steps 0, 1, 2, 3
1326        for step in 0..=3 {
1327            let state = make_state(&[("counter", step as i64)]);
1328            let cp = Checkpoint::new("t1", state, step, vec![]).with_version(step as u64 + 1);
1329            dc.save(&cp).await.unwrap();
1330        }
1331
1332        // Step 3 should be a full snapshot (3 % 3 == 0)
1333        let all = dc.list("t1").await.unwrap();
1334        let step3 = all.iter().find(|cp| cp.step == 3).unwrap();
1335        assert_eq!(
1336            step3.metadata.get(META_CHECKPOINT_TYPE).and_then(|v| v.as_str()),
1337            Some(TYPE_FULL)
1338        );
1339
1340        // Step 1 should be a delta
1341        let step1 = all.iter().find(|cp| cp.step == 1).unwrap();
1342        assert_eq!(
1343            step1.metadata.get(META_CHECKPOINT_TYPE).and_then(|v| v.as_str()),
1344            Some(TYPE_DELTA)
1345        );
1346    }
1347
1348    #[tokio::test]
1349    async fn delta_checkpointer_load_by_id_reconstructs_state() {
1350        let inner = MemoryCheckpointer::new();
1351        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 10 });
1352
1353        // Step 0: full
1354        let state0 = make_state(&[("a", 1)]);
1355        let cp0 = Checkpoint::new("t1", state0, 0, vec![]).with_version(1);
1356        dc.save(&cp0).await.unwrap();
1357
1358        // Step 1: delta
1359        let state1 = make_state(&[("a", 1), ("b", 2)]);
1360        let cp1 = Checkpoint::new("t1", state1.clone(), 1, vec![]).with_version(2);
1361        let id1 = dc.save(&cp1).await.unwrap();
1362
1363        // Step 2: delta
1364        let state2 = make_state(&[("a", 1), ("b", 2), ("c", 3)]);
1365        let cp2 = Checkpoint::new("t1", state2.clone(), 2, vec![]).with_version(3);
1366        let id2 = dc.save(&cp2).await.unwrap();
1367
1368        // Load by ID for step 1
1369        let loaded1 = dc.load_by_id(&id1).await.unwrap().unwrap();
1370        assert_eq!(loaded1.state, state1);
1371
1372        // Load by ID for step 2
1373        let loaded2 = dc.load_by_id(&id2).await.unwrap().unwrap();
1374        assert_eq!(loaded2.state, state2);
1375    }
1376
1377    #[tokio::test]
1378    async fn delta_checkpointer_multiple_deltas_between_snapshots() {
1379        let inner = MemoryCheckpointer::new();
1380        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 5 });
1381
1382        // Create 5 checkpoints (step 0 = full, steps 1-4 = delta)
1383        let states: Vec<State> =
1384            (0..5).map(|i| make_state(&[("step", i), ("data", i * 10)])).collect();
1385
1386        for (step, state) in states.iter().enumerate() {
1387            let cp =
1388                Checkpoint::new("t1", state.clone(), step, vec![]).with_version(step as u64 + 1);
1389            dc.save(&cp).await.unwrap();
1390        }
1391
1392        // Load latest (step 4) — should reconstruct through all deltas
1393        let loaded = dc.load("t1").await.unwrap().unwrap();
1394        assert_eq!(loaded.state, states[4]);
1395        assert_eq!(loaded.step, 4);
1396    }
1397
1398    #[tokio::test]
1399    async fn delta_checkpointer_delete_delegates() {
1400        let inner = MemoryCheckpointer::new();
1401        let dc = DeltaCheckpointer::new(inner, DeltaConfig::default());
1402
1403        let state = make_state(&[("x", 1)]);
1404        let cp = Checkpoint::new("t1", state, 0, vec![]).with_version(1);
1405        dc.save(&cp).await.unwrap();
1406
1407        dc.delete("t1").await.unwrap();
1408        let loaded = dc.load("t1").await.unwrap();
1409        assert!(loaded.is_none());
1410    }
1411
1412    #[tokio::test]
1413    async fn delta_checkpointer_handles_key_removal() {
1414        let inner = MemoryCheckpointer::new();
1415        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 10 });
1416
1417        // Step 0: full with keys a, b, c
1418        let state0 = make_state(&[("a", 1), ("b", 2), ("c", 3)]);
1419        let cp0 = Checkpoint::new("t1", state0, 0, vec![]).with_version(1);
1420        dc.save(&cp0).await.unwrap();
1421
1422        // Step 1: remove key b, modify c
1423        let state1 = make_state(&[("a", 1), ("c", 99)]);
1424        let cp1 = Checkpoint::new("t1", state1.clone(), 1, vec![]).with_version(2);
1425        dc.save(&cp1).await.unwrap();
1426
1427        // Load should reconstruct correctly
1428        let loaded = dc.load("t1").await.unwrap().unwrap();
1429        assert_eq!(loaded.state, state1);
1430        assert!(!loaded.state.contains_key("b"));
1431    }
1432
1433    #[tokio::test]
1434    async fn delta_checkpointer_reconstruction_across_full_snapshot_boundary() {
1435        let inner = MemoryCheckpointer::new();
1436        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 3 });
1437
1438        // Steps 0-5: full at 0, 3; deltas at 1, 2, 4, 5
1439        let states: Vec<State> = (0..6).map(|i| make_state(&[("val", i * 100)])).collect();
1440
1441        for (step, state) in states.iter().enumerate() {
1442            let cp =
1443                Checkpoint::new("t1", state.clone(), step, vec![]).with_version(step as u64 + 1);
1444            dc.save(&cp).await.unwrap();
1445        }
1446
1447        // Load latest (step 5) — should reconstruct from full at step 3 + deltas 4, 5
1448        let loaded = dc.load("t1").await.unwrap().unwrap();
1449        assert_eq!(loaded.state, states[5]);
1450    }
1451
1452    #[tokio::test]
1453    async fn delta_checkpointer_prune_keeps_an_open_pause_and_its_base() {
1454        let dc = DeltaCheckpointer::new(
1455            MemoryCheckpointer::new(),
1456            DeltaConfig { full_snapshot_interval: 3 },
1457        );
1458        let mut saved = Vec::new();
1459        for step in 0..7usize {
1460            let mut state = State::new();
1461            state.insert("count".to_string(), serde_json::json!(step));
1462            let mut checkpoint =
1463                Checkpoint::new("t1", state, step, vec![]).with_version(step as u64 + 1);
1464            if step == 6 {
1465                // The newest lists the pause at step 4, a delta over the snapshot at step 3.
1466                let pause: &Checkpoint = &saved[4];
1467                checkpoint = checkpoint.with_metadata(
1468                    crate::record::OPEN_PAUSES_METADATA_KEY,
1469                    serde_json::json!([pause.checkpoint_id]),
1470                );
1471            }
1472            dc.save(&checkpoint).await.unwrap();
1473            saved.push(checkpoint);
1474        }
1475
1476        let removed =
1477            dc.prune("t1", &crate::checkpoint::RetentionPolicy::keep_last(1)).await.unwrap();
1478        assert_eq!(removed, 3, "everything before the pause's base snapshot goes");
1479        let pause = dc.load_by_id(&saved[4].checkpoint_id).await.unwrap().unwrap();
1480        assert_eq!(pause.state, saved[4].state, "the open pause still reconstructs");
1481    }
1482}