juncture-checkpoint 0.2.0

Checkpoint persistence for Juncture state machine executions
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
//! In-memory checkpoint storage
//!
//! Thread-safe in-memory implementation of `CheckpointSaver` for development and testing.

use juncture_core::checkpoint::{
    Checkpoint, CheckpointError as CoreCheckpointError, CheckpointFilter, CheckpointMetadata,
    CheckpointSaver, CheckpointTuple, PendingWrite,
};
use juncture_core::config::RunnableConfig;
use juncture_core::info_span;
#[cfg(target_family = "wasm")]
use juncture_core::tracing_wasm::WasmInstrument;
use juncture_tracing::spans::names;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
#[cfg(not(target_family = "wasm"))]
use tracing::Instrument;

use crate::error::CheckpointError;

// Convert crate's CheckpointError to core's CheckpointError
#[allow(dead_code, reason = "conversion trait used internally")]
trait ToCoreCheckpointError<T> {
    fn map_checkpoint(self) -> Result<T, CoreCheckpointError>;
}

impl<T> ToCoreCheckpointError<T> for Result<T, CheckpointError> {
    fn map_checkpoint(self) -> Result<T, CoreCheckpointError> {
        self.map_err(|e| match e {
            CheckpointError::Serialize(msg) | CheckpointError::Serialization(msg) => {
                CoreCheckpointError::Serialize(msg)
            }
            CheckpointError::Deserialize(msg) => CoreCheckpointError::Deserialize(msg),
            CheckpointError::NotFound {
                thread_id,
                checkpoint_id,
            } => CoreCheckpointError::NotFound {
                thread_id,
                checkpoint_id,
            },
            CheckpointError::Storage(msg) | CheckpointError::Database(msg) => {
                CoreCheckpointError::Storage(msg)
            }
            CheckpointError::SchemaMigration { from, to, reason } => {
                CoreCheckpointError::Other(format!("Schema migration: {from} -> {to}: {reason}"))
            }
            CheckpointError::PoolExhausted => {
                CoreCheckpointError::Storage("Connection pool exhausted".into())
            }
        })
    }
}

/// Type alias for storage: `thread_id` -> `checkpoint_ns` -> Vec<CheckpointTuple>
type StorageMap = HashMap<String, HashMap<String, Vec<CheckpointTuple>>>;

/// Type alias for writes: (`thread_id`, `checkpoint_id`, `checkpoint_ns`) -> Vec<PendingWrite>
type WritesMap = HashMap<(String, String, String), Vec<PendingWrite>>;

/// In-memory checkpoint storage
///
/// Thread-safe checkpoint storage using in-memory data structures.
/// Data is lost when the process exits. Suitable for development and testing.
#[derive(Clone, Debug)]
pub struct MemorySaver {
    /// `thread_id` -> `checkpoint_ns` -> Vec<CheckpointTuple> (sorted by `created_at` DESC)
    storage: Arc<RwLock<StorageMap>>,

    /// (`thread_id`, `checkpoint_id`, `checkpoint_ns`) -> Vec<PendingWrite>
    writes: Arc<RwLock<WritesMap>>,

    /// TTL configuration for checkpoint expiration (M04-001)
    ttl_config: Arc<std::sync::RwLock<crate::types::TtlConfig>>,
}

impl MemorySaver {
    /// Create a new in-memory saver
    #[must_use]
    pub fn new() -> Self {
        Self {
            storage: Arc::new(RwLock::new(HashMap::new())),
            writes: Arc::new(RwLock::new(HashMap::new())),
            ttl_config: Arc::new(std::sync::RwLock::new(crate::types::TtlConfig::default())),
        }
    }

    /// Create a new in-memory saver with TTL configuration (M04-001)
    ///
    /// # Arguments
    ///
    /// * `ttl_config` - TTL configuration for automatic checkpoint expiration
    #[must_use]
    pub fn with_ttl_config(mut self, ttl_config: crate::types::TtlConfig) -> Self {
        self.ttl_config = Arc::new(std::sync::RwLock::new(ttl_config));
        self
    }

    /// Get the current TTL configuration
    ///
    /// Returns a clone of the current TTL configuration.
    ///
    /// # Panics
    ///
    /// Panics if the internal `RwLock` is poisoned (indicating a writer thread
    /// panicked while holding the write lock).
    #[must_use]
    pub fn ttl_config(&self) -> crate::types::TtlConfig {
        self.ttl_config.read().unwrap().clone()
    }

    /// Update the TTL configuration (M04-001)
    ///
    /// # Arguments
    ///
    /// * `ttl_config` - New TTL configuration
    ///
    /// # Panics
    ///
    /// Panics if the internal `RwLock` is poisoned (indicating a writer thread
    /// panicked while holding the write lock).
    pub fn set_ttl_config(&self, ttl_config: crate::types::TtlConfig) {
        *self.ttl_config.write().unwrap() = ttl_config;
    }

    /// Perform lazy cleanup of expired checkpoints (M04-001)
    ///
    /// This method implements lazy cleanup as specified in design doc §5.7.
    /// It removes expired checkpoints and enforces `max_checkpoints` limit.
    /// Called automatically by `list()` and `get_tuple()` operations.
    #[allow(
        clippy::significant_drop_tightening,
        reason = "lock scope is already optimized for minimal contention"
    )]
    async fn lazy_cleanup(
        &self,
        thread_id: &str,
        checkpoint_ns: &str,
    ) -> Result<(), CheckpointError> {
        let ttl_config = self.ttl_config.read().unwrap().clone();

        // Reduce lock contention by limiting write lock scope
        let (checkpoint_ids, expired_count) = {
            let mut storage = self.storage.write().await;

            let thread_map = storage
                .entry(thread_id.to_string())
                .or_insert_with(HashMap::new);
            let checkpoints = thread_map
                .entry(checkpoint_ns.to_string())
                .or_insert_with(Vec::new);

            // Remove expired checkpoints (lazy cleanup per design §5.7)
            let original_len = checkpoints.len();
            checkpoints.retain(|tuple| !ttl_config.is_expired(&tuple.checkpoint.created_at));
            let expired_count = original_len - checkpoints.len();

            // Enforce max_checkpoints limit (delete oldest)
            let Some(max) = ttl_config.max_checkpoints else {
                return Ok(());
            };

            if checkpoints.len() > max {
                let excess = checkpoints.len() - max;
                checkpoints.truncate(max);
                tracing::debug!("Deleted {excess} oldest checkpoints (max_checkpoints={max})");
            }

            // Collect checkpoint IDs for writes cleanup
            let checkpoint_ids: std::collections::HashSet<String> = checkpoints
                .iter()
                .map(|t| t.checkpoint.id.clone())
                .collect();

            (checkpoint_ids, expired_count)
        };

        // Clean up writes for deleted checkpoints outside storage lock
        if expired_count > 0 {
            let mut writes = self.writes.write().await;

            // Remove writes for checkpoints that no longer exist
            writes.retain(|(thread, ns, id), _| {
                thread == thread_id && ns == checkpoint_ns && checkpoint_ids.contains(id)
            });
        }

        Ok(())
    }

    /// Get checkpoint namespace string from config, defaulting to empty string
    #[must_use]
    fn get_checkpoint_ns(config: &RunnableConfig) -> String {
        config
            .checkpoint_ns
            .as_ref()
            .map_or_else(String::new, juncture_core::CheckpointNamespace::as_str)
    }

    /// Get thread ID from config, returning error if not set
    fn get_thread_id(config: &RunnableConfig) -> Result<String, CheckpointError> {
        config
            .thread_id
            .clone()
            .ok_or_else(|| CheckpointError::Storage("thread_id is required".into()))
    }

    /// Sort checkpoints by creation time descending
    fn sort_checkpoints(checkpoints: &mut [CheckpointTuple]) {
        checkpoints.sort_by(|a, b| {
            b.checkpoint
                .created_at
                .cmp(&a.checkpoint.created_at)
                .then_with(|| b.checkpoint.id.cmp(&a.checkpoint.id))
        });
    }
}

impl Default for MemorySaver {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait::async_trait]
impl CheckpointSaver for MemorySaver {
    async fn get_tuple(
        &self,
        config: &RunnableConfig,
    ) -> Result<Option<CheckpointTuple>, CoreCheckpointError> {
        let thread_id = Self::get_thread_id(config).map_checkpoint()?;
        let checkpoint_ns = Self::get_checkpoint_ns(config);

        // Perform lazy cleanup before retrieving checkpoint (M04-001)
        Self::lazy_cleanup(self, &thread_id, &checkpoint_ns)
            .await
            .map_checkpoint()?;

        // Clone the checkpoint data we need while holding the lock briefly
        let storage = self.storage.read().await;
        let checkpoint_data = storage
            .get(&thread_id)
            .and_then(|ns| ns.get(&checkpoint_ns))
            .cloned();
        drop(storage);

        let tuple_opt = checkpoint_data.and_then(|checkpoints| {
            config.checkpoint_id.as_ref().map_or_else(
                || checkpoints.first().cloned(),
                |checkpoint_id| {
                    checkpoints
                        .iter()
                        .find(|t| t.checkpoint.id == *checkpoint_id)
                        .cloned()
                },
            )
        });

        // Then, get pending writes if we found a checkpoint
        if let Some(mut tuple) = tuple_opt {
            let checkpoint_id = tuple.checkpoint.id.clone();
            let writes = self.writes.read().await;
            let pending_writes = writes
                .get(&(thread_id, checkpoint_id, checkpoint_ns))
                .cloned()
                .unwrap_or_default();
            drop(writes);

            tuple.pending_writes = pending_writes;
            Ok(Some(tuple))
        } else {
            Ok(None)
        }
    }

    async fn list(
        &self,
        config: &RunnableConfig,
        filter: Option<CheckpointFilter>,
    ) -> Result<Vec<CheckpointTuple>, CoreCheckpointError> {
        let thread_id = Self::get_thread_id(config).map_checkpoint()?;
        let checkpoint_ns = Self::get_checkpoint_ns(config);

        // Perform lazy cleanup before listing checkpoints (M04-001)
        Self::lazy_cleanup(self, &thread_id, &checkpoint_ns)
            .await
            .map_checkpoint()?;

        let namespace = {
            let storage = self.storage.read().await;
            storage
                .get(&thread_id)
                .and_then(|ns| ns.get(&checkpoint_ns))
                .cloned()
        };

        let mut checkpoints = namespace.unwrap_or_default();

        // Apply filters
        if let Some(f) = filter {
            // Filter by source
            if let Some(source) = f.source {
                checkpoints.retain(|t| t.metadata.source == source);
            }

            // Filter by step range
            if let Some(min_step) = f.step_gte {
                checkpoints.retain(|t| t.metadata.step >= min_step);
            }
            if let Some(max_step) = f.step_lte {
                checkpoints.retain(|t| t.metadata.step <= max_step);
            }

            // Filter by checkpoint_id range (before/after)
            if let Some(before_id) = f.before {
                let before_pos = checkpoints
                    .iter()
                    .position(|t| t.checkpoint.id == before_id);
                if let Some(pos) = before_pos {
                    checkpoints = checkpoints.into_iter().take(pos).collect();
                }
            }
            if let Some(after_id) = f.after {
                let after_pos = checkpoints.iter().position(|t| t.checkpoint.id == after_id);
                if let Some(pos) = after_pos {
                    checkpoints = checkpoints.into_iter().skip(pos + 1).collect();
                }
            }

            // Apply limit
            if let Some(limit) = f.limit {
                checkpoints.truncate(limit);
            }
        }

        Ok(checkpoints)
    }

    async fn put(
        &self,
        config: &RunnableConfig,
        checkpoint: Checkpoint,
        metadata: CheckpointMetadata,
    ) -> Result<RunnableConfig, CoreCheckpointError> {
        // Create tracing span for checkpoint put operation
        let span = info_span!(
            target: "juncture",
            names::CHECKPOINT_PUT,
            "juncture.checkpoint.id" = %checkpoint.id,
            "juncture.checkpoint.source" = ?metadata.source,
            "juncture.checkpoint.step" = metadata.step,
        );

        async move {
            let thread_id = Self::get_thread_id(config).map_checkpoint()?;
            let checkpoint_ns = Self::get_checkpoint_ns(config);
            let checkpoint_id = checkpoint.id.clone();
            let source = metadata.source.clone();

            // Create checkpoint tuple
            let tuple = CheckpointTuple {
                config: config.clone(),
                checkpoint,
                metadata,
                pending_writes: Vec::new(),
                parent_config: None,
            };

            // Store checkpoint by cloning, modifying, and replacing
            // This approach avoids holding the write lock for too long
            let mut storage = self.storage.write().await;
            let thread_map = storage
                .entry(thread_id.clone())
                .or_insert_with(HashMap::new);
            let namespace = thread_map
                .entry(checkpoint_ns.clone())
                .or_insert_with(Vec::new);

            namespace.push(tuple);

            // Keep sorted by creation time descending
            Self::sort_checkpoints(namespace);
            drop(storage);

            // Emit metrics for checkpoint write
            tracing::debug!(
                name: "juncture.checkpoint.writes",
                source = ?source,
            );

            // Return updated config with checkpoint_id
            let mut result_config = config.clone();
            result_config.checkpoint_id = Some(checkpoint_id);

            Ok(result_config)
        }
        .instrument(span)
        .await
    }

    async fn put_writes(
        &self,
        config: &RunnableConfig,
        writes: Vec<PendingWrite>,
        task_id: &str,
    ) -> Result<(), CoreCheckpointError> {
        let checkpoint_id_for_span = config.checkpoint_id.clone().unwrap_or_default();

        // Create tracing span for checkpoint put_writes operation
        let span = info_span!(
            target: "juncture",
            "juncture.checkpoint.put_writes",
            "juncture.checkpoint.id" = %checkpoint_id_for_span,
            "juncture.checkpoint.task_id" = %task_id,
            "juncture.checkpoint.writes_count" = writes.len(),
        );

        async move {
            let thread_id = Self::get_thread_id(config).map_checkpoint()?;
            let checkpoint_ns = Self::get_checkpoint_ns(config);
            let checkpoint_id = config
                .checkpoint_id
                .clone()
                .ok_or_else(|| CoreCheckpointError::Storage("checkpoint_id is required".into()))?;

            let key = (thread_id, checkpoint_id, checkpoint_ns);

            // Prepare the writes with task_id set
            let prepared_writes: Vec<PendingWrite> = writes
                .into_iter()
                .map(|mut w| {
                    w.task_id = task_id.to_string();
                    w
                })
                .collect();

            // Insert the prepared writes in a single statement to minimize lock time
            // We chain the operations to avoid storing the lock guard
            self.writes
                .write()
                .await
                .entry(key)
                .or_insert_with(Vec::new)
                .extend(prepared_writes);

            Ok(())
        }
        .instrument(span)
        .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;
    use juncture_core::checkpoint::CheckpointSource;
    use serde_json::json;

    fn create_test_checkpoint(id: &str, _step: i64) -> Checkpoint {
        Checkpoint {
            id: id.to_string(),
            channel_values: json!({}),
            channel_versions: HashMap::new(),
            versions_seen: HashMap::new(),
            pending_tasks: vec![],
            pending_sends: vec![],
            pending_interrupts: vec![],
            schema_version: 1,
            created_at: Utc::now().to_rfc3339(),
            v: 1,
            new_versions: HashMap::new(),
            counters_since_delta_snapshot: HashMap::new(),
        }
    }

    fn create_test_metadata(source: CheckpointSource, step: i64) -> CheckpointMetadata {
        CheckpointMetadata {
            source,
            step,
            writes: HashMap::new(),
            parents: HashMap::new(),
            run_id: "test-run".to_string(),
        }
    }

    fn create_test_config(thread_id: &str) -> RunnableConfig {
        RunnableConfig::default().with_thread_id(thread_id)
    }

    #[tokio::test]
    async fn test_memory_saver_put_get() {
        let saver = MemorySaver::new();
        let config = create_test_config("thread1");
        let checkpoint = create_test_checkpoint("cp1", 0);
        let metadata = create_test_metadata(CheckpointSource::Input, 0);

        let result_config = saver
            .put(&config, checkpoint.clone(), metadata)
            .await
            .unwrap();

        assert_eq!(result_config.checkpoint_id, Some("cp1".to_string()));

        let retrieved = saver.get_tuple(&result_config).await.unwrap().unwrap();
        assert_eq!(retrieved.checkpoint.id, "cp1");
    }

    #[tokio::test]
    async fn test_memory_saver_get_latest() {
        let saver = MemorySaver::new();
        let config = create_test_config("thread1");

        // Add multiple checkpoints
        for i in 0..3 {
            let checkpoint = create_test_checkpoint(&format!("cp{i}"), i);
            let metadata = create_test_metadata(CheckpointSource::Loop, i);
            saver.put(&config, checkpoint, metadata).await.unwrap();
        }

        // Get latest (without checkpoint_id)
        let latest = saver.get_tuple(&config).await.unwrap().unwrap();
        assert_eq!(latest.checkpoint.id, "cp2"); // Last one added
    }

    #[tokio::test]
    async fn test_memory_saver_list() {
        let saver = MemorySaver::new();
        let config = create_test_config("thread1");

        // Add checkpoints
        for i in 0..5 {
            let checkpoint = create_test_checkpoint(&format!("cp{i}"), i);
            let metadata = create_test_metadata(CheckpointSource::Loop, i);
            saver.put(&config, checkpoint, metadata).await.unwrap();
        }

        // List all
        let all = saver.list(&config, None).await.unwrap();
        assert_eq!(all.len(), 5);

        // List with limit
        let limited = saver
            .list(
                &config,
                Some(CheckpointFilter {
                    limit: Some(3),
                    ..Default::default()
                }),
            )
            .await
            .unwrap();
        assert_eq!(limited.len(), 3);

        // List with step filter
        let filtered = saver
            .list(
                &config,
                Some(CheckpointFilter {
                    step_gte: Some(2),
                    ..Default::default()
                }),
            )
            .await
            .unwrap();
        assert_eq!(filtered.len(), 3); // steps 2, 3, 4
    }

    #[tokio::test]
    async fn test_memory_saver_put_writes() {
        let saver = MemorySaver::new();
        let config = create_test_config("thread1");
        let checkpoint = create_test_checkpoint("cp1", 0);
        let metadata = create_test_metadata(CheckpointSource::Input, 0);

        let result_config = saver.put(&config, checkpoint, metadata).await.unwrap();

        // Add writes
        let writes = vec![PendingWrite {
            task_id: String::new(),
            channel: "messages".to_string(),
            value: json!("hello"),
        }];

        saver
            .put_writes(&result_config, writes, "task1")
            .await
            .unwrap();

        // Retrieve with writes
        let tuple = saver.get_tuple(&result_config).await.unwrap().unwrap();
        assert_eq!(tuple.pending_writes.len(), 1);
        assert_eq!(tuple.pending_writes[0].channel, "messages");
        assert_eq!(tuple.pending_writes[0].task_id, "task1");
    }

    #[tokio::test]
    async fn test_memory_saver_namespace_isolation() {
        let saver = MemorySaver::new();

        let config_ns1 = RunnableConfig::default()
            .with_thread_id("thread1")
            .with_checkpoint_ns(juncture_core::checkpoint::CheckpointNamespace::parse("ns1"));
        let config_ns2 = RunnableConfig::default()
            .with_thread_id("thread1")
            .with_checkpoint_ns(juncture_core::checkpoint::CheckpointNamespace::parse("ns2"));

        let checkpoint1 = create_test_checkpoint("cp1", 0);
        let checkpoint2 = create_test_checkpoint("cp2", 0);
        let metadata = create_test_metadata(CheckpointSource::Input, 0);

        saver
            .put(&config_ns1, checkpoint1, metadata.clone())
            .await
            .unwrap();
        saver.put(&config_ns2, checkpoint2, metadata).await.unwrap();

        // Should not find cp1 in ns2
        let result = saver.get_tuple(&config_ns2).await.unwrap().unwrap();
        assert_eq!(result.checkpoint.id, "cp2");
    }

    #[tokio::test]
    async fn test_memory_saver_thread_isolation() {
        let saver = MemorySaver::new();

        let config_t1 = RunnableConfig::default().with_thread_id("thread1");
        let config_t2 = RunnableConfig::default().with_thread_id("thread2");

        let checkpoint1 = create_test_checkpoint("cp1", 0);
        let checkpoint2 = create_test_checkpoint("cp2", 0);
        let metadata = create_test_metadata(CheckpointSource::Input, 0);

        saver
            .put(&config_t1, checkpoint1, metadata.clone())
            .await
            .unwrap();
        saver.put(&config_t2, checkpoint2, metadata).await.unwrap();

        // Each thread should only see its own checkpoints
        let result1 = saver.get_tuple(&config_t1).await.unwrap().unwrap();
        assert_eq!(result1.checkpoint.id, "cp1");

        let result2 = saver.get_tuple(&config_t2).await.unwrap().unwrap();
        assert_eq!(result2.checkpoint.id, "cp2");
    }

    #[tokio::test]
    async fn test_memory_saver_not_found() {
        let saver = MemorySaver::new();
        let config = RunnableConfig::default()
            .with_thread_id("nonexistent")
            .with_checkpoint_id("missing");

        let result = saver.get_tuple(&config).await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_memory_saver_filter_by_source() {
        let saver = MemorySaver::new();
        let config = create_test_config("thread1");

        // Add checkpoints with different sources
        let cp_input = create_test_checkpoint("cp1", 0);
        let meta_input = create_test_metadata(CheckpointSource::Input, 0);
        saver.put(&config, cp_input, meta_input).await.unwrap();

        let cp_loop = create_test_checkpoint("cp2", 1);
        let meta_loop = create_test_metadata(CheckpointSource::Loop, 1);
        saver.put(&config, cp_loop, meta_loop).await.unwrap();

        // Filter by Loop source
        let filtered = saver
            .list(
                &config,
                Some(CheckpointFilter {
                    source: Some(CheckpointSource::Loop),
                    ..Default::default()
                }),
            )
            .await
            .unwrap();

        assert_eq!(filtered.len(), 1);
        assert!(matches!(
            filtered[0].metadata.source,
            CheckpointSource::Loop
        ));
    }

    #[tokio::test]
    async fn test_memory_saver_clone() {
        let saver = MemorySaver::new();
        let cloned = saver.clone();

        let config = create_test_config("thread1");
        let checkpoint = create_test_checkpoint("cp1", 0);
        let metadata = create_test_metadata(CheckpointSource::Input, 0);

        // Use original
        saver
            .put(&config, checkpoint.clone(), metadata.clone())
            .await
            .unwrap();

        // Use cloned - should see same data
        let result = cloned.get_tuple(&config).await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().checkpoint.id, "cp1");
    }

    #[tokio::test]
    async fn test_memory_saver_ttl_expiration() {
        use crate::types::TtlConfig;
        use std::time::Duration;

        let saver = MemorySaver::new().with_ttl_config(TtlConfig {
            default_ttl: Some(Duration::from_millis(100)), // Very short TTL for testing
            sweep_interval: Duration::from_secs(3600),
            max_checkpoints: None,
        });

        let config = create_test_config("thread1");

        // Add checkpoints
        for i in 0..3 {
            let checkpoint = create_test_checkpoint(&format!("cp{i}"), i);
            let metadata = create_test_metadata(CheckpointSource::Loop, i);
            saver.put(&config, checkpoint, metadata).await.unwrap();
        }

        // Should have 3 checkpoints initially
        let list = saver.list(&config, None).await.unwrap();
        assert_eq!(list.len(), 3);

        // Wait for TTL to expire
        tokio::time::sleep(Duration::from_millis(150)).await;

        // Trigger lazy cleanup via get_tuple (M04-001)
        let result = saver.get_tuple(&config).await.unwrap();

        // All checkpoints should be expired and cleaned up
        assert!(result.is_none());

        // List should also be empty after lazy cleanup
        let list = saver.list(&config, None).await.unwrap();
        assert_eq!(list.len(), 0);
    }

    #[tokio::test]
    async fn test_memory_saver_max_checkpoints() {
        use crate::types::TtlConfig;

        let saver = MemorySaver::new().with_ttl_config(TtlConfig {
            default_ttl: None,
            sweep_interval: std::time::Duration::from_secs(3600),
            max_checkpoints: Some(2), // Keep only 2 most recent
        });

        let config = create_test_config("thread1");

        // Add 5 checkpoints
        for i in 0..5 {
            let checkpoint = create_test_checkpoint(&format!("cp{i}"), i);
            let metadata = create_test_metadata(CheckpointSource::Loop, i);
            saver.put(&config, checkpoint, metadata).await.unwrap();
        }

        // Trigger lazy cleanup via list (M04-001)
        let list = saver.list(&config, None).await.unwrap();

        // Should only keep 2 most recent (cp3, cp4)
        assert_eq!(list.len(), 2);
        assert_eq!(list[0].checkpoint.id, "cp4"); // Most recent
        assert_eq!(list[1].checkpoint.id, "cp3"); // Second most recent
    }
}

// Rust guideline compliant 2026-05-23