Skip to main content

lellm_graph/
test_executor.rs

1//! 测试用执行器 — 替代已删除的 SimpleExecutor。
2//!
3//! 提供两种执行模式:
4//! - `execute()` — 阻塞执行,返回 `GraphResult`
5//! - `execute_stream()` — 流式执行,返回 `GraphExecution { stream, handle }`
6
7use std::sync::Arc;
8use std::time::Instant;
9
10use tokio_util::sync::CancellationToken;
11
12use crate::error::GraphError;
13use crate::event::{GraphExecution, GraphHandle};
14use crate::execution_engine::{ExecutionEngine, ExecutorState, NextAction};
15use crate::graph::Graph;
16use crate::ids::TraceId;
17use crate::node::{BarrierNode, ConditionNode, FlowNode, LeafNode, NodeKind};
18use crate::state::{ExecutionEntry, GraphResult, State};
19
20// ─── SimpleExecutor 兼容层 ────────────────────────────────────────
21
22/// 兼容 SimpleExecutor 的 API,供测试使用。
23///
24/// 仅支持 `Graph<State, StateMerge>`(默认泛型参数)。
25pub struct SimpleExecutor {
26    max_steps: usize,
27}
28
29impl Default for SimpleExecutor {
30    fn default() -> Self {
31        Self { max_steps: 100 }
32    }
33}
34
35impl SimpleExecutor {
36    pub fn new(max_steps: usize) -> Self {
37        Self { max_steps }
38    }
39
40    pub async fn execute(
41        &self,
42        graph: Arc<Graph>,
43        mut state: State,
44    ) -> Result<GraphResult, GraphError> {
45        let trace_id = TraceId::new();
46        let start_time = Instant::now();
47        let mut execution_log: Vec<ExecutionEntry> = Vec::new();
48
49        let cancel = CancellationToken::new();
50        let mut engine = ExecutionEngine::new(&mut state, None, cancel);
51
52        // 执行循环 — 与 run_inline 一致,但记录 ExecutionEntry
53        let mut current = graph.start_node().to_string();
54        let mut step: usize = 0;
55
56        loop {
57            step += 1;
58            if step > self.max_steps {
59                return Err(GraphError::Terminal(
60                    crate::error::TerminalError::StepsExceeded {
61                        limit: self.max_steps,
62                    },
63                ));
64            }
65
66            let node = match graph.nodes.get(&current) {
67                Some(n) => n,
68                None => {
69                    return Err(GraphError::Terminal(
70                        crate::error::TerminalError::NodeNotFound(current.clone()),
71                    ));
72                }
73            };
74
75            let node_name = current.clone();
76            let node_start = Instant::now();
77
78            // 根据 NodeKind 分发执行
79            match node {
80                NodeKind::Task(n) => {
81                    let mut ctx = engine.build_node_context();
82                    n.execute(&mut ctx).await?;
83                }
84                NodeKind::Condition(n) => {
85                    let mut ctx = engine.build_leaf_context();
86                    <ConditionNode as LeafNode>::execute(n, &mut ctx).await?;
87                }
88                NodeKind::Barrier(n) => {
89                    let mut ctx = engine.build_leaf_context();
90                    <BarrierNode as LeafNode>::execute(n, &mut ctx).await?;
91                }
92                NodeKind::External(n) => {
93                    let mut ctx = engine.build_node_context();
94                    n.execute(&mut ctx).await?;
95                }
96                NodeKind::ExternalLeaf(n) => {
97                    let mut ctx = engine.build_leaf_context();
98                    n.execute(&mut ctx).await?;
99                }
100                NodeKind::Parallel(p) => {
101                    // ExecutorOperation 直接接收 &mut ExecutionEngine
102                    p.execute(&mut engine).await?;
103                }
104                NodeKind::Subgraph(_subgraph) => {
105                    // TODO: 实现 Subgraph 执行
106                    // 由 ExecutionEngine 负责 Frame 管理、状态投影、Checkpoint 和恢复
107                    tracing::warn!("Subgraph execution not yet implemented");
108                }
109            }
110
111            let node_duration = node_start.elapsed();
112
113            execution_log.push(ExecutionEntry {
114                step,
115                node_name,
116                start_time: node_start,
117                end_time: start_time.checked_add(node_duration).unwrap_or(start_time),
118                success: true,
119                error: None,
120            });
121
122            // commit mutations (Unit of Work) — 对 Parallel 是空操作
123            // (replace_state 已经直接替换了状态,mutation buffer 为空)
124            engine.commit();
125
126            // 提取控制信号
127            let (next_action, _signal) = engine.take_control();
128
129            // 处理路由
130            match next_action {
131                NextAction::End => break,
132                NextAction::Goto(target) => {
133                    current = target;
134                }
135                NextAction::Next => {
136                    if current == graph.end_node() {
137                        break;
138                    }
139                    current = graph.resolve_next_inline(&current, engine.state())?;
140                }
141            }
142        }
143
144        let duration = start_time.elapsed();
145        let final_state = state;
146
147        Ok(GraphResult {
148            trace_id,
149            state: final_state,
150            execution_log,
151            duration,
152            trace: None,
153        })
154    }
155
156    pub fn execute_stream(&self, graph: Arc<Graph>, state: State) -> GraphExecution<State> {
157        self.execute_stream_with_restore(graph, state, None)
158    }
159
160    pub fn execute_stream_with_restore(
161        &self,
162        graph: Arc<Graph>,
163        state: State,
164        restore_from: Option<crate::checkpoint::Checkpoint<State>>,
165    ) -> GraphExecution<State> {
166        let (event_tx, event_rx) = tokio::sync::mpsc::channel(256);
167        let (decision_tx, decision_rx) = tokio::sync::mpsc::channel(256);
168        let (cancel_tx, cancel_rx) = tokio::sync::mpsc::channel(1);
169
170        let trace_id = TraceId::new();
171        let cancel = CancellationToken::new();
172
173        let handle = GraphHandle::new(decision_tx, cancel_tx);
174
175        tokio::spawn(crate::execution_loop::run_execution_loop(
176            graph,
177            state,
178            self.max_steps,
179            trace_id,
180            event_tx,
181            decision_rx,
182            cancel_rx,
183            cancel,
184            None, // checkpoint
185            None, // trace_sink
186            restore_from,
187        ));
188
189        GraphExecution {
190            stream: event_rx,
191            handle,
192        }
193    }
194}