adk-graph 0.9.0

Graph-based workflow orchestration for ADK-Rust agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
//! Delta checkpoint compression for graph state.
//!
//! This module provides incremental (delta-based) checkpoint storage, reducing
//! storage growth from quadratic (full snapshots every step) to linear (only
//! differences between consecutive states are persisted).
//!
//! # Architecture
//!
//! The core abstraction is the [`Diff`] trait, which defines how to compute and
//! apply incremental deltas for a given state type. [`DeltaConfig`] controls how
//! often full snapshots are stored (bounding reconstruction cost), and
//! [`CheckpointType`] distinguishes between full snapshots and delta records.
//!
//! # Example
//!
//! ```rust
//! use adk_graph::delta::{Diff, DeltaConfig, CheckpointType};
//!
//! // DeltaConfig with default full_snapshot_interval of 10
//! let config = DeltaConfig::default();
//! assert_eq!(config.full_snapshot_interval, 10);
//!
//! // CheckpointType distinguishes full vs delta records
//! let full = CheckpointType::Full;
//! let delta = CheckpointType::Delta {
//!     base_checkpoint_id: "ckpt-001".to_string(),
//! };
//! ```

use std::collections::HashMap;

use async_trait::async_trait;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value;

use crate::checkpoint::Checkpointer;
use crate::error::GraphError;
use crate::state::{Checkpoint, State};

/// Trait for types that can compute and apply incremental diffs.
///
/// Implementors define an associated `Delta` type representing the difference
/// between two instances. The trait guarantees a round-trip property:
///
/// > For any states `s1` and `s2`, `Diff::apply(&s1, &Diff::diff(&s1, &s2)) == s2`.
///
/// # Example
///
/// ```rust,ignore
/// use adk_graph::delta::Diff;
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Clone, Debug, PartialEq)]
/// struct Counter(u64);
///
/// #[derive(Clone, Debug, Serialize, Deserialize)]
/// struct CounterDelta(i64);
///
/// impl Diff for Counter {
///     type Delta = CounterDelta;
///
///     fn diff(old: &Self, new: &Self) -> Self::Delta {
///         CounterDelta(new.0 as i64 - old.0 as i64)
///     }
///
///     fn apply(base: &Self, delta: &Self::Delta) -> Self {
///         Counter((base.0 as i64 + delta.0) as u64)
///     }
/// }
///
/// let s1 = Counter(5);
/// let s2 = Counter(12);
/// let delta = Counter::diff(&s1, &s2);
/// assert_eq!(Counter::apply(&s1, &delta), s2);
/// ```
pub trait Diff: Sized {
    /// The delta representation capturing the difference between two states.
    ///
    /// Must be serializable for checkpoint storage and sendable across async
    /// boundaries.
    type Delta: Clone + Serialize + DeserializeOwned + Send + Sync;

    /// Compute the delta that transforms `old` into `new`.
    ///
    /// The returned delta, when applied to `old` via [`Diff::apply`], must
    /// reproduce `new` exactly.
    fn diff(old: &Self, new: &Self) -> Self::Delta;

    /// Apply a delta to a base state, producing the resulting state.
    ///
    /// This is the inverse of [`Diff::diff`]: applying the delta produced by
    /// `diff(old, new)` to `old` yields `new`.
    fn apply(base: &Self, delta: &Self::Delta) -> Self;
}

/// Configuration for delta-based checkpoint compression.
///
/// Controls how frequently full snapshots are stored among the stream of delta
/// records. A full snapshot is stored every `full_snapshot_interval` steps,
/// bounding the number of deltas that must be replayed during reconstruction.
///
/// # Example
///
/// ```rust
/// use adk_graph::delta::DeltaConfig;
///
/// // Default: full snapshot every 10 steps
/// let config = DeltaConfig::default();
/// assert_eq!(config.full_snapshot_interval, 10);
///
/// // Custom interval
/// let config = DeltaConfig { full_snapshot_interval: 5 };
/// assert_eq!(config.full_snapshot_interval, 5);
/// ```
#[derive(Debug, Clone)]
pub struct DeltaConfig {
    /// Store a full snapshot every N steps.
    ///
    /// At step boundaries divisible by this value, a full state snapshot is
    /// persisted instead of a delta. This bounds reconstruction cost to at most
    /// `full_snapshot_interval - 1` delta applications.
    ///
    /// Default: 10.
    pub full_snapshot_interval: u32,
}

impl Default for DeltaConfig {
    fn default() -> Self {
        Self { full_snapshot_interval: 10 }
    }
}

/// Discriminates between full state snapshots and incremental delta records.
///
/// Each persisted checkpoint is tagged with its type so the loader knows whether
/// to use the payload directly (full) or apply it as a delta on top of a base
/// checkpoint.
///
/// # Example
///
/// ```rust
/// use adk_graph::delta::CheckpointType;
///
/// let full = CheckpointType::Full;
/// assert!(matches!(full, CheckpointType::Full));
///
/// let delta = CheckpointType::Delta {
///     base_checkpoint_id: "ckpt-042".to_string(),
/// };
/// if let CheckpointType::Delta { base_checkpoint_id } = &delta {
///     assert_eq!(base_checkpoint_id, "ckpt-042");
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CheckpointType {
    /// A complete state snapshot — no base required for reconstruction.
    Full,
    /// An incremental delta relative to a base checkpoint.
    Delta {
        /// The identifier of the checkpoint this delta is relative to.
        base_checkpoint_id: String,
    },
}

/// Delta representation for `Vec<Value>`.
///
/// Captures either appended items (when the new vec extends the old one) or a
/// full replacement (when items were removed or modified in the middle).
///
/// # Example
///
/// ```rust
/// use adk_graph::delta::{Diff, VecDelta};
/// use serde_json::{Value, json};
///
/// let old = vec![json!(1), json!(2), json!(3)];
/// let new = vec![json!(1), json!(2), json!(3), json!(4), json!(5)];
///
/// let delta = <Vec<Value> as Diff>::diff(&old, &new);
/// assert!(!delta.full_replacement);
/// assert_eq!(delta.start_index, 3);
/// assert_eq!(delta.items, vec![json!(4), json!(5)]);
///
/// let reconstructed = <Vec<Value> as Diff>::apply(&old, &delta);
/// assert_eq!(reconstructed, new);
/// ```
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct VecDelta {
    /// If true, the delta is a full replacement (for non-append-only changes).
    pub full_replacement: bool,
    /// Start index for appended items (only used when `full_replacement` is false).
    pub start_index: usize,
    /// The items (appended items or full replacement).
    pub items: Vec<Value>,
}

impl Diff for Vec<Value> {
    type Delta = VecDelta;

    /// Compute the delta between two `Vec<Value>` instances.
    ///
    /// If `new` is a strict extension of `old` (i.e., `old` is a prefix of `new`),
    /// the delta captures only the appended items and the start index. Otherwise,
    /// the delta stores the full new vec as a replacement.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_graph::delta::Diff;
    /// use serde_json::{Value, json};
    ///
    /// // Append case
    /// let old = vec![json!("a"), json!("b")];
    /// let new = vec![json!("a"), json!("b"), json!("c")];
    /// let delta = <Vec<Value> as Diff>::diff(&old, &new);
    /// assert!(!delta.full_replacement);
    ///
    /// // Modification case (full replacement)
    /// let old = vec![json!(1), json!(2)];
    /// let new = vec![json!(1), json!(99)];
    /// let delta = <Vec<Value> as Diff>::diff(&old, &new);
    /// assert!(delta.full_replacement);
    /// ```
    fn diff(old: &Self, new: &Self) -> Self::Delta {
        // Check if new is a strict extension of old (old is a prefix of new)
        if new.len() >= old.len() && old.iter().zip(new.iter()).all(|(a, b)| a == b) {
            VecDelta {
                full_replacement: false,
                start_index: old.len(),
                items: new[old.len()..].to_vec(),
            }
        } else {
            // Items were removed or modified — store full replacement
            VecDelta { full_replacement: true, start_index: 0, items: new.clone() }
        }
    }

    /// Apply a delta to a base `Vec<Value>`, producing the resulting vec.
    ///
    /// If the delta is a full replacement, the base is ignored and the delta's
    /// items are returned directly. Otherwise, the base is truncated to
    /// `start_index` and the delta's items are appended.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_graph::delta::Diff;
    /// use serde_json::{Value, json};
    ///
    /// let old = vec![json!(1), json!(2)];
    /// let new = vec![json!(1), json!(2), json!(3)];
    /// let delta = <Vec<Value> as Diff>::diff(&old, &new);
    /// assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
    /// ```
    fn apply(base: &Self, delta: &Self::Delta) -> Self {
        if delta.full_replacement {
            delta.items.clone()
        } else {
            let mut result = base[..delta.start_index].to_vec();
            result.extend_from_slice(&delta.items);
            result
        }
    }
}

/// Delta representation for `HashMap<String, Value>`.
///
/// Captures the difference between two maps as three disjoint sets:
/// - `added`: keys present in the new map but not in the old map
/// - `removed`: keys present in the old map but not in the new map
/// - `modified`: keys present in both maps but with different values
///
/// # Example
///
/// ```rust
/// use adk_graph::delta::{Diff, MapDelta};
/// use serde_json::{Value, json};
/// use std::collections::HashMap;
///
/// let old: HashMap<String, Value> = [
///     ("a".to_string(), json!(1)),
///     ("b".to_string(), json!(2)),
/// ].into_iter().collect();
///
/// let new: HashMap<String, Value> = [
///     ("a".to_string(), json!(1)),
///     ("b".to_string(), json!(99)),
///     ("c".to_string(), json!(3)),
/// ].into_iter().collect();
///
/// let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
/// assert_eq!(delta.added.get("c"), Some(&json!(3)));
/// assert_eq!(delta.removed, Vec::<String>::new());
/// assert_eq!(delta.modified.get("b"), Some(&json!(99)));
///
/// let reconstructed = <HashMap<String, Value> as Diff>::apply(&old, &delta);
/// assert_eq!(reconstructed, new);
/// ```
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MapDelta {
    /// Keys present in the new map but not in the old map, with their values.
    pub added: HashMap<String, Value>,
    /// Keys present in the old map but not in the new map.
    pub removed: Vec<String>,
    /// Keys present in both maps but with different values (new values stored).
    pub modified: HashMap<String, Value>,
}

impl Diff for HashMap<String, Value> {
    type Delta = MapDelta;

    /// Compute the delta between two `HashMap<String, Value>` instances.
    ///
    /// Classifies each key into one of three categories:
    /// - **added**: present in `new` but absent from `old`
    /// - **removed**: present in `old` but absent from `new`
    /// - **modified**: present in both but with different values
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_graph::delta::Diff;
    /// use serde_json::{Value, json};
    /// use std::collections::HashMap;
    ///
    /// let old: HashMap<String, Value> = [
    ///     ("x".to_string(), json!("hello")),
    ///     ("y".to_string(), json!(42)),
    /// ].into_iter().collect();
    ///
    /// let new: HashMap<String, Value> = [
    ///     ("x".to_string(), json!("world")),
    ///     ("z".to_string(), json!(true)),
    /// ].into_iter().collect();
    ///
    /// let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
    /// assert!(delta.added.contains_key("z"));
    /// assert!(delta.removed.contains(&"y".to_string()));
    /// assert!(delta.modified.contains_key("x"));
    /// ```
    fn diff(old: &Self, new: &Self) -> Self::Delta {
        let mut added = HashMap::new();
        let mut removed = Vec::new();
        let mut modified = HashMap::new();

        // Find removed and modified keys
        for (key, old_value) in old {
            match new.get(key) {
                None => removed.push(key.clone()),
                Some(new_value) if new_value != old_value => {
                    modified.insert(key.clone(), new_value.clone());
                }
                _ => {} // unchanged
            }
        }

        // Find added keys
        for (key, new_value) in new {
            if !old.contains_key(key) {
                added.insert(key.clone(), new_value.clone());
            }
        }

        MapDelta { added, removed, modified }
    }

    /// Apply a delta to a base `HashMap<String, Value>`, producing the resulting map.
    ///
    /// Operations are applied in order: remove keys, insert added keys, update
    /// modified keys.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_graph::delta::Diff;
    /// use serde_json::{Value, json};
    /// use std::collections::HashMap;
    ///
    /// let old: HashMap<String, Value> = [
    ///     ("a".to_string(), json!(1)),
    ///     ("b".to_string(), json!(2)),
    /// ].into_iter().collect();
    ///
    /// let new: HashMap<String, Value> = [
    ///     ("a".to_string(), json!(1)),
    ///     ("c".to_string(), json!(3)),
    /// ].into_iter().collect();
    ///
    /// let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
    /// assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
    /// ```
    fn apply(base: &Self, delta: &Self::Delta) -> Self {
        let mut result = base.clone();

        // Remove keys
        for key in &delta.removed {
            result.remove(key);
        }

        // Insert added keys
        for (key, value) in &delta.added {
            result.insert(key.clone(), value.clone());
        }

        // Update modified keys
        for (key, value) in &delta.modified {
            result.insert(key.clone(), value.clone());
        }

        result
    }
}

/// An individual edit operation for string diffs.
///
/// Represents one segment of a string diff: text that is unchanged, text that
/// was inserted, or a deletion of characters from the original string.
///
/// # Example
///
/// ```rust
/// use adk_graph::delta::StringOp;
///
/// let ops = vec![
///     StringOp::Equal("hello ".to_string()),
///     StringOp::Delete(5),   // "world" deleted
///     StringOp::Insert("rust".to_string()),
/// ];
/// ```
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum StringOp {
    /// A segment of text that is identical in both old and new strings.
    Equal(String),
    /// Text that was inserted in the new string (not present in old).
    Insert(String),
    /// Number of characters deleted from the old string (not present in new).
    Delete(usize),
}

/// Delta representation for `String`.
///
/// Captures the difference between two strings as a sequence of edit operations.
/// When applied to the old string, these operations reconstruct the new string.
///
/// Uses the `similar` crate (when the `delta-checkpoint` feature is enabled) to
/// compute character-level diffs.
///
/// # Example
///
/// ```rust
/// use adk_graph::delta::{Diff, StringDelta, StringOp};
///
/// let old = "hello world".to_string();
/// let new = "hello rust".to_string();
///
/// let delta = <String as Diff>::diff(&old, &new);
/// let reconstructed = <String as Diff>::apply(&old, &delta);
/// assert_eq!(reconstructed, new);
/// ```
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct StringDelta {
    /// The sequence of edit operations that transform the old string into the new.
    pub ops: Vec<StringOp>,
}

#[cfg(feature = "delta-checkpoint")]
impl Diff for String {
    type Delta = StringDelta;

    /// Compute the delta between two strings using character-level diffing.
    ///
    /// Uses `similar::TextDiff::from_chars()` to compute the minimal set of
    /// edit operations that transform `old` into `new`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_graph::delta::{Diff, StringOp};
    ///
    /// let old = "abcdef".to_string();
    /// let new = "abXYef".to_string();
    ///
    /// let delta = <String as Diff>::diff(&old, &new);
    /// // The delta contains: Equal("ab"), Delete(2), Insert("XY"), Equal("ef")
    /// assert_eq!(<String as Diff>::apply(&old, &delta), new);
    /// ```
    fn diff(old: &Self, new: &Self) -> Self::Delta {
        use similar::{ChangeTag, TextDiff};

        let text_diff = TextDiff::from_chars(old.as_str(), new.as_str());
        let mut ops = Vec::new();

        for change in text_diff.iter_all_changes() {
            let value = change.value();
            match change.tag() {
                ChangeTag::Equal => {
                    // Merge consecutive Equal ops
                    if let Some(StringOp::Equal(s)) = ops.last_mut() {
                        s.push_str(value);
                    } else {
                        ops.push(StringOp::Equal(value.to_string()));
                    }
                }
                ChangeTag::Insert => {
                    // Merge consecutive Insert ops
                    if let Some(StringOp::Insert(s)) = ops.last_mut() {
                        s.push_str(value);
                    } else {
                        ops.push(StringOp::Insert(value.to_string()));
                    }
                }
                ChangeTag::Delete => {
                    // Merge consecutive Delete ops
                    if let Some(StringOp::Delete(count)) = ops.last_mut() {
                        *count += value.chars().count();
                    } else {
                        ops.push(StringOp::Delete(value.chars().count()));
                    }
                }
            }
        }

        StringDelta { ops }
    }

    /// Apply a delta to a base string, producing the resulting string.
    ///
    /// Replays the edit operations in order:
    /// - `Equal(s)`: advance past `s.len()` characters in the base (copy them)
    /// - `Delete(n)`: skip `n` characters in the base
    /// - `Insert(s)`: append `s` to the result
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_graph::delta::Diff;
    ///
    /// let old = "hello world".to_string();
    /// let new = "hello rust".to_string();
    /// let delta = <String as Diff>::diff(&old, &new);
    /// assert_eq!(<String as Diff>::apply(&old, &delta), new);
    /// ```
    fn apply(base: &Self, delta: &Self::Delta) -> Self {
        let mut result = String::new();
        let mut chars = base.chars();

        for op in &delta.ops {
            match op {
                StringOp::Equal(s) => {
                    // Advance past the equal characters in base
                    for _ in 0..s.chars().count() {
                        if let Some(c) = chars.next() {
                            result.push(c);
                        }
                    }
                }
                StringOp::Delete(count) => {
                    // Skip characters in base
                    for _ in 0..*count {
                        chars.next();
                    }
                }
                StringOp::Insert(s) => {
                    // Append inserted text
                    result.push_str(s);
                }
            }
        }

        result
    }
}

// --- Metadata keys used to tag checkpoint records ---

/// Metadata key indicating the checkpoint type (full or delta).
const META_CHECKPOINT_TYPE: &str = "__delta_ckpt_type";
/// Metadata key storing the serialized delta payload for delta checkpoints.
const META_DELTA_PAYLOAD: &str = "__delta_ckpt_payload";
/// Metadata key storing the base checkpoint ID for delta checkpoints.
const META_BASE_CHECKPOINT_ID: &str = "__delta_ckpt_base_id";

/// Metadata value indicating a full snapshot.
const TYPE_FULL: &str = "full";
/// Metadata value indicating a delta record.
const TYPE_DELTA: &str = "delta";

/// Wraps any [`Checkpointer`] with delta compression.
///
/// On save, the `DeltaCheckpointer` stores either a full state snapshot or an
/// incremental delta depending on the step number and the configured
/// [`DeltaConfig::full_snapshot_interval`]. On load, it reconstructs the full
/// state by finding the nearest full snapshot and replaying deltas forward.
///
/// The `DeltaCheckpointer` exposes the same [`Checkpointer`] trait interface,
/// making it a drop-in replacement for any existing checkpointer.
///
/// # Example
///
/// ```rust,ignore
/// use adk_graph::delta::{DeltaCheckpointer, DeltaConfig};
/// use adk_graph::checkpoint::MemoryCheckpointer;
///
/// let inner = MemoryCheckpointer::new();
/// let config = DeltaConfig { full_snapshot_interval: 5 };
/// let checkpointer = DeltaCheckpointer::new(inner, config);
///
/// // Use checkpointer as any other Checkpointer implementation
/// ```
pub struct DeltaCheckpointer<C: Checkpointer> {
    inner: C,
    config: DeltaConfig,
}

impl<C: Checkpointer> DeltaCheckpointer<C> {
    /// Create a new `DeltaCheckpointer` wrapping the given inner checkpointer.
    ///
    /// # Arguments
    ///
    /// * `inner` - The underlying checkpointer used for actual storage.
    /// * `config` - Configuration controlling full snapshot frequency.
    pub fn new(inner: C, config: DeltaConfig) -> Self {
        Self { inner, config }
    }

    /// Returns a reference to the inner checkpointer.
    pub fn inner(&self) -> &C {
        &self.inner
    }

    /// Returns the delta configuration.
    pub fn config(&self) -> &DeltaConfig {
        &self.config
    }

    /// Determine whether a given step should be a full snapshot.
    fn is_full_snapshot_step(&self, step: usize) -> bool {
        step == 0 || (step as u32) % self.config.full_snapshot_interval == 0
    }

    /// Reconstruct full state from a list of checkpoints starting from a full
    /// snapshot and replaying deltas forward up to (and including) the target step.
    fn reconstruct_state(
        checkpoints: &[Checkpoint],
        target_step: usize,
    ) -> crate::error::Result<State> {
        // Find the nearest full snapshot at or before target_step
        let full_snapshot_idx = checkpoints
            .iter()
            .enumerate()
            .rev()
            .find(|(_, cp)| {
                cp.step <= target_step
                    && cp.metadata.get(META_CHECKPOINT_TYPE).and_then(|v| v.as_str())
                        == Some(TYPE_FULL)
            })
            .map(|(idx, _)| idx);

        let full_idx = full_snapshot_idx.ok_or_else(|| {
            GraphError::CheckpointError(
                "No full snapshot found for state reconstruction".to_string(),
            )
        })?;

        let base_checkpoint = &checkpoints[full_idx];
        let mut state = base_checkpoint.state.clone();

        // Replay deltas forward from the full snapshot to the target step
        for cp in &checkpoints[full_idx + 1..] {
            if cp.step > target_step {
                break;
            }

            let cp_type =
                cp.metadata.get(META_CHECKPOINT_TYPE).and_then(|v| v.as_str()).unwrap_or(TYPE_FULL);

            if cp_type == TYPE_DELTA {
                // Extract and apply the delta
                let delta_json = cp.metadata.get(META_DELTA_PAYLOAD).ok_or_else(|| {
                    GraphError::CheckpointError(format!(
                        "Delta checkpoint at step {} missing payload",
                        cp.step
                    ))
                })?;

                let delta: MapDelta = serde_json::from_value(delta_json.clone()).map_err(|e| {
                    GraphError::CheckpointError(format!(
                        "Failed to deserialize delta at step {}: {e}",
                        cp.step
                    ))
                })?;

                state = <HashMap<String, Value> as Diff>::apply(&state, &delta);
            } else {
                // It's a full snapshot — use its state directly
                state = cp.state.clone();
            }
        }

        Ok(state)
    }
}

#[async_trait]
impl<C: Checkpointer> Checkpointer for DeltaCheckpointer<C> {
    /// Save a checkpoint with delta compression.
    ///
    /// If the step is a full snapshot boundary (step == 0 or step %
    /// full_snapshot_interval == 0), the full state is stored. Otherwise, the
    /// delta from the previous checkpoint is computed and stored, with the
    /// checkpoint's `state` field set to an empty map to save space.
    async fn save(&self, checkpoint: &Checkpoint) -> crate::error::Result<String> {
        if self.is_full_snapshot_step(checkpoint.step) {
            // Store full snapshot with type metadata
            let mut full_checkpoint = checkpoint.clone();
            full_checkpoint
                .metadata
                .insert(META_CHECKPOINT_TYPE.to_string(), Value::String(TYPE_FULL.to_string()));
            self.inner.save(&full_checkpoint).await
        } else {
            // Load the previous checkpoint to compute delta
            let all_checkpoints = self.inner.list(&checkpoint.thread_id).await?;

            // Find the previous checkpoint (the one with the highest step < current step)
            let previous = all_checkpoints
                .iter()
                .filter(|cp| cp.step < checkpoint.step)
                .max_by_key(|cp| cp.step);

            match previous {
                Some(prev_cp) => {
                    // Reconstruct the previous state (it might itself be a delta)
                    let prev_state = Self::reconstruct_state(&all_checkpoints, prev_cp.step)?;

                    // Compute delta from previous state to current state
                    let delta =
                        <HashMap<String, Value> as Diff>::diff(&prev_state, &checkpoint.state);

                    // Store the delta checkpoint with minimal state (empty map)
                    let mut delta_checkpoint = checkpoint.clone();
                    delta_checkpoint.state = HashMap::new(); // Don't store full state
                    delta_checkpoint.metadata.insert(
                        META_CHECKPOINT_TYPE.to_string(),
                        Value::String(TYPE_DELTA.to_string()),
                    );
                    delta_checkpoint.metadata.insert(
                        META_BASE_CHECKPOINT_ID.to_string(),
                        Value::String(prev_cp.checkpoint_id.clone()),
                    );
                    delta_checkpoint.metadata.insert(
                        META_DELTA_PAYLOAD.to_string(),
                        serde_json::to_value(&delta).map_err(|e| {
                            GraphError::CheckpointError(format!("Failed to serialize delta: {e}"))
                        })?,
                    );

                    self.inner.save(&delta_checkpoint).await
                }
                None => {
                    // No previous checkpoint found — store as full snapshot
                    let mut full_checkpoint = checkpoint.clone();
                    full_checkpoint.metadata.insert(
                        META_CHECKPOINT_TYPE.to_string(),
                        Value::String(TYPE_FULL.to_string()),
                    );
                    self.inner.save(&full_checkpoint).await
                }
            }
        }
    }

    /// Load the latest checkpoint for a thread, reconstructing full state.
    ///
    /// Finds the latest checkpoint, then reconstructs the full state by
    /// replaying deltas from the nearest full snapshot forward.
    async fn load(&self, thread_id: &str) -> crate::error::Result<Option<Checkpoint>> {
        let all_checkpoints = self.inner.list(thread_id).await?;
        if all_checkpoints.is_empty() {
            return Ok(None);
        }

        // Get the latest checkpoint
        let latest = all_checkpoints.last().unwrap();
        let target_step = latest.step;

        // Reconstruct the full state
        let full_state = Self::reconstruct_state(&all_checkpoints, target_step)?;

        // Return the latest checkpoint with reconstructed state
        let mut result = latest.clone();
        result.state = full_state;
        Ok(Some(result))
    }

    /// Load a specific checkpoint by ID, reconstructing full state.
    ///
    /// Finds the checkpoint by ID, determines its thread, then reconstructs
    /// the full state by replaying deltas from the nearest full snapshot.
    async fn load_by_id(&self, checkpoint_id: &str) -> crate::error::Result<Option<Checkpoint>> {
        let checkpoint = self.inner.load_by_id(checkpoint_id).await?;
        match checkpoint {
            Some(cp) => {
                let all_checkpoints = self.inner.list(&cp.thread_id).await?;
                let full_state = Self::reconstruct_state(&all_checkpoints, cp.step)?;

                let mut result = cp;
                result.state = full_state;
                Ok(Some(result))
            }
            None => Ok(None),
        }
    }

    /// List all checkpoints for a thread.
    ///
    /// Delegates directly to the inner checkpointer. Note that delta
    /// checkpoints in the list will have empty state fields — use
    /// [`load`](Self::load) or [`load_by_id`](Self::load_by_id) to get
    /// reconstructed state.
    async fn list(&self, thread_id: &str) -> crate::error::Result<Vec<Checkpoint>> {
        self.inner.list(thread_id).await
    }

    /// Delete all checkpoints for a thread.
    ///
    /// Delegates directly to the inner checkpointer.
    async fn delete(&self, thread_id: &str) -> crate::error::Result<()> {
        self.inner.delete(thread_id).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn delta_config_default_interval_is_10() {
        let config = DeltaConfig::default();
        assert_eq!(config.full_snapshot_interval, 10);
    }

    #[test]
    fn delta_config_custom_interval() {
        let config = DeltaConfig { full_snapshot_interval: 25 };
        assert_eq!(config.full_snapshot_interval, 25);
    }

    #[test]
    fn checkpoint_type_full_variant() {
        let ct = CheckpointType::Full;
        assert!(matches!(ct, CheckpointType::Full));
    }

    #[test]
    fn checkpoint_type_delta_variant() {
        let ct = CheckpointType::Delta { base_checkpoint_id: "abc-123".to_string() };
        assert!(matches!(ct, CheckpointType::Delta { .. }));
        if let CheckpointType::Delta { base_checkpoint_id } = ct {
            assert_eq!(base_checkpoint_id, "abc-123");
        }
    }

    #[test]
    fn vec_value_diff_append() {
        use serde_json::json;
        let old = vec![json!(1), json!(2), json!(3)];
        let new = vec![json!(1), json!(2), json!(3), json!(4), json!(5)];
        let delta = <Vec<Value> as Diff>::diff(&old, &new);
        assert!(!delta.full_replacement);
        assert_eq!(delta.start_index, 3);
        assert_eq!(delta.items, vec![json!(4), json!(5)]);
        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn vec_value_diff_identical() {
        use serde_json::json;
        let old = vec![json!("a"), json!("b")];
        let new = vec![json!("a"), json!("b")];
        let delta = <Vec<Value> as Diff>::diff(&old, &new);
        assert!(!delta.full_replacement);
        assert_eq!(delta.start_index, 2);
        assert!(delta.items.is_empty());
        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn vec_value_diff_shorter_new() {
        use serde_json::json;
        let old = vec![json!(1), json!(2), json!(3)];
        let new = vec![json!(1)];
        let delta = <Vec<Value> as Diff>::diff(&old, &new);
        assert!(delta.full_replacement);
        assert_eq!(delta.items, vec![json!(1)]);
        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn vec_value_diff_modified_element() {
        use serde_json::json;
        let old = vec![json!(1), json!(2), json!(3)];
        let new = vec![json!(1), json!(99), json!(3)];
        let delta = <Vec<Value> as Diff>::diff(&old, &new);
        assert!(delta.full_replacement);
        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn vec_value_diff_empty_to_items() {
        use serde_json::json;
        let old: Vec<Value> = vec![];
        let new = vec![json!(1), json!(2)];
        let delta = <Vec<Value> as Diff>::diff(&old, &new);
        assert!(!delta.full_replacement);
        assert_eq!(delta.start_index, 0);
        assert_eq!(delta.items, vec![json!(1), json!(2)]);
        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn vec_value_diff_items_to_empty() {
        use serde_json::json;
        let old = vec![json!(1), json!(2)];
        let new: Vec<Value> = vec![];
        let delta = <Vec<Value> as Diff>::diff(&old, &new);
        assert!(delta.full_replacement);
        assert!(delta.items.is_empty());
        assert_eq!(<Vec<Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn map_value_diff_added_keys() {
        use serde_json::json;
        let old: HashMap<String, Value> = [("a".to_string(), json!(1))].into_iter().collect();
        let new: HashMap<String, Value> =
            [("a".to_string(), json!(1)), ("b".to_string(), json!(2)), ("c".to_string(), json!(3))]
                .into_iter()
                .collect();
        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
        assert!(delta.removed.is_empty());
        assert!(delta.modified.is_empty());
        assert_eq!(delta.added.len(), 2);
        assert_eq!(delta.added.get("b"), Some(&json!(2)));
        assert_eq!(delta.added.get("c"), Some(&json!(3)));
        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn map_value_diff_removed_keys() {
        use serde_json::json;
        let old: HashMap<String, Value> =
            [("a".to_string(), json!(1)), ("b".to_string(), json!(2)), ("c".to_string(), json!(3))]
                .into_iter()
                .collect();
        let new: HashMap<String, Value> = [("a".to_string(), json!(1))].into_iter().collect();
        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
        assert!(delta.added.is_empty());
        assert!(delta.modified.is_empty());
        assert_eq!(delta.removed.len(), 2);
        assert!(delta.removed.contains(&"b".to_string()));
        assert!(delta.removed.contains(&"c".to_string()));
        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn map_value_diff_modified_keys() {
        use serde_json::json;
        let old: HashMap<String, Value> =
            [("a".to_string(), json!(1)), ("b".to_string(), json!(2))].into_iter().collect();
        let new: HashMap<String, Value> =
            [("a".to_string(), json!(1)), ("b".to_string(), json!(99))].into_iter().collect();
        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
        assert!(delta.added.is_empty());
        assert!(delta.removed.is_empty());
        assert_eq!(delta.modified.len(), 1);
        assert_eq!(delta.modified.get("b"), Some(&json!(99)));
        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn map_value_diff_mixed_changes() {
        use serde_json::json;
        let old: HashMap<String, Value> =
            [("a".to_string(), json!(1)), ("b".to_string(), json!(2)), ("c".to_string(), json!(3))]
                .into_iter()
                .collect();
        let new: HashMap<String, Value> = [
            ("a".to_string(), json!(1)),
            ("b".to_string(), json!(99)),
            ("d".to_string(), json!(4)),
        ]
        .into_iter()
        .collect();
        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
        assert_eq!(delta.added.len(), 1);
        assert_eq!(delta.added.get("d"), Some(&json!(4)));
        assert_eq!(delta.removed, vec!["c".to_string()]);
        assert_eq!(delta.modified.len(), 1);
        assert_eq!(delta.modified.get("b"), Some(&json!(99)));
        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn map_value_diff_identical() {
        use serde_json::json;
        let old: HashMap<String, Value> =
            [("a".to_string(), json!(1)), ("b".to_string(), json!(2))].into_iter().collect();
        let new = old.clone();
        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
        assert!(delta.added.is_empty());
        assert!(delta.removed.is_empty());
        assert!(delta.modified.is_empty());
        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn map_value_diff_empty_to_populated() {
        use serde_json::json;
        let old: HashMap<String, Value> = HashMap::new();
        let new: HashMap<String, Value> =
            [("a".to_string(), json!(1)), ("b".to_string(), json!(2))].into_iter().collect();
        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
        assert_eq!(delta.added.len(), 2);
        assert!(delta.removed.is_empty());
        assert!(delta.modified.is_empty());
        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn map_value_diff_populated_to_empty() {
        use serde_json::json;
        let old: HashMap<String, Value> =
            [("a".to_string(), json!(1)), ("b".to_string(), json!(2))].into_iter().collect();
        let new: HashMap<String, Value> = HashMap::new();
        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
        assert!(delta.added.is_empty());
        assert_eq!(delta.removed.len(), 2);
        assert!(delta.modified.is_empty());
        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
    }

    #[test]
    fn map_value_diff_nested_values() {
        use serde_json::json;
        let old: HashMap<String, Value> = [
            ("config".to_string(), json!({"host": "localhost", "port": 8080})),
            ("name".to_string(), json!("app")),
        ]
        .into_iter()
        .collect();
        let new: HashMap<String, Value> = [
            ("config".to_string(), json!({"host": "prod.example.com", "port": 443})),
            ("name".to_string(), json!("app")),
            ("version".to_string(), json!("1.0.0")),
        ]
        .into_iter()
        .collect();
        let delta = <HashMap<String, Value> as Diff>::diff(&old, &new);
        assert_eq!(delta.added.get("version"), Some(&json!("1.0.0")));
        assert!(delta.removed.is_empty());
        assert_eq!(
            delta.modified.get("config"),
            Some(&json!({"host": "prod.example.com", "port": 443}))
        );
        assert_eq!(<HashMap<String, Value> as Diff>::apply(&old, &delta), new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_diff_identical() {
        let old = "hello world".to_string();
        let new = "hello world".to_string();
        let delta = <String as Diff>::diff(&old, &new);
        assert_eq!(delta.ops.len(), 1);
        assert_eq!(delta.ops[0], StringOp::Equal("hello world".to_string()));
        assert_eq!(<String as Diff>::apply(&old, &delta), new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_diff_completely_different() {
        let old = "abc".to_string();
        let new = "xyz".to_string();
        let delta = <String as Diff>::diff(&old, &new);
        let reconstructed = <String as Diff>::apply(&old, &delta);
        assert_eq!(reconstructed, new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_diff_suffix_change() {
        let old = "hello world".to_string();
        let new = "hello rust".to_string();
        let delta = <String as Diff>::diff(&old, &new);
        let reconstructed = <String as Diff>::apply(&old, &delta);
        assert_eq!(reconstructed, new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_diff_prefix_change() {
        let old = "hello world".to_string();
        let new = "goodbye world".to_string();
        let delta = <String as Diff>::diff(&old, &new);
        let reconstructed = <String as Diff>::apply(&old, &delta);
        assert_eq!(reconstructed, new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_diff_middle_insertion() {
        let old = "abcdef".to_string();
        let new = "abcXYZdef".to_string();
        let delta = <String as Diff>::diff(&old, &new);
        let reconstructed = <String as Diff>::apply(&old, &delta);
        assert_eq!(reconstructed, new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_diff_middle_deletion() {
        let old = "abcXYZdef".to_string();
        let new = "abcdef".to_string();
        let delta = <String as Diff>::diff(&old, &new);
        let reconstructed = <String as Diff>::apply(&old, &delta);
        assert_eq!(reconstructed, new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_diff_empty_to_content() {
        let old = String::new();
        let new = "hello".to_string();
        let delta = <String as Diff>::diff(&old, &new);
        assert_eq!(delta.ops.len(), 1);
        assert_eq!(delta.ops[0], StringOp::Insert("hello".to_string()));
        assert_eq!(<String as Diff>::apply(&old, &delta), new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_diff_content_to_empty() {
        let old = "hello".to_string();
        let new = String::new();
        let delta = <String as Diff>::diff(&old, &new);
        assert_eq!(delta.ops.len(), 1);
        assert_eq!(delta.ops[0], StringOp::Delete(5));
        assert_eq!(<String as Diff>::apply(&old, &delta), new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_diff_both_empty() {
        let old = String::new();
        let new = String::new();
        let delta = <String as Diff>::diff(&old, &new);
        assert!(delta.ops.is_empty());
        assert_eq!(<String as Diff>::apply(&old, &delta), new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_diff_unicode() {
        let old = "héllo wörld 🌍".to_string();
        let new = "héllo rüst 🦀".to_string();
        let delta = <String as Diff>::diff(&old, &new);
        let reconstructed = <String as Diff>::apply(&old, &delta);
        assert_eq!(reconstructed, new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_diff_multiline() {
        let old = "line1\nline2\nline3".to_string();
        let new = "line1\nmodified\nline3\nline4".to_string();
        let delta = <String as Diff>::diff(&old, &new);
        let reconstructed = <String as Diff>::apply(&old, &delta);
        assert_eq!(reconstructed, new);
    }

    #[cfg(feature = "delta-checkpoint")]
    #[test]
    fn string_delta_serialization_round_trip() {
        let old = "hello world".to_string();
        let new = "hello rust".to_string();
        let delta = <String as Diff>::diff(&old, &new);

        // Serialize and deserialize the delta
        let json = serde_json::to_string(&delta).unwrap();
        let deserialized: StringDelta = serde_json::from_str(&json).unwrap();

        assert_eq!(<String as Diff>::apply(&old, &deserialized), new);
    }

    /// Verify the Diff trait can be implemented and round-trips correctly.
    #[test]
    fn diff_trait_round_trip() {
        #[derive(Clone, Debug, PartialEq)]
        struct TestState(Vec<i32>);

        #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
        struct TestDelta {
            added: Vec<i32>,
            removed_count: usize,
        }

        impl Diff for TestState {
            type Delta = TestDelta;

            fn diff(old: &Self, new: &Self) -> Self::Delta {
                // Simple: assume new extends or truncates old
                if new.0.len() >= old.0.len() {
                    TestDelta { added: new.0[old.0.len()..].to_vec(), removed_count: 0 }
                } else {
                    TestDelta { added: vec![], removed_count: old.0.len() - new.0.len() }
                }
            }

            fn apply(base: &Self, delta: &Self::Delta) -> Self {
                let mut result = base.0.clone();
                if delta.removed_count > 0 {
                    result.truncate(result.len() - delta.removed_count);
                }
                result.extend_from_slice(&delta.added);
                TestState(result)
            }
        }

        let s1 = TestState(vec![1, 2, 3]);
        let s2 = TestState(vec![1, 2, 3, 4, 5]);
        let delta = TestState::diff(&s1, &s2);
        let reconstructed = TestState::apply(&s1, &delta);
        assert_eq!(reconstructed, s2);
    }

    // --- DeltaCheckpointer tests ---

    use crate::checkpoint::MemoryCheckpointer;

    fn make_state(pairs: &[(&str, i64)]) -> State {
        pairs.iter().map(|(k, v)| (k.to_string(), serde_json::json!(v))).collect()
    }

    #[tokio::test]
    async fn delta_checkpointer_first_save_is_full() {
        let inner = MemoryCheckpointer::new();
        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 5 });

        let state = make_state(&[("x", 1)]);
        let cp = Checkpoint::new("t1", state.clone(), 0, vec![]);
        dc.save(&cp).await.unwrap();

        // Load should return the full state
        let loaded = dc.load("t1").await.unwrap().unwrap();
        assert_eq!(loaded.state, state);
        assert_eq!(
            loaded.metadata.get(META_CHECKPOINT_TYPE).and_then(|v| v.as_str()),
            Some(TYPE_FULL)
        );
    }

    #[tokio::test]
    async fn delta_checkpointer_stores_delta_between_full_snapshots() {
        let inner = MemoryCheckpointer::new();
        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 5 });

        // Step 0: full snapshot
        let state0 = make_state(&[("x", 1), ("y", 2)]);
        let cp0 = Checkpoint::new("t1", state0, 0, vec![]);
        dc.save(&cp0).await.unwrap();

        // Step 1: should be delta
        let state1 = make_state(&[("x", 1), ("y", 3), ("z", 4)]);
        let cp1 = Checkpoint::new("t1", state1.clone(), 1, vec![]);
        dc.save(&cp1).await.unwrap();

        // Load should reconstruct the full state at step 1
        let loaded = dc.load("t1").await.unwrap().unwrap();
        assert_eq!(loaded.state, state1);
        assert_eq!(loaded.step, 1);
    }

    #[tokio::test]
    async fn delta_checkpointer_full_snapshot_at_interval() {
        let inner = MemoryCheckpointer::new();
        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 3 });

        // Steps 0, 1, 2, 3
        for step in 0..=3 {
            let state = make_state(&[("counter", step as i64)]);
            let cp = Checkpoint::new("t1", state, step, vec![]);
            dc.save(&cp).await.unwrap();
        }

        // Step 3 should be a full snapshot (3 % 3 == 0)
        let all = dc.list("t1").await.unwrap();
        let step3 = all.iter().find(|cp| cp.step == 3).unwrap();
        assert_eq!(
            step3.metadata.get(META_CHECKPOINT_TYPE).and_then(|v| v.as_str()),
            Some(TYPE_FULL)
        );

        // Step 1 should be a delta
        let step1 = all.iter().find(|cp| cp.step == 1).unwrap();
        assert_eq!(
            step1.metadata.get(META_CHECKPOINT_TYPE).and_then(|v| v.as_str()),
            Some(TYPE_DELTA)
        );
    }

    #[tokio::test]
    async fn delta_checkpointer_load_by_id_reconstructs_state() {
        let inner = MemoryCheckpointer::new();
        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 10 });

        // Step 0: full
        let state0 = make_state(&[("a", 1)]);
        let cp0 = Checkpoint::new("t1", state0, 0, vec![]);
        dc.save(&cp0).await.unwrap();

        // Step 1: delta
        let state1 = make_state(&[("a", 1), ("b", 2)]);
        let cp1 = Checkpoint::new("t1", state1.clone(), 1, vec![]);
        let id1 = dc.save(&cp1).await.unwrap();

        // Step 2: delta
        let state2 = make_state(&[("a", 1), ("b", 2), ("c", 3)]);
        let cp2 = Checkpoint::new("t1", state2.clone(), 2, vec![]);
        let id2 = dc.save(&cp2).await.unwrap();

        // Load by ID for step 1
        let loaded1 = dc.load_by_id(&id1).await.unwrap().unwrap();
        assert_eq!(loaded1.state, state1);

        // Load by ID for step 2
        let loaded2 = dc.load_by_id(&id2).await.unwrap().unwrap();
        assert_eq!(loaded2.state, state2);
    }

    #[tokio::test]
    async fn delta_checkpointer_multiple_deltas_between_snapshots() {
        let inner = MemoryCheckpointer::new();
        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 5 });

        // Create 5 checkpoints (step 0 = full, steps 1-4 = delta)
        let states: Vec<State> =
            (0..5).map(|i| make_state(&[("step", i as i64), ("data", i * 10)])).collect();

        for (step, state) in states.iter().enumerate() {
            let cp = Checkpoint::new("t1", state.clone(), step, vec![]);
            dc.save(&cp).await.unwrap();
        }

        // Load latest (step 4) — should reconstruct through all deltas
        let loaded = dc.load("t1").await.unwrap().unwrap();
        assert_eq!(loaded.state, states[4]);
        assert_eq!(loaded.step, 4);
    }

    #[tokio::test]
    async fn delta_checkpointer_delete_delegates() {
        let inner = MemoryCheckpointer::new();
        let dc = DeltaCheckpointer::new(inner, DeltaConfig::default());

        let state = make_state(&[("x", 1)]);
        let cp = Checkpoint::new("t1", state, 0, vec![]);
        dc.save(&cp).await.unwrap();

        dc.delete("t1").await.unwrap();
        let loaded = dc.load("t1").await.unwrap();
        assert!(loaded.is_none());
    }

    #[tokio::test]
    async fn delta_checkpointer_handles_key_removal() {
        let inner = MemoryCheckpointer::new();
        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 10 });

        // Step 0: full with keys a, b, c
        let state0 = make_state(&[("a", 1), ("b", 2), ("c", 3)]);
        let cp0 = Checkpoint::new("t1", state0, 0, vec![]);
        dc.save(&cp0).await.unwrap();

        // Step 1: remove key b, modify c
        let state1 = make_state(&[("a", 1), ("c", 99)]);
        let cp1 = Checkpoint::new("t1", state1.clone(), 1, vec![]);
        dc.save(&cp1).await.unwrap();

        // Load should reconstruct correctly
        let loaded = dc.load("t1").await.unwrap().unwrap();
        assert_eq!(loaded.state, state1);
        assert!(!loaded.state.contains_key("b"));
    }

    #[tokio::test]
    async fn delta_checkpointer_reconstruction_across_full_snapshot_boundary() {
        let inner = MemoryCheckpointer::new();
        let dc = DeltaCheckpointer::new(inner, DeltaConfig { full_snapshot_interval: 3 });

        // Steps 0-5: full at 0, 3; deltas at 1, 2, 4, 5
        let states: Vec<State> = (0..6).map(|i| make_state(&[("val", i * 100)])).collect();

        for (step, state) in states.iter().enumerate() {
            let cp = Checkpoint::new("t1", state.clone(), step, vec![]);
            dc.save(&cp).await.unwrap();
        }

        // Load latest (step 5) — should reconstruct from full at step 3 + deltas 4, 5
        let loaded = dc.load("t1").await.unwrap().unwrap();
        assert_eq!(loaded.state, states[5]);
    }
}