daimon 0.16.0

A Rust-native AI agent framework
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
//! Distributed checkpoint synchronization across processes.
//!
//! [`CheckpointSync`] wraps two [`Checkpoint`] backends — a fast local
//! store and a shared remote store — and keeps them in sync. Saves
//! write-through to both; loads prefer local with remote fallback.
//!
//! [`CheckpointReplicator`] runs as a background task, periodically
//! pulling new checkpoints from the remote into the local store.
//!
//! ```ignore
//! use daimon::checkpoint::{InMemoryCheckpoint, FileCheckpoint, CheckpointSync};
//!
//! let local = InMemoryCheckpoint::new();
//! let remote = FileCheckpoint::new("/shared/nfs/checkpoints")?;
//! let synced = CheckpointSync::new(local, remote);
//!
//! // Use `synced` as the checkpoint backend — writes go to both stores.
//! let agent = Agent::builder()
//!     .model(model)
//!     .checkpoint(synced)
//!     .build()?;
//! ```

use std::sync::Arc;

use crate::error::Result;

use super::traits::{Checkpoint, ErasedCheckpoint};
use super::types::CheckpointState;

/// Write-through checkpoint that synchronizes a local and remote store.
///
/// - `save` writes to both local and remote (write-through).
/// - `load` checks local first, falls back to remote, and backfills local on miss.
/// - `list_runs` returns the union of both stores' run IDs.
/// - `delete` removes from both stores.
pub struct CheckpointSync {
    local: Arc<dyn ErasedCheckpoint>,
    remote: Arc<dyn ErasedCheckpoint>,
}

impl CheckpointSync {
    /// Creates a new synced checkpoint from a local and remote backend.
    pub fn new<L: Checkpoint + 'static, R: Checkpoint + 'static>(
        local: L,
        remote: R,
    ) -> Self {
        Self {
            local: Arc::new(local),
            remote: Arc::new(remote),
        }
    }

    /// Creates from pre-erased checkpoint backends.
    pub fn from_erased(
        local: Arc<dyn ErasedCheckpoint>,
        remote: Arc<dyn ErasedCheckpoint>,
    ) -> Self {
        Self { local, remote }
    }

    /// Pulls all checkpoints from the remote store into the local store.
    ///
    /// Returns the number of run IDs that were synced (i.e. missing locally).
    pub async fn pull_all(&self) -> Result<usize> {
        let remote_runs = self.remote.list_runs_erased().await?;
        let local_runs = self.local.list_runs_erased().await?;

        let local_set: std::collections::HashSet<&str> =
            local_runs.iter().map(|s| s.as_str()).collect();

        let mut synced = 0;
        for run_id in &remote_runs {
            if !local_set.contains(run_id.as_str()) {
                if let Some(state) = self.remote.load_erased(run_id).await? {
                    self.local.save_erased(&state).await?;
                    synced += 1;
                }
            }
        }

        Ok(synced)
    }

    /// Pushes all checkpoints from the local store to the remote store.
    ///
    /// Returns the number of run IDs that were pushed (i.e. missing remotely).
    pub async fn push_all(&self) -> Result<usize> {
        let local_runs = self.local.list_runs_erased().await?;
        let remote_runs = self.remote.list_runs_erased().await?;

        let remote_set: std::collections::HashSet<&str> =
            remote_runs.iter().map(|s| s.as_str()).collect();

        let mut pushed = 0;
        for run_id in &local_runs {
            if !remote_set.contains(run_id.as_str()) {
                if let Some(state) = self.local.load_erased(run_id).await? {
                    self.remote.save_erased(&state).await?;
                    pushed += 1;
                }
            }
        }

        Ok(pushed)
    }
}

impl Checkpoint for CheckpointSync {
    async fn save(&self, state: &CheckpointState) -> Result<()> {
        self.local.save_erased(state).await?;
        self.remote.save_erased(state).await?;
        Ok(())
    }

    async fn load(&self, run_id: &str) -> Result<Option<CheckpointState>> {
        if let Some(state) = self.local.load_erased(run_id).await? {
            return Ok(Some(state));
        }

        if let Some(state) = self.remote.load_erased(run_id).await? {
            self.local.save_erased(&state).await?;
            return Ok(Some(state));
        }

        Ok(None)
    }

    async fn list_runs(&self) -> Result<Vec<String>> {
        let mut local_runs = self.local.list_runs_erased().await?;
        let remote_runs = self.remote.list_runs_erased().await?;

        let local_set: std::collections::HashSet<String> =
            local_runs.iter().cloned().collect();

        for run_id in remote_runs {
            if !local_set.contains(&run_id) {
                local_runs.push(run_id);
            }
        }

        Ok(local_runs)
    }

    async fn delete(&self, run_id: &str) -> Result<()> {
        self.local.delete_erased(run_id).await?;
        self.remote.delete_erased(run_id).await?;
        Ok(())
    }
}

/// Periodically replicates checkpoints from a remote store to a local store.
///
/// Runs as a background task. Useful for keeping a local in-memory cache
/// warm with checkpoints from a shared persistent store.
///
/// ```ignore
/// use daimon::checkpoint::{InMemoryCheckpoint, FileCheckpoint, CheckpointReplicator};
///
/// let local = Arc::new(InMemoryCheckpoint::new());
/// let remote = Arc::new(FileCheckpoint::new("/shared/checkpoints")?);
///
/// let replicator = CheckpointReplicator::new(
///     local.clone() as Arc<dyn ErasedCheckpoint>,
///     remote.clone() as Arc<dyn ErasedCheckpoint>,
///     std::time::Duration::from_secs(30),
/// );
///
/// // Run in background
/// tokio::spawn(replicator.run());
/// ```
pub struct CheckpointReplicator {
    local: Arc<dyn ErasedCheckpoint>,
    remote: Arc<dyn ErasedCheckpoint>,
    interval: std::time::Duration,
}

impl CheckpointReplicator {
    /// Creates a new replicator.
    ///
    /// * `local` — the local (fast) checkpoint store to populate
    /// * `remote` — the remote (shared) checkpoint store to pull from
    /// * `interval` — how often to poll for new remote checkpoints
    pub fn new(
        local: Arc<dyn ErasedCheckpoint>,
        remote: Arc<dyn ErasedCheckpoint>,
        interval: std::time::Duration,
    ) -> Self {
        Self {
            local,
            remote,
            interval,
        }
    }

    /// Runs the replicator loop indefinitely, pulling new checkpoints
    /// from the remote store at the configured interval.
    pub async fn run(&self) -> Result<()> {
        loop {
            match self.pull_once().await {
                Ok(count) => {
                    if count > 0 {
                        tracing::info!(synced = count, "checkpoint replicator: pulled new runs");
                    }
                }
                Err(e) => {
                    tracing::warn!(error = %e, "checkpoint replicator: pull failed");
                }
            }

            tokio::time::sleep(self.interval).await;
        }
    }

    /// Performs a single pull, returning the number of new runs synced.
    pub async fn pull_once(&self) -> Result<usize> {
        let remote_runs = self.remote.list_runs_erased().await?;
        let local_runs = self.local.list_runs_erased().await?;

        let local_set: std::collections::HashSet<String> =
            local_runs.into_iter().collect();

        let mut synced = 0;
        for run_id in &remote_runs {
            if !local_set.contains(run_id) {
                if let Some(state) = self.remote.load_erased(run_id).await? {
                    self.local.save_erased(&state).await?;
                    synced += 1;
                }
            }
        }

        Ok(synced)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::checkpoint::InMemoryCheckpoint;
    use crate::model::types::Message;

    #[tokio::test]
    async fn test_write_through() {
        let local = InMemoryCheckpoint::new();
        let remote = InMemoryCheckpoint::new();
        let sync = CheckpointSync::new(local, remote);

        let state = CheckpointState::new("run-1", vec![Message::user("hello")], 1);
        sync.save(&state).await.unwrap();

        let loaded = sync.load("run-1").await.unwrap().unwrap();
        assert_eq!(loaded.run_id, "run-1");
        assert_eq!(loaded.messages.len(), 1);
    }

    #[tokio::test]
    async fn test_load_local_first() {
        let local = Arc::new(InMemoryCheckpoint::new());
        let remote = Arc::new(InMemoryCheckpoint::new());

        let local_state = CheckpointState::new("run-1", vec![Message::user("local")], 2);
        local.save(&local_state).await.unwrap();

        let remote_state = CheckpointState::new("run-1", vec![Message::user("remote")], 1);
        remote.save(&remote_state).await.unwrap();

        let sync = CheckpointSync::from_erased(local, remote);
        let loaded = sync.load("run-1").await.unwrap().unwrap();
        assert_eq!(loaded.iteration, 2);
    }

    #[tokio::test]
    async fn test_load_falls_back_to_remote() {
        let local = Arc::new(InMemoryCheckpoint::new());
        let remote = Arc::new(InMemoryCheckpoint::new());

        let state = CheckpointState::new("run-remote", vec![Message::user("hi")], 1);
        remote.save(&state).await.unwrap();

        let sync = CheckpointSync::from_erased(local.clone(), remote);
        let loaded = sync.load("run-remote").await.unwrap().unwrap();
        assert_eq!(loaded.run_id, "run-remote");

        let backfilled = local.load("run-remote").await.unwrap();
        assert!(backfilled.is_some());
    }

    #[tokio::test]
    async fn test_load_returns_none_when_missing() {
        let sync = CheckpointSync::new(InMemoryCheckpoint::new(), InMemoryCheckpoint::new());
        assert!(sync.load("nonexistent").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_list_runs_union() {
        let local = Arc::new(InMemoryCheckpoint::new());
        let remote = Arc::new(InMemoryCheckpoint::new());

        local
            .save(&CheckpointState::new("local-only", vec![], 1))
            .await
            .unwrap();
        remote
            .save(&CheckpointState::new("remote-only", vec![], 1))
            .await
            .unwrap();
        local
            .save(&CheckpointState::new("both", vec![], 1))
            .await
            .unwrap();
        remote
            .save(&CheckpointState::new("both", vec![], 1))
            .await
            .unwrap();

        let sync = CheckpointSync::from_erased(local, remote);
        let mut runs = sync.list_runs().await.unwrap();
        runs.sort();
        assert_eq!(runs, vec!["both", "local-only", "remote-only"]);
    }

    #[tokio::test]
    async fn test_delete_from_both() {
        let sync = CheckpointSync::new(InMemoryCheckpoint::new(), InMemoryCheckpoint::new());

        let state = CheckpointState::new("run-del", vec![], 1);
        sync.save(&state).await.unwrap();
        assert!(sync.load("run-del").await.unwrap().is_some());

        sync.delete("run-del").await.unwrap();
        assert!(sync.load("run-del").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_pull_all() {
        let local = Arc::new(InMemoryCheckpoint::new());
        let remote = Arc::new(InMemoryCheckpoint::new());

        remote
            .save(&CheckpointState::new("r1", vec![], 1))
            .await
            .unwrap();
        remote
            .save(&CheckpointState::new("r2", vec![], 1))
            .await
            .unwrap();
        local
            .save(&CheckpointState::new("r1", vec![], 1))
            .await
            .unwrap();

        let sync = CheckpointSync::from_erased(local.clone(), remote);
        let synced = sync.pull_all().await.unwrap();
        assert_eq!(synced, 1);

        assert!(local.load("r2").await.unwrap().is_some());
    }

    #[tokio::test]
    async fn test_push_all() {
        let local = Arc::new(InMemoryCheckpoint::new());
        let remote = Arc::new(InMemoryCheckpoint::new());

        local
            .save(&CheckpointState::new("l1", vec![], 1))
            .await
            .unwrap();
        local
            .save(&CheckpointState::new("l2", vec![], 1))
            .await
            .unwrap();
        remote
            .save(&CheckpointState::new("l1", vec![], 1))
            .await
            .unwrap();

        let sync = CheckpointSync::from_erased(local, remote.clone());
        let pushed = sync.push_all().await.unwrap();
        assert_eq!(pushed, 1);

        assert!(remote.load("l2").await.unwrap().is_some());
    }

    #[tokio::test]
    async fn test_replicator_pull_once() {
        let local = Arc::new(InMemoryCheckpoint::new());
        let remote = Arc::new(InMemoryCheckpoint::new());

        remote
            .save(&CheckpointState::new("rep-1", vec![], 1))
            .await
            .unwrap();

        let replicator = CheckpointReplicator::new(
            local.clone(),
            remote,
            std::time::Duration::from_secs(60),
        );

        let synced = replicator.pull_once().await.unwrap();
        assert_eq!(synced, 1);

        assert!(local.load("rep-1").await.unwrap().is_some());
    }

    #[tokio::test]
    async fn test_replicator_pull_once_no_new() {
        let local = Arc::new(InMemoryCheckpoint::new());
        let remote = Arc::new(InMemoryCheckpoint::new());

        let state = CheckpointState::new("shared", vec![], 1);
        local.save(&state).await.unwrap();
        remote.save(&state).await.unwrap();

        let replicator = CheckpointReplicator::new(
            local,
            remote,
            std::time::Duration::from_secs(60),
        );

        let synced = replicator.pull_once().await.unwrap();
        assert_eq!(synced, 0);
    }
}