pe-graph 0.1.0

Graph execution engine for Potential Expectations — state graphs, Pregel model, ReAct topology, and builder DSL
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
//! Integration tests for the graph execution engine.
//!
//! Tests the full BSP cycle: StateGraph → compile → invoke → verify outcome.

use pe_core::error::PeError;
use pe_core::node::{InterruptRequest, NodeContext, NodeFn, NodeFuture, NodeResult};
use pe_core::state::{State, StateUpdate};
use pe_core::types::{END, START};
use pe_graph::{ExecutionOutcome, GraphConfig, InMemoryCheckpointer, StateGraph};
use serde::{Deserialize, Serialize};
use std::time::Duration;

// ── Test Types ────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct TestState {
    messages: Vec<String>,
    counter: u32,
    thread_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
struct TestUpdate {
    messages: Option<Vec<String>>,
    counter: Option<u32>,
}

impl StateUpdate for TestUpdate {}

impl State for TestState {
    type Update = TestUpdate;
    fn apply(&mut self, update: TestUpdate) {
        if let Some(msgs) = update.messages {
            self.messages.extend(msgs);
        }
        if let Some(c) = update.counter {
            self.counter = c;
        }
    }
}

impl TestState {
    fn new() -> Self {
        Self {
            messages: Vec::new(),
            counter: 0,
            thread_id: "test".into(),
        }
    }
}

// ── Test Nodes ────────────────────────────────────────────────────────

struct AppendNode {
    node_name: &'static str,
    msg: &'static str,
}

impl AppendNode {
    fn new(name: &'static str, msg: &'static str) -> Self {
        Self {
            node_name: name,
            msg,
        }
    }
}

impl NodeFn<TestState> for AppendNode {
    fn call(&self, _state: &TestState, _ctx: &NodeContext) -> NodeFuture<TestUpdate> {
        let msg = self.msg.to_string();
        Box::pin(async move {
            NodeResult::Update(TestUpdate {
                messages: Some(vec![msg]),
                counter: None,
            })
        })
    }
    fn name(&self) -> &str {
        self.node_name
    }
}

struct IncrementNode {
    node_name: &'static str,
}

impl NodeFn<TestState> for IncrementNode {
    fn call(&self, state: &TestState, _ctx: &NodeContext) -> NodeFuture<TestUpdate> {
        let new_val = state.counter + 1;
        Box::pin(async move {
            NodeResult::Update(TestUpdate {
                messages: None,
                counter: Some(new_val),
            })
        })
    }
    fn name(&self) -> &str {
        self.node_name
    }
}

struct InterruptNode;

impl NodeFn<TestState> for InterruptNode {
    fn call(&self, _state: &TestState, _ctx: &NodeContext) -> NodeFuture<TestUpdate> {
        Box::pin(async {
            NodeResult::Interrupt(InterruptRequest {
                reason: "need approval".into(),
                partial_update: None,
                resume_point: "review".into(),
            })
        })
    }
    fn name(&self) -> &str {
        "interrupt"
    }
}

struct ErrorNode;

impl NodeFn<TestState> for ErrorNode {
    fn call(&self, _state: &TestState, _ctx: &NodeContext) -> NodeFuture<TestUpdate> {
        Box::pin(async {
            NodeResult::Error(PeError::Internal {
                details: "node failed".into(),
            })
        })
    }
    fn name(&self) -> &str {
        "error"
    }
}

// ── Tests ─────────────────────────────────────────────────────────────

#[tokio::test]
async fn test_linear_graph_executes_in_order() {
    let graph = StateGraph::new()
        .add_node("a", AppendNode::new("a", "first"))
        .add_node("b", AppendNode::new("b", "second"))
        .add_node("c", AppendNode::new("c", "third"))
        .add_edge(START, "a")
        .add_edge("a", "b")
        .add_edge("b", "c")
        .add_edge("c", END)
        .compile()
        .unwrap();

    let outcome = graph
        .invoke(TestState::new(), GraphConfig::default())
        .await
        .unwrap();

    match outcome {
        ExecutionOutcome::Completed(state) => {
            assert_eq!(state.messages, vec!["first", "second", "third"]);
        }
        _ => panic!("Expected Completed"),
    }
}

#[tokio::test]
async fn test_cycle_hits_recursion_limit() {
    // a → b → a (infinite loop)
    let graph = StateGraph::new()
        .add_node("a", AppendNode::new("a", "ping"))
        .add_node("b", AppendNode::new("b", "pong"))
        .add_edge(START, "a")
        .add_edge("a", "b")
        .add_edge("b", "a")
        .compile()
        .unwrap();

    let config = GraphConfig::default().with_recursion_limit(5);
    let result = graph.invoke(TestState::new(), config).await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(err, PeError::GraphRecursion { limit: 5 }),
        "Expected GraphRecursion, got: {err:?}"
    );
}

#[tokio::test]
async fn test_conditional_edge_routes_correctly() {
    // chat → tools (if counter < 2) or END (if counter >= 2)
    let graph = StateGraph::new()
        .add_node("chat", IncrementNode { node_name: "chat" })
        .add_node("tools", AppendNode::new("tools", "tool_call"))
        .add_edge(START, "chat")
        .add_conditional_edge("chat", |state: &TestState| {
            if state.counter < 2 {
                vec!["tools".into()]
            } else {
                vec![END.into()]
            }
        })
        .add_edge("tools", "chat")
        .compile()
        .unwrap();

    let outcome = graph
        .invoke(TestState::new(), GraphConfig::default())
        .await
        .unwrap();

    match outcome {
        ExecutionOutcome::Completed(state) => {
            // chat runs 3 times (counter: 0→1, 1→2, at 2 → END)
            // tools runs 2 times (when counter was 1 and 2... wait let me trace:
            // Step 1: chat runs (counter 0→1), conditional: 1 < 2 → tools
            // Step 2: tools runs (appends "tool_call"), then edge tools→chat
            // Step 3: chat runs (counter 1→2), conditional: 2 >= 2 → END
            assert_eq!(state.counter, 2);
            assert_eq!(state.messages, vec!["tool_call"]);
        }
        _ => panic!("Expected Completed"),
    }
}

#[tokio::test]
async fn test_parallel_edges_both_execute() {
    // START → a, START → b (both run in same superstep)
    let graph = StateGraph::new()
        .add_node("a", AppendNode::new("a", "from_a"))
        .add_node("b", AppendNode::new("b", "from_b"))
        .add_edge(START, "a")
        .add_edge(START, "b")
        .add_edge("a", END)
        .add_edge("b", END)
        .compile()
        .unwrap();

    let outcome = graph
        .invoke(TestState::new(), GraphConfig::default())
        .await
        .unwrap();

    match outcome {
        ExecutionOutcome::Completed(state) => {
            // Both messages should be present (Appender semantics)
            assert_eq!(state.messages.len(), 2);
            assert!(state.messages.contains(&"from_a".to_string()));
            assert!(state.messages.contains(&"from_b".to_string()));
        }
        _ => panic!("Expected Completed"),
    }
}

#[tokio::test]
async fn test_interrupt_halts_execution() {
    let graph = StateGraph::new()
        .add_node("work", AppendNode::new("work", "done"))
        .add_node("review", InterruptNode)
        .add_edge(START, "work")
        .add_edge("work", "review")
        .add_edge("review", END)
        .compile()
        .unwrap();

    let outcome = graph
        .invoke(TestState::new(), GraphConfig::default())
        .await
        .unwrap();

    match outcome {
        ExecutionOutcome::Interrupted { state, request } => {
            // "work" completed before interrupt
            assert_eq!(state.messages, vec!["done"]);
            assert_eq!(request.reason, "need approval");
            assert_eq!(request.resume_point, "review");
        }
        _ => panic!("Expected Interrupted"),
    }
}

#[tokio::test]
async fn test_error_propagates() {
    let graph = StateGraph::new()
        .add_node("bad", ErrorNode)
        .add_edge(START, "bad")
        .add_edge("bad", END)
        .compile()
        .unwrap();

    let result = graph.invoke(TestState::new(), GraphConfig::default()).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("node failed"), "Error should propagate: {err}");
}

#[tokio::test]
async fn test_snapshot_isolation() {
    // Two parallel nodes both read counter=0 and try to set counter=1
    // With snapshot isolation, both see counter=0
    // LastValue semantics means last-applied wins (both set to 1, not 2)
    struct SetCounterNode {
        name: &'static str,
    }

    impl NodeFn<TestState> for SetCounterNode {
        fn call(&self, state: &TestState, _ctx: &NodeContext) -> NodeFuture<TestUpdate> {
            // Read current counter and add 1
            let val = state.counter + 1;
            Box::pin(async move {
                NodeResult::Update(TestUpdate {
                    messages: None,
                    counter: Some(val),
                })
            })
        }
        fn name(&self) -> &str {
            self.name
        }
    }

    let graph = StateGraph::new()
        .add_node("a", SetCounterNode { name: "a" })
        .add_node("b", SetCounterNode { name: "b" })
        .add_edge(START, "a")
        .add_edge(START, "b")
        .add_edge("a", END)
        .add_edge("b", END)
        .compile()
        .unwrap();

    let outcome = graph
        .invoke(TestState::new(), GraphConfig::default())
        .await
        .unwrap();

    match outcome {
        ExecutionOutcome::Completed(state) => {
            // Both saw counter=0, both set counter=1
            // LastValue: last applied wins = 1 (not 2)
            assert_eq!(
                state.counter, 1,
                "Snapshot isolation: both nodes saw counter=0"
            );
        }
        _ => panic!("Expected Completed"),
    }
}

#[tokio::test]
async fn test_snapshot_isolation_appender() {
    // Two parallel nodes both append messages — Appender semantics means BOTH preserved
    let graph = StateGraph::new()
        .add_node("a", AppendNode::new("a", "from_a"))
        .add_node("b", AppendNode::new("b", "from_b"))
        .add_edge(START, "a")
        .add_edge(START, "b")
        .add_edge("a", END)
        .add_edge("b", END)
        .compile()
        .unwrap();

    let outcome = graph
        .invoke(TestState::new(), GraphConfig::default())
        .await
        .unwrap();

    match outcome {
        ExecutionOutcome::Completed(state) => {
            // Appender: both writes accumulate (unlike LastValue which overwrites)
            assert_eq!(state.messages.len(), 2);
            assert!(state.messages.contains(&"from_a".to_string()));
            assert!(state.messages.contains(&"from_b".to_string()));
        }
        _ => panic!("Expected Completed"),
    }
}

#[tokio::test]
async fn test_node_context_remaining_steps() {
    // Node reads ctx.remaining_steps() and puts it in the message
    struct ContextAwareNode;

    impl NodeFn<TestState> for ContextAwareNode {
        fn call(&self, _state: &TestState, ctx: &NodeContext) -> NodeFuture<TestUpdate> {
            let remaining = ctx.remaining_steps();
            let is_last = ctx.is_last_step();
            let msg = format!("remaining={remaining},last={is_last}");
            Box::pin(async move {
                NodeResult::Update(TestUpdate {
                    messages: Some(vec![msg]),
                    counter: None,
                })
            })
        }
        fn name(&self) -> &str {
            "ctx-aware"
        }
    }

    let graph = StateGraph::new()
        .add_node("check", ContextAwareNode)
        .add_edge(START, "check")
        .add_edge("check", END)
        .compile()
        .unwrap();

    let config = GraphConfig::default().with_recursion_limit(10);
    let outcome = graph.invoke(TestState::new(), config).await.unwrap();

    match outcome {
        ExecutionOutcome::Completed(state) => {
            // Step 1, limit 10 → remaining = 10 - 1 = 9, not last
            assert_eq!(state.messages, vec!["remaining=9,last=false"]);
        }
        _ => panic!("Expected Completed"),
    }
}

#[tokio::test]
async fn test_get_state_history() {
    let cp = InMemoryCheckpointer::new();

    // Graph with 3 linear steps → 3 checkpoints
    let graph = StateGraph::new()
        .add_node("a", AppendNode::new("a", "first"))
        .add_node("b", AppendNode::new("b", "second"))
        .add_node("c", AppendNode::new("c", "third"))
        .add_edge(START, "a")
        .add_edge("a", "b")
        .add_edge("b", "c")
        .add_edge("c", END)
        .compile()
        .unwrap()
        .with_checkpointer(cp);

    let config = GraphConfig::default().with_thread_id("history-test");
    let _ = graph.invoke(TestState::new(), config).await.unwrap();

    let history = graph.get_state_history("history-test").await.unwrap();
    // Should have checkpoints (one per superstep)
    assert!(
        history.len() >= 3,
        "Expected at least 3 checkpoints, got {}",
        history.len()
    );
    // Steps should be monotonically increasing
    for i in 1..history.len() {
        assert!(history[i].step >= history[i - 1].step);
    }
}

#[tokio::test]
async fn test_resume_after_interrupt() {
    let cp = InMemoryCheckpointer::new();

    let graph = StateGraph::new()
        .add_node("work", AppendNode::new("work", "step1"))
        .add_node("review", InterruptNode)
        .add_node("finish", AppendNode::new("finish", "step2"))
        .add_edge(START, "work")
        .add_edge("work", "review")
        .add_edge("review", "finish")
        .add_edge("finish", END)
        .compile()
        .unwrap()
        .with_checkpointer(cp);

    let config = GraphConfig::default().with_thread_id("resume-test");

    // First invoke — hits interrupt
    let outcome = graph
        .invoke(TestState::new(), config.clone())
        .await
        .unwrap();
    assert!(matches!(outcome, ExecutionOutcome::Interrupted { .. }));

    // Resume with human input
    let human_input = TestUpdate {
        messages: Some(vec!["human says ok".into()]),
        counter: None,
    };
    let outcome = graph
        .resume("resume-test", human_input, config)
        .await
        .unwrap();

    match outcome {
        ExecutionOutcome::Completed(state) => {
            assert!(state.messages.contains(&"step1".to_string()));
            assert!(state.messages.contains(&"human says ok".to_string()));
            // "finish" node should have run after resume
            assert!(state.messages.contains(&"step2".to_string()));
        }
        _ => panic!("Expected Completed after resume"),
    }
}

#[tokio::test]
async fn test_get_state_after_checkpoint() {
    let cp = InMemoryCheckpointer::new();

    let graph = StateGraph::new()
        .add_node("work", AppendNode::new("work", "data"))
        .add_node("review", InterruptNode)
        .add_edge(START, "work")
        .add_edge("work", "review")
        .add_edge("review", END)
        .compile()
        .unwrap()
        .with_checkpointer(cp);

    let config = GraphConfig::default().with_thread_id("state-test");
    let _ = graph.invoke(TestState::new(), config).await.unwrap();

    let snapshot = graph.get_state("state-test").await.unwrap();
    assert!(snapshot.is_some());

    let snap = snapshot.unwrap();
    assert!(snap.state.messages.contains(&"data".to_string()));
    assert_eq!(snap.thread_id, "state-test");
}

#[tokio::test]
async fn test_empty_graph_no_start_edge() {
    let result = StateGraph::<TestState>::new()
        .add_node("orphan", AppendNode::new("orphan", "lost"))
        .compile();

    assert!(result.is_err());
}

#[tokio::test]
async fn test_single_node_graph() {
    let graph = StateGraph::new()
        .add_node("only", AppendNode::new("only", "hello"))
        .add_edge(START, "only")
        .add_edge("only", END)
        .compile()
        .unwrap();

    let outcome = graph
        .invoke(TestState::new(), GraphConfig::default())
        .await
        .unwrap();

    match outcome {
        ExecutionOutcome::Completed(state) => {
            assert_eq!(state.messages, vec!["hello"]);
        }
        _ => panic!("Expected Completed"),
    }
}

// ── Timeout Tests ────────────────────────────────────────────────────

/// A node that sleeps for a specified duration before returning.
struct SlowNode {
    name: &'static str,
    delay: Duration,
}

impl NodeFn<TestState> for SlowNode {
    fn call(&self, _state: &TestState, _ctx: &NodeContext) -> NodeFuture<TestUpdate> {
        let delay = self.delay;
        Box::pin(async move {
            tokio::time::sleep(delay).await;
            NodeResult::Update(TestUpdate {
                messages: Some(vec!["slow_done".into()]),
                counter: None,
            })
        })
    }
    fn name(&self) -> &str {
        self.name
    }
}

#[tokio::test]
async fn test_no_timeout_runs_normally() {
    // Default config has no timeout — graph completes without issue
    let graph = StateGraph::new()
        .add_node("a", AppendNode::new("a", "first"))
        .add_node("b", AppendNode::new("b", "second"))
        .add_edge(START, "a")
        .add_edge("a", "b")
        .add_edge("b", END)
        .compile()
        .unwrap();

    let config = GraphConfig::default();
    assert!(config.max_execution_time.is_none());

    let outcome = graph.invoke(TestState::new(), config).await.unwrap();
    match outcome {
        ExecutionOutcome::Completed(state) => {
            assert_eq!(state.messages, vec!["first", "second"]);
        }
        _ => panic!("Expected Completed"),
    }
}

#[tokio::test]
async fn test_generous_timeout_completes_normally() {
    // 10-second timeout on a fast graph — should complete with time to spare
    let graph = StateGraph::new()
        .add_node("a", AppendNode::new("a", "done"))
        .add_edge(START, "a")
        .add_edge("a", END)
        .compile()
        .unwrap();

    let config = GraphConfig::default().with_max_execution_time(Duration::from_secs(10));

    let outcome = graph.invoke(TestState::new(), config).await.unwrap();
    match outcome {
        ExecutionOutcome::Completed(state) => {
            assert_eq!(state.messages, vec!["done"]);
        }
        _ => panic!("Expected Completed"),
    }
}

#[tokio::test]
async fn test_short_timeout_on_multi_step_graph_returns_timeout() {
    // A cycling graph with a 1ms timeout — the first superstep may complete
    // (the timeout check happens at the START of each superstep), but subsequent
    // iterations will exceed the 1ms budget and return Timeout.
    let graph = StateGraph::new()
        .add_node(
            "work",
            SlowNode {
                name: "work",
                delay: Duration::from_millis(10),
            },
        )
        .add_node("loop_back", AppendNode::new("loop_back", "again"))
        .add_edge(START, "work")
        .add_edge("work", "loop_back")
        .add_edge("loop_back", "work") // cycle
        .compile()
        .unwrap();

    let config = GraphConfig::default()
        .with_recursion_limit(100) // high limit so timeout triggers first
        .with_max_execution_time(Duration::from_millis(1));

    let result = graph.invoke(TestState::new(), config).await;
    assert!(result.is_err(), "Expected timeout error");
    let err = result.unwrap_err();
    assert!(
        matches!(err, PeError::Timeout { .. }),
        "Expected PeError::Timeout, got: {err:?}"
    );
}

#[tokio::test]
async fn test_timeout_error_contains_elapsed_info() {
    // Verify the Timeout variant has meaningful data (seconds field)
    let graph = StateGraph::new()
        .add_node(
            "slow",
            SlowNode {
                name: "slow",
                delay: Duration::from_millis(50),
            },
        )
        .add_node("next", AppendNode::new("next", "x"))
        .add_edge(START, "slow")
        .add_edge("slow", "next")
        .add_edge("next", "slow") // cycle
        .compile()
        .unwrap();

    let config = GraphConfig::default()
        .with_recursion_limit(100)
        .with_max_execution_time(Duration::from_millis(1));

    let result = graph.invoke(TestState::new(), config).await;
    let err = result.unwrap_err();
    match err {
        PeError::Timeout { seconds } => {
            // The Display message should contain "timeout"
            let msg = format!("{err}");
            assert!(
                msg.to_lowercase().contains("timeout"),
                "Error message should mention timeout: {msg}"
            );
            // seconds should be small since we're timing out after ~50ms
            assert!(
                seconds < 5.0,
                "Sub-second timeout should report small value, got {seconds}"
            );
        }
        other => panic!("Expected PeError::Timeout, got: {other:?}"),
    }
}