dagrs 0.8.0

Dagrs follows the concept of Flow-based Programming and is suitable for the execution of multiple tasks with graph-like dependencies. Dagrs has the characteristics of high performance and asynchronous execution. It provides users with a convenient programming interface.
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
//! Tests for Checkpoint mechanism (REQ-002)
//!
//! This module tests the checkpoint system for state persistence and recovery.
//! Key features tested:
//! - Checkpoint creation and storage
//! - Checkpoint loading and restoration
//! - Resuming execution from checkpoint
//! - Automatic checkpointing configuration
//! - Memory and file-based checkpoint stores

use async_trait::async_trait;
use dagrs::graph::event::GraphEvent;
use dagrs::node::action::Action;
use dagrs::node::default_node::DefaultNode;
use dagrs::{
    Checkpoint, CheckpointConfig, CheckpointStore, EnvVar, Graph, InChannels,
    MemoryCheckpointStore, Node, NodeTable, OutChannels, Output,
};
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// Action that counts executions
#[derive(Clone)]
struct CounterAction {
    count: Arc<Mutex<usize>>,
}

#[async_trait]
impl Action for CounterAction {
    async fn run(&self, _: &mut InChannels, _: &mut OutChannels, _: Arc<EnvVar>) -> Output {
        let mut c = self.count.lock().unwrap();
        *c += 1;
        Output::new(*c)
    }
}

/// Action that sleeps for a short duration (simulating long-running task)
#[derive(Clone)]
struct SlowAction {
    name: String,
    executed: Arc<Mutex<Vec<String>>>,
}

#[async_trait]
impl Action for SlowAction {
    async fn run(&self, _: &mut InChannels, _: &mut OutChannels, _: Arc<EnvVar>) -> Output {
        tokio::time::sleep(Duration::from_millis(10)).await;
        self.executed.lock().unwrap().push(self.name.clone());
        Output::empty()
    }
}

#[tokio::test]
async fn test_checkpoint_store_configuration() {
    let mut graph = Graph::new();
    let store = MemoryCheckpointStore::new();

    // Configure checkpoint store
    graph.set_checkpoint_store(Box::new(store));

    // Configure checkpoint settings
    let config = CheckpointConfig::enabled()
        .with_node_interval(5)
        .with_max_checkpoints(3);
    graph.set_checkpoint_config(config);

    // Configuration is set - verified through subsequent operations
    // (direct field access is private, which is correct encapsulation)
}

#[tokio::test]
async fn test_manual_checkpoint_save_and_load() {
    let mut graph = Graph::new();
    let mut table = NodeTable::new();

    // Set up graph with nodes
    let node_a = DefaultNode::new("A".to_string(), &mut table);
    let node_b = DefaultNode::new("B".to_string(), &mut table);
    let id_a = node_a.id();
    let id_b = node_b.id();

    graph.add_node(node_a);
    graph.add_node(node_b);
    graph.add_edge(id_a, vec![id_b]);

    graph.set_checkpoint_store(Box::new(MemoryCheckpointStore::new()));

    // Run the graph first to initialize it
    graph.async_start().await.unwrap();

    // Reset and try to list checkpoints (should work if store is configured)
    let checkpoints = graph.list_checkpoints().await.unwrap();
    // Initially empty since we didn't enable auto-checkpoint
    assert!(checkpoints.is_empty());
}

#[tokio::test]
async fn test_checkpoint_list_and_delete() {
    let store = MemoryCheckpointStore::new();

    // Create multiple checkpoints
    let cp1 = Checkpoint::with_id("test_1", 1, 0);
    let cp2 = Checkpoint::with_id("test_2", 2, 1);
    let cp3 = Checkpoint::with_id("test_3", 3, 2);

    store.save(&cp1).await.unwrap();
    store.save(&cp2).await.unwrap();
    store.save(&cp3).await.unwrap();

    // List checkpoints
    let ids = store.list().await.unwrap();
    assert_eq!(ids.len(), 3);

    // Delete one checkpoint
    store.delete(&"test_2".to_string()).await.unwrap();

    let ids = store.list().await.unwrap();
    assert_eq!(ids.len(), 2);
    assert!(!ids.contains(&"test_2".to_string()));

    // Clear all checkpoints
    store.clear().await.unwrap();
    let ids = store.list().await.unwrap();
    assert_eq!(ids.len(), 0);
}

#[tokio::test]
async fn test_get_latest_checkpoint() {
    let store = MemoryCheckpointStore::new();

    // Create checkpoints with different timestamps
    let mut cp1 = Checkpoint::with_id("old", 1, 0);
    cp1.timestamp = 1000;

    let mut cp2 = Checkpoint::with_id("newer", 2, 1);
    cp2.timestamp = 2000;

    let mut cp3 = Checkpoint::with_id("newest", 3, 2);
    cp3.timestamp = 3000;

    store.save(&cp1).await.unwrap();
    store.save(&cp3).await.unwrap();
    store.save(&cp2).await.unwrap();

    // Get latest should return cp3
    let latest = store.latest().await.unwrap().unwrap();
    assert_eq!(latest.id, "newest");
    assert_eq!(latest.pc, 3);
}

#[tokio::test]
async fn test_checkpoint_with_node_states() {
    use dagrs::NodeState;
    let mut checkpoint = Checkpoint::new(5, 2);

    // Add node states using the new API
    checkpoint.add_node_state(NodeState::completed(1, true));
    checkpoint.add_node_state(NodeState::completed(2, false));
    checkpoint.add_node_state(NodeState::pending(3));

    assert_eq!(checkpoint.node_states.len(), 3);
    assert!(checkpoint.node_states.get(&1).unwrap().success);
    assert!(!checkpoint.node_states.get(&2).unwrap().success);
    assert!(!checkpoint.node_states.get(&3).unwrap().completed);
}

#[tokio::test]
async fn test_checkpoint_metadata() {
    let mut checkpoint = Checkpoint::new(0, 0);

    checkpoint.add_metadata("graph_name", "test_graph");
    checkpoint.add_metadata("version", "1.0");
    checkpoint.add_metadata("environment", "test");

    assert_eq!(
        checkpoint.metadata.get("graph_name"),
        Some(&"test_graph".to_string())
    );
    assert_eq!(checkpoint.metadata.get("version"), Some(&"1.0".to_string()));
    assert_eq!(
        checkpoint.metadata.get("environment"),
        Some(&"test".to_string())
    );
}

#[tokio::test]
async fn test_checkpoint_events() {
    let mut graph = Graph::new();
    let mut table = NodeTable::new();

    let count = Arc::new(Mutex::new(0));
    let node_a = DefaultNode::with_action(
        "A".to_string(),
        CounterAction {
            count: count.clone(),
        },
        &mut table,
    );
    let node_b = DefaultNode::with_action(
        "B".to_string(),
        CounterAction {
            count: count.clone(),
        },
        &mut table,
    );
    let id_a = node_a.id();
    let id_b = node_b.id();

    graph.add_node(node_a);
    graph.add_node(node_b);
    graph.add_edge(id_a, vec![id_b]);

    graph.set_checkpoint_store(Box::new(MemoryCheckpointStore::new()));

    // Enable checkpointing on every node
    let config = CheckpointConfig::enabled()
        .with_node_interval(1)
        .with_max_checkpoints(10);
    graph.set_checkpoint_config(config);

    let mut receiver = graph.subscribe();
    let events = Arc::new(Mutex::new(Vec::new()));
    let events_clone = events.clone();

    // Spawn event collector
    let collector = tokio::spawn(async move {
        let mut collected = Vec::new();
        while let Ok(Ok(event)) =
            tokio::time::timeout(Duration::from_millis(200), receiver.recv()).await
        {
            let is_finished = matches!(event, GraphEvent::GraphFinished);
            collected.push(event);
            if is_finished {
                break;
            }
        }
        collected
    });

    // Run graph
    graph.async_start().await.unwrap();

    tokio::time::sleep(Duration::from_millis(50)).await;

    let collected = collector.await.unwrap();
    *events_clone.lock().unwrap() = collected;

    let events_list = events.lock().unwrap();

    // Should have node events
    let has_node_start = events_list
        .iter()
        .any(|e| matches!(e, GraphEvent::NodeStart { .. }));
    let has_node_success = events_list
        .iter()
        .any(|e| matches!(e, GraphEvent::NodeSuccess { .. }));
    let has_finished = events_list
        .iter()
        .any(|e| matches!(e, GraphEvent::GraphFinished));

    assert!(has_node_start, "Should have NodeStart events");
    assert!(has_node_success, "Should have NodeSuccess events");
    assert!(has_finished, "Should have GraphFinished event");
}

#[tokio::test]
async fn test_checkpoint_config_builder() {
    // Test default config
    let default_config = CheckpointConfig::default();
    assert!(!default_config.enabled);
    assert_eq!(default_config.interval_nodes, Some(10));
    assert!(default_config.on_loop_iteration);
    assert!(default_config.before_conditional);
    assert_eq!(default_config.max_checkpoints, 5);

    // Test builder pattern
    let custom_config = CheckpointConfig::enabled()
        .with_node_interval(20)
        .with_time_interval(300)
        .with_loop_checkpoint(false)
        .with_max_checkpoints(10);

    assert!(custom_config.enabled);
    assert_eq!(custom_config.interval_nodes, Some(20));
    assert_eq!(custom_config.interval_seconds, Some(300));
    assert!(!custom_config.on_loop_iteration);
    assert_eq!(custom_config.max_checkpoints, 10);
}

#[tokio::test]
async fn test_checkpoint_serialization() {
    use dagrs::NodeState;
    let mut checkpoint = Checkpoint::new(5, 3);
    checkpoint.active_nodes.insert(1);
    checkpoint.active_nodes.insert(2);
    checkpoint.active_nodes.insert(3);
    checkpoint.add_metadata("key", "value");
    checkpoint.add_node_state(NodeState::completed(1, true));

    // Serialize to JSON
    let json = serde_json::to_string(&checkpoint).unwrap();
    assert!(json.contains("\"pc\":5"));
    assert!(json.contains("\"loop_count\":3"));

    // Deserialize back
    let restored: Checkpoint = serde_json::from_str(&json).unwrap();
    assert_eq!(restored.pc, 5);
    assert_eq!(restored.loop_count, 3);
    assert_eq!(restored.active_nodes.len(), 3);
    assert_eq!(restored.metadata.get("key"), Some(&"value".to_string()));
}

#[tokio::test]
async fn test_resume_execution_basic() {
    // This test verifies basic resume functionality
    let mut graph = Graph::new();
    let mut table = NodeTable::new();
    let executed = Arc::new(Mutex::new(Vec::new()));

    // Create nodes
    let node_a = DefaultNode::with_action(
        "A".to_string(),
        SlowAction {
            name: "A".to_string(),
            executed: executed.clone(),
        },
        &mut table,
    );
    let node_b = DefaultNode::with_action(
        "B".to_string(),
        SlowAction {
            name: "B".to_string(),
            executed: executed.clone(),
        },
        &mut table,
    );
    let id_a = node_a.id();
    let id_b = node_b.id();

    graph.add_node(node_a);
    graph.add_node(node_b);
    graph.add_edge(id_a, vec![id_b]);

    let store = MemoryCheckpointStore::new();
    graph.set_checkpoint_store(Box::new(store));

    // Run the graph normally
    graph.async_start().await.unwrap();

    let exec_log = executed.lock().unwrap();
    assert!(exec_log.contains(&"A".to_string()), "Node A should execute");
    assert!(exec_log.contains(&"B".to_string()), "Node B should execute");
}
#[tokio::test]
async fn test_file_checkpoint_store_basic() {
    use dagrs::FileCheckpointStore;
    use std::env::temp_dir;

    // Create a temporary directory for test
    let test_dir = temp_dir().join("dagrs_checkpoint_test");
    let store = FileCheckpointStore::new(&test_dir);

    // Clean up any existing checkpoints
    let _ = store.clear().await;

    // Create and save checkpoint
    let mut checkpoint = Checkpoint::with_id("test_file_cp", 5, 2);
    checkpoint.add_metadata("test_key", "test_value");
    checkpoint.active_nodes.insert(1);

    store.save(&checkpoint).await.unwrap();

    // Load checkpoint
    let loaded = store.load(&"test_file_cp".to_string()).await.unwrap();
    assert_eq!(loaded.pc, 5);
    assert_eq!(loaded.loop_count, 2);
    assert!(loaded.active_nodes.contains(&1));

    // List checkpoints
    let ids = store.list().await.unwrap();
    assert!(ids.contains(&"test_file_cp".to_string()));

    // Get latest
    let latest = store.latest().await.unwrap();
    assert!(latest.is_some());

    // Clean up
    store.clear().await.unwrap();
    let _ = std::fs::remove_dir_all(&test_dir);
}

#[tokio::test]
async fn test_file_checkpoint_store_path_traversal_prevention() {
    use dagrs::FileCheckpointStore;
    use std::env::temp_dir;

    let test_dir = temp_dir().join("dagrs_checkpoint_security_test");
    let store = FileCheckpointStore::new(&test_dir);

    // Attempt path traversal attack with ..
    let malicious_checkpoint = Checkpoint::with_id("../../../etc/passwd", 0, 0);
    let result = store.save(&malicious_checkpoint).await;
    assert!(
        result.is_err(),
        "Should reject path traversal attempts with .."
    );

    // Attempt with forward slash
    let malicious_checkpoint2 = Checkpoint::with_id("foo/bar", 0, 0);
    let result2 = store.save(&malicious_checkpoint2).await;
    assert!(result2.is_err(), "Should reject checkpoint IDs with /");

    // Attempt to load with malicious ID
    let result3 = store.load(&"../secret".to_string()).await;
    assert!(result3.is_err(), "Should reject path traversal in load");

    // Clean up
    let _ = std::fs::remove_dir_all(&test_dir);
}

#[tokio::test]
async fn test_checkpoint_id_generation() {
    // Test that auto-generated IDs are safe
    let cp1 = Checkpoint::new(0, 0);
    let cp2 = Checkpoint::new(10, 5);

    // IDs should start with "ckpt_" and not contain path separators
    assert!(cp1.id.starts_with("ckpt_"));
    assert!(cp2.id.starts_with("ckpt_"));
    assert!(!cp1.id.contains('/'));
    assert!(!cp1.id.contains('\\'));
    assert!(!cp1.id.contains(".."));

    // IDs should be unique
    // Note: In very fast execution, timestamps might be the same, but pc differs
    // This is acceptable as the ID format includes both timestamp and pc
}

#[tokio::test]
async fn test_node_state_builder_api() {
    use dagrs::NodeState;

    // Test completed with success
    let state = NodeState::completed(1, true)
        .with_summary("String(hello)")
        .with_output_data(b"\"hello\"".to_vec());

    assert_eq!(state.node_id, 1);
    assert!(state.completed);
    assert!(state.success);
    assert_eq!(state.output_summary, Some("String(hello)".to_string()));
    assert_eq!(state.output_data, Some(b"\"hello\"".to_vec()));

    // Test completed with failure
    let state = NodeState::completed(2, false).with_summary("Error: connection timeout");

    assert_eq!(state.node_id, 2);
    assert!(state.completed);
    assert!(!state.success);
    assert_eq!(
        state.output_summary,
        Some("Error: connection timeout".to_string())
    );

    // Test pending
    let state = NodeState::pending(3);
    assert_eq!(state.node_id, 3);
    assert!(!state.completed);
    assert!(!state.success);
}

#[tokio::test]
async fn test_checkpoint_output_data_serialization() {
    use dagrs::NodeState;

    let mut checkpoint = Checkpoint::new(0, 0);

    // Add node with serialized output
    let output_json = serde_json::to_vec(&"test_output").unwrap();
    let state = NodeState::completed(1, true)
        .with_output_data(output_json.clone())
        .with_summary("String(test_output)");
    checkpoint.add_node_state(state);

    // Serialize and deserialize checkpoint
    let json = serde_json::to_string(&checkpoint).unwrap();
    let restored: Checkpoint = serde_json::from_str(&json).unwrap();

    // Verify output data was preserved
    let restored_state = restored.node_states.get(&1).unwrap();
    assert_eq!(restored_state.output_data, Some(output_json));
    assert_eq!(
        restored_state.output_summary,
        Some("String(test_output)".to_string())
    );

    // Deserialize the output data
    let output: String =
        serde_json::from_slice(restored_state.output_data.as_ref().unwrap()).unwrap();
    assert_eq!(output, "test_output");
}