ri-agent-graph 0.2.2

Graph-based agent orchestration for Rust — LangGraph-inspired execution engine with checkpointing, parallel fan-out/fan-in, interrupt/resume, and event streaming
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
use ri_agent_graph::prelude::*;

#[tokio::test]
async fn test_parallel_failure_cancels_delayed_side_effect_branch() {
    let graph = AgentGraph::builder()
        .add_node("start", node!(|_state| async move { Ok(()) }))
        .add_node(
            "fail",
            node!(|_state| async move {
                tokio::task::yield_now().await;
                Err::<(), _>(AgentGraphError::ExecutionError("first failure".into()))
            }),
        )
        .add_node(
            "delayed",
            node!(|state| async move {
                tokio::time::sleep(std::time::Duration::from_secs(5)).await;
                state.set("post_failure_effect", true).await?;
                Ok(())
            }),
        )
        .add_edge("start", "fail")
        .add_edge("start", "delayed")
        .build()
        .unwrap();

    let started = std::time::Instant::now();
    let result = graph.execute("start", AgentState::new()).await;
    assert!(
        matches!(result, Err(AgentGraphError::ExecutionError(message)) if message == "first failure")
    );
    assert!(started.elapsed() < std::time::Duration::from_secs(1));
}

#[tokio::test]
async fn test_fan_out_parallel_execution() {
    // A -> B, A -> C (fan-out), both B and C should execute
    let graph = AgentGraph::builder()
        .add_node(
            "a",
            node!(|state| async move {
                state.set("a_done", true).await?;
                Ok(())
            }),
        )
        .add_node(
            "b",
            node!(|state| async move {
                state.set("b_done", true).await?;
                Ok(())
            }),
        )
        .add_node(
            "c",
            node!(|state| async move {
                state.set("c_done", true).await?;
                Ok(())
            }),
        )
        .add_edge("a", "b")
        .add_edge("a", "c")
        .build()
        .unwrap();

    let state = AgentState::new();
    let result = graph.execute("a", state).await.unwrap();

    assert!(result.get::<bool>("a_done").await.unwrap());
    assert!(result.get::<bool>("b_done").await.unwrap());
    assert!(result.get::<bool>("c_done").await.unwrap());
}

#[tokio::test]
async fn test_fan_out_fan_in() {
    // A -> B, A -> C, B -> D, C -> D
    // D should execute after both B and C
    let graph = AgentGraph::builder()
        .add_node(
            "a",
            node!(|state| async move {
                state.set("value", 10i32).await?;
                Ok(())
            }),
        )
        .add_node(
            "b",
            node!(|state| async move {
                state.set("b_result", "from_b").await?;
                Ok(())
            }),
        )
        .add_node(
            "c",
            node!(|state| async move {
                state.set("c_result", "from_c").await?;
                Ok(())
            }),
        )
        .add_node(
            "d",
            node!(|state| async move {
                // D should see results from both B and C
                let b: String = state.get("b_result").await?;
                let c: String = state.get("c_result").await?;
                state.set("combined", format!("{} + {}", b, c)).await?;
                Ok(())
            }),
        )
        .add_edge("a", "b")
        .add_edge("a", "c")
        .add_edge("b", "d")
        .add_edge("c", "d")
        .build()
        .unwrap();

    let state = AgentState::new();
    let result = graph.execute("a", state).await.unwrap();

    let combined: String = result.get("combined").await.unwrap();
    assert_eq!(combined, "from_b + from_c");
}

#[tokio::test]
async fn test_parallel_execution_actually_parallel() {
    // Verify that parallel branches actually run concurrently
    let graph = AgentGraph::builder()
        .add_node(
            "start",
            node!(|state| async move {
                state.set("started", true).await?;
                Ok(())
            }),
        )
        .add_node(
            "branch_a",
            node!(|state| async move {
                // Simulate some work
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                state.set("a_done", true).await?;
                Ok(())
            }),
        )
        .add_node(
            "branch_b",
            node!(|state| async move {
                // Simulate some work
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                state.set("b_done", true).await?;
                Ok(())
            }),
        )
        .add_edge("start", "branch_a")
        .add_edge("start", "branch_b")
        .build()
        .unwrap();

    let state = AgentState::new();
    let start = std::time::Instant::now();
    let result = graph.execute("start", state).await.unwrap();
    let elapsed = start.elapsed();

    // If truly parallel, both branches should complete in ~50ms, not ~100ms
    assert!(
        elapsed.as_millis() < 100,
        "Parallel branches took too long: {:?}",
        elapsed
    );

    assert!(result.get::<bool>("a_done").await.unwrap());
    assert!(result.get::<bool>("b_done").await.unwrap());
}

#[tokio::test]
async fn test_parallel_state_with_reducer() {
    // Two parallel branches both increment a counter
    // Without a reducer, last-write-wins; with AddReducer, both are added
    let graph = AgentGraph::builder()
        .add_node(
            "start",
            node!(|state| async move {
                state.set("count", 0i64).await?;
                Ok(())
            }),
        )
        .add_node(
            "add_one",
            node!(|state| async move {
                state.set("count", 1i64).await?;
                Ok(())
            }),
        )
        .add_node(
            "add_two",
            node!(|state| async move {
                state.set("count", 2i64).await?;
                Ok(())
            }),
        )
        .add_edge("start", "add_one")
        .add_edge("start", "add_two")
        .with_reducer("count", AddReducer)
        .build()
        .unwrap();

    let state = AgentState::new();
    let result = graph.execute("start", state).await.unwrap();

    // With AddReducer: 0 (snapshot) + 1 (add_one diff) + 2 (add_two diff) = 3
    let count: f64 = result.get("count").await.unwrap();
    assert_eq!(count, 3.0);
}

#[tokio::test]
async fn test_parallel_state_with_append_reducer() {
    let graph = AgentGraph::builder()
        .add_node(
            "start",
            node!(|state| async move {
                state.set("items", Vec::<String>::new()).await?;
                Ok(())
            }),
        )
        .add_node(
            "add_fruits",
            node!(|state| async move {
                state
                    .set("items", vec!["apple".to_string(), "banana".to_string()])
                    .await?;
                Ok(())
            }),
        )
        .add_node(
            "add_vegs",
            node!(|state| async move {
                state
                    .set("items", vec!["carrot".to_string(), "daikon".to_string()])
                    .await?;
                Ok(())
            }),
        )
        .add_edge("start", "add_fruits")
        .add_edge("start", "add_vegs")
        .with_reducer("items", AppendReducer)
        .build()
        .unwrap();

    let state = AgentState::new();
    let result = graph.execute("start", state).await.unwrap();

    let items: Vec<String> = result.get("items").await.unwrap();
    // Both branches should have their items appended
    assert_eq!(items.len(), 4);
    assert!(items.contains(&"apple".to_string()));
    assert!(items.contains(&"banana".to_string()));
    assert!(items.contains(&"carrot".to_string()));
    assert!(items.contains(&"daikon".to_string()));
}

#[tokio::test]
async fn test_start_end_constants() {
    let graph = AgentGraph::builder()
        .add_node(
            "step1",
            node!(|state| async move {
                state.set("step1", true).await?;
                Ok(())
            }),
        )
        .add_node(
            "step2",
            node!(|state| async move {
                state.set("step2", true).await?;
                Ok(())
            }),
        )
        .set_entry_point("step1")
        .add_edge("step1", "step2")
        .set_finish_point("step2")
        .build()
        .unwrap();

    let state = AgentState::new();
    let result = graph.execute(START, state).await.unwrap();

    assert!(result.get::<bool>("step1").await.unwrap());
    assert!(result.get::<bool>("step2").await.unwrap());
}

#[tokio::test]
async fn test_command_goto() {
    let graph = AgentGraph::builder()
        .add_node(
            "a",
            node!(|state| async move {
                state.set("visited_a", true).await?;
                // Use command to skip to 'c', bypassing normal edges
                Ok(NodeOutput::goto("c"))
            }),
        )
        .add_node(
            "b",
            node!(|state| async move {
                state.set("visited_b", true).await?;
                Ok(())
            }),
        )
        .add_node(
            "c",
            node!(|state| async move {
                state.set("visited_c", true).await?;
                Ok(())
            }),
        )
        .add_edge("a", "b") // Normal edge would go to b
        .build()
        .unwrap();

    let state = AgentState::new();
    let result = graph.execute("a", state).await.unwrap();

    assert!(result.get::<bool>("visited_a").await.unwrap());
    // b should NOT have been visited (command overrides edge)
    assert!(result.get_opt::<bool>("visited_b").await.unwrap().is_none());
    assert!(result.get::<bool>("visited_c").await.unwrap());
}

#[tokio::test]
async fn test_command_end() {
    let graph = AgentGraph::builder()
        .add_node(
            "a",
            node!(|state| async move {
                state.set("visited_a", true).await?;
                Ok(NodeOutput::end())
            }),
        )
        .add_node(
            "b",
            node!(|state| async move {
                state.set("visited_b", true).await?;
                Ok(())
            }),
        )
        .add_edge("a", "b")
        .build()
        .unwrap();

    let state = AgentState::new();
    let result = graph.execute("a", state).await.unwrap();

    assert!(result.get::<bool>("visited_a").await.unwrap());
    assert!(result.get_opt::<bool>("visited_b").await.unwrap().is_none());
}

#[tokio::test]
async fn test_config_access_in_node() {
    let graph = AgentGraph::builder()
        .add_node(
            "read_config",
            node!(|state, config| async move {
                if let Some(thread_id) = &config.thread_id {
                    state.set("thread_id", thread_id.clone()).await?;
                }
                state
                    .set("recursion_limit", config.recursion_limit as i64)
                    .await?;
                Ok(())
            }),
        )
        .build()
        .unwrap();

    let state = AgentState::new();
    let config = GraphConfig::new()
        .with_thread_id("test-thread-42")
        .with_recursion_limit(50);
    let result = graph
        .execute_with_config("read_config", state, config)
        .await
        .unwrap();

    let thread_id: String = result.get("thread_id").await.unwrap();
    assert_eq!(thread_id, "test-thread-42");

    let limit: i64 = result.get("recursion_limit").await.unwrap();
    assert_eq!(limit, 50);
}

#[tokio::test]
async fn test_conditional_fan_out() {
    // Router returns multiple nodes for fan-out
    let graph = AgentGraph::builder()
        .add_node(
            "start",
            node!(|state| async move {
                state.set("started", true).await?;
                Ok(())
            }),
        )
        .add_node(
            "branch_a",
            node!(|state| async move {
                state.set("a_done", true).await?;
                Ok(())
            }),
        )
        .add_node(
            "branch_b",
            node!(|state| async move {
                state.set("b_done", true).await?;
                Ok(())
            }),
        )
        .add_conditional_edge(
            "start",
            router!(|_state| async move {
                Ok(RouterOutput::FanOut(vec![
                    "branch_a".to_string(),
                    "branch_b".to_string(),
                ]))
            }),
        )
        .build()
        .unwrap();

    let state = AgentState::new();
    let result = graph.execute("start", state).await.unwrap();

    assert!(result.get::<bool>("a_done").await.unwrap());
    assert!(result.get::<bool>("b_done").await.unwrap());
}