Skip to main content

lellm_graph/exec/
execution_engine.rs

1//! ExecutionEngine — 执行引擎核心类型。
2//!
3//! 职责分离:
4//! - `ExecutionEngine<'a, S>` — Executor 内部使用,**借用** State(`&'a mut S`),
5//!   持有 Mutation 缓冲、流发射器等运行时资源
6//! - `NodeContext<'a, S>` / `LeafContext<'a, S>` — 节点能力视图(在 node_context.rs 中)
7//!
8//! # 状态所有权模型
9//!
10//! ExecutionEngine **借用** State,不拥有它。调用方持有 State 的所有权,
11//! Engine 只在执行期间借用。这使得 Subgraph 组合成为可能:
12//!
13//! ```text
14//! 调用方
15//!   ├── state: S                (拥有所有权)
16//!   ├── engine: Engine<'_, S>   (借用 &mut state)
17//!   │     └── SubgraphSpec::execute()
18//!   │           ├── lens.get(state) → &mut Inner
19//!   │           ├── inner_engine: Engine<'_, Inner>  (借用 &mut inner)
20//!   │           └── graph.run_inline(&mut inner_engine)
21//!   └── state 仍然可用(engine drop 后借用释放)
22//! ```
23//!
24//! 数据流单向:
25//!
26//! ```text
27//! Node
28//!   ↓
29//! ctx.record(Mutation)
30//!   ↓
31//! Mutation Buffer (ExecutionEngine)
32//!   ↓
33//! Engine: take_mutations()
34//!   ↓
35//! state.apply_batch(mutations)
36//!   ↓
37//! State
38//! ```
39//!
40//! 节点只能通过 `record()` 声明变更意图,无法直接修改 State。
41//! 这保证了 Mutation Log 是唯一写入口,使 Replay、Trace、Parallel Merge、Undo 全部成立。
42//!
43//! # Sink 注入模型
44//!
45//! 所有高级能力通过 Sink 注入,Engine 不维护任何"事件缓冲":
46//!
47//! ```text
48//! Graph::run_inline()
49//!         │
50//!         ▼
51//!    ExecutionEngine
52//!         │
53//!         ├── StreamSink        — 数据面流式输出
54//!         ├── CheckpointSink    — 恢复边界通知
55//!         └── BarrierSink       — Barrier 等待 + 决策注入
56//! ```
57
58use std::sync::Arc;
59
60use tokio_util::sync::CancellationToken;
61
62use crate::checkpoint::{CheckpointSink, NodeId};
63use crate::error::GraphError;
64use crate::node::barrier_sink::BarrierSink;
65use crate::state::workflow_state::WorkflowState;
66use crate::stream_chunk::StreamChunk;
67use crate::stream_emitter::StreamSink;
68
69// ─── ExecutionSignal ──────────────────────────────────────────
70
71/// 控制信号 — 独立枚举,Barrier 挂起不是路由。
72#[derive(Debug, Clone)]
73pub enum ExecutionSignal {
74    /// Barrier 挂起执行
75    Pause {
76        barrier_id: crate::event::BarrierId,
77        timeout: Option<std::time::Duration>,
78    },
79}
80
81// ─── NextAction ────────────────────────────────────────────────
82
83/// 节点执行后的下一步路由。
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub enum NextAction {
86    /// 按拓扑顺序走下一步(默认值)
87    Next,
88    /// 跳转到指定节点
89    Goto(String),
90    /// 结束执行
91    End,
92}
93
94// ─── ExecutionControl ─────────────────────────────────────────
95
96/// 控制信号容器 — 节点写入,Executor 读取。
97#[derive(Debug, Default)]
98pub struct ExecutionControl {
99    next: Option<NextAction>,
100    signal: Option<ExecutionSignal>,
101}
102
103impl ExecutionControl {
104    pub fn new() -> Self {
105        Self::default()
106    }
107
108    /// 跳转到指定节点。
109    pub fn goto(&mut self, target: impl Into<String>) {
110        self.next = Some(NextAction::Goto(target.into()));
111    }
112
113    /// 结束执行。
114    pub fn end(&mut self) {
115        self.next = Some(NextAction::End);
116    }
117
118    /// Barrier 挂起。
119    pub fn pause(
120        &mut self,
121        barrier_id: crate::event::BarrierId,
122        timeout: Option<std::time::Duration>,
123    ) {
124        self.signal = Some(ExecutionSignal::Pause {
125            barrier_id,
126            timeout,
127        });
128    }
129
130    /// 获取最终的控制信号。
131    pub fn take(&mut self) -> (NextAction, Option<ExecutionSignal>) {
132        let next = self.next.take().unwrap_or(NextAction::Next);
133        let signal = self.signal.take();
134        (next, signal)
135    }
136}
137
138// ─── NodeMetadata ─────────────────────────────────────────────
139
140/// 节点元数据 — 提供给 Executor 的额外信息。
141#[derive(Debug, Clone, Default)]
142pub struct NodeMetadata {
143    /// Token 消耗成本(0.0 表示无 LLM 调用)
144    pub token_cost: f64,
145    /// 是否有外部副作用(如部署、发送消息)
146    pub has_side_effects: bool,
147}
148
149// ─── ExecutionView trait ──────────────────────────────────────
150
151/// 受限视图 — Leaf 节点需要的最小能力。
152pub trait ExecutionView<S: WorkflowState>: Send + Sync {
153    fn state(&self) -> &S;
154    fn emit(&self, chunk: StreamChunk);
155    fn is_cancelled(&self) -> bool;
156}
157
158// ─── ExecutorState trait ──────────────────────────────────────
159
160/// 完整能力 — Composite 节点 + LeafAdapter 使用。
161///
162/// # 注意
163///
164/// 此 trait **不是 dyn compatible**(`build_node_context` 返回带生命周期的 `NodeContext`,
165/// `apply_batch` 使用泛型)。仅用于静态分发(`T: ExecutorState<S>`),不用于 `dyn ExecutorState<S>`。
166pub trait ExecutorState<S: WorkflowState>: ExecutionView<S> {
167    fn build_node_context(&mut self) -> crate::node::node_context::NodeContext<'_, S>;
168    fn build_leaf_context(&mut self) -> crate::node::node_context::LeafContext<'_, S>;
169    fn clone_state(&self) -> S;
170    fn replace_state(&mut self, state: S);
171    fn apply_batch(&mut self, mutations: impl IntoIterator<Item = S::Mutation>);
172    fn take_control(&mut self) -> (NextAction, Option<ExecutionSignal>);
173    fn take_metadata(&mut self) -> NodeMetadata;
174}
175
176// ─── ExecutionEngine ──────────────────────────────────────────
177
178/// 执行引擎 — **借用** State,持有 Mutation 缓冲、流发射器等运行时资源。
179///
180/// 不对节点开发者公开。节点通过 [`NodeContext`](crate::node::node_context::NodeContext)
181/// 或 [`LeafContext`](crate::node::node_context::LeafContext) 能力视图交互。
182///
183/// # 状态所有权
184///
185/// Engine 借用 `&'a mut S`,不拥有 State。调用方在 Engine 生命周期外持有所有权。
186/// 这使得 Subgraph 组合成为可能 — 外层 Engine 借用 Outer,内层 Engine 借用 Inner。
187///
188/// # Sink 注入
189///
190/// 所有高级能力通过 Sink 注入:
191/// - `stream` — 数据面流式输出
192/// - `checkpoint` — 恢复边界通知
193/// - `barrier` — Barrier 等待 + 决策注入
194///
195/// # 三层 API
196///
197/// - **Leaf Execution API**: `build_leaf_context()` — 构建只读 + emit 视图
198/// - **Composite Execution API**: `clone_state()`, `replace_state()` — 执行控制
199/// - **Runtime Control Plane**: `stream`, `cancel`, `commit()` — 运行时管理
200pub struct ExecutionEngine<'a, S: WorkflowState> {
201    /// 类型化状态 — Engine 借用,不拥有
202    state: &'a mut S,
203    /// 数据面发射器 — 可选(阻塞模式 = None)。使用 Arc 以便 Parallel 子分支 clone。
204    stream: Option<Arc<dyn StreamSink>>,
205    /// 取消令牌 — 消费者断开时触发
206    cancel: CancellationToken,
207    /// Checkpoint Sink — 可选。Engine 借用,不拥有 Checkpoint 生命周期。
208    /// 在 commit() 之后通知 Sink 到达了合法的恢复边界。
209    checkpoint: Option<&'a mut dyn CheckpointSink<S>>,
210    /// Barrier Sink — 可选。Engine 借用,不拥有 Barrier 生命周期。
211    /// 在检测到 Pause 信号时,通过 BarrierSink 等待外部决策。
212    barrier: Option<&'a mut dyn BarrierSink>,
213    /// 控制信号 — 节点写入,Executor 读取
214    control: ExecutionControl,
215    /// 节点元数据 — 节点写入
216    metadata: NodeMetadata,
217    /// Mutation 缓冲 — 节点产生的强类型领域事件
218    mutations: Vec<S::Mutation>,
219}
220
221impl<'a, S: WorkflowState> ExecutionEngine<'a, S> {
222    /// 创建新的 ExecutionEngine。
223    ///
224    /// Engine 借用 `state`,不拥有它。调用方在 Engine 外保持所有权。
225    ///
226    /// - `checkpoint` — 可选的 Checkpoint Sink(`None` = 不需要自动 checkpoint)
227    /// - `barrier` — 可选的 Barrier Sink(`None` = 遇到 Barrier 直接 Approve)
228    pub fn new(
229        state: &'a mut S,
230        stream: Option<Arc<dyn StreamSink>>,
231        cancel: CancellationToken,
232        checkpoint: Option<&'a mut dyn CheckpointSink<S>>,
233        barrier: Option<&'a mut dyn BarrierSink>,
234    ) -> Self {
235        Self {
236            state,
237            stream,
238            cancel,
239            checkpoint,
240            barrier,
241            control: ExecutionControl::new(),
242            metadata: NodeMetadata::default(),
243            mutations: Vec::new(),
244        }
245    }
246
247    /// 通知 Checkpoint Sink 到达恢复边界并**同步等待保存完成**(crate 内部使用)。
248    ///
249    /// 由 Graph 执行循环在 commit + 路由解析之后调用。
250    /// 保存失败 → `GraphError::Terminal(CheckpointSaveFailed)`,不越过边界。
251    pub(crate) async fn emit_checkpoint(
252        &mut self,
253        next_node: Option<NodeId>,
254        step: usize,
255    ) -> Result<(), GraphError> {
256        if let Some(ref mut sink) = self.checkpoint {
257            let frame = crate::checkpoint::FrameInfo::new(next_node, step);
258            sink.on_checkpoint(self.state, &frame).await.map_err(|e| {
259                GraphError::Terminal(crate::error::TerminalError::CheckpointSaveFailed {
260                    error: e.to_string(),
261                })
262            })
263        } else {
264            Ok(())
265        }
266    }
267
268    /// 等待 Barrier 决策(crate 内部使用)。
269    ///
270    /// 由 Graph::run_inline() 在检测到 Pause 信号时调用。
271    /// 无 BarrierSink 时,直接返回 Approve。
272    pub(crate) async fn wait_barrier(
273        &mut self,
274        barrier_id: &crate::event::BarrierId,
275        timeout: Option<std::time::Duration>,
276    ) -> crate::node::barrier_sink::BarrierOutcome {
277        if let Some(ref mut sink) = self.barrier {
278            sink.wait_decision(barrier_id, timeout).await
279        } else {
280            crate::node::barrier_sink::BarrierOutcome::Decision(
281                crate::event::BarrierDecision::Approve,
282            )
283        }
284    }
285
286    // ─── Executor API ─────────────────────────────────────────
287
288    /// 消费 Mutation 缓冲(Executor 调用)。
289    pub fn take_mutations(&mut self) -> Vec<S::Mutation> {
290        std::mem::take(&mut self.mutations)
291    }
292
293    /// 消费控制信号(Executor 调用)。
294    pub fn take_control(&mut self) -> (NextAction, Option<ExecutionSignal>) {
295        self.control.take()
296    }
297
298    /// 获取元数据(Executor 调用)。
299    pub fn take_metadata(&mut self) -> NodeMetadata {
300        std::mem::take(&mut self.metadata)
301    }
302
303    /// 获取状态引用。
304    pub fn state(&self) -> &S {
305        self.state
306    }
307
308    /// 获取状态可变引用(Executor 内部使用)。
309    ///
310    /// ⚠️ 仅限 crate 内部调用。外部代码应通过 `ExecutorState::apply_batch()` 或
311    /// `NodeContext::record()` 间接操作状态。
312    pub(crate) fn state_mut(&mut self) -> &mut S {
313        self.state
314    }
315
316    /// 获取数据面发射器引用。
317    pub fn stream(&self) -> Option<&dyn StreamSink> {
318        self.stream.as_deref()
319    }
320
321    /// 获取取消令牌引用(Composite 节点用于 child_token)。
322    pub fn cancel_token(&self) -> &CancellationToken {
323        &self.cancel
324    }
325
326    /// 获取 stream 的 Arc 引用(Parallel 子分支 clone 用)。
327    pub fn stream_sink(&self) -> Option<Arc<dyn StreamSink>> {
328        self.stream.clone()
329    }
330
331    // ─── commit() — Unit of Work 流水线 ───────────────────────
332
333    /// 取出 mutation batch(Executor 调用)。
334    ///
335    /// 这是 commit 流水线的第一段:
336    /// ```text
337    /// take_commit_batch() → TraceSink/MutationLog 消费 → apply_batch_to_state()
338    /// ```
339    ///
340    /// 调用方可以在此处插入 Trace 记录、MutationLog 持久化等扩展点。
341    pub fn take_commit_batch(&mut self) -> Vec<S::Mutation> {
342        std::mem::take(&mut self.mutations)
343    }
344
345    /// 将 mutation batch 应用到状态(Executor 调用)。
346    ///
347    /// commit 流水线的最后一段。与 `take_commit_batch()` 配合使用。
348    pub fn apply_batch_to_state(&mut self, mutations: Vec<S::Mutation>) {
349        if !mutations.is_empty() {
350            self.state.apply_batch(mutations);
351        }
352    }
353
354    /// 完整的 commit 流水线(便捷方法)。
355    ///
356    /// 等价于 `apply_batch_to_state(take_commit_batch())`。
357    /// 内部调用使用此方法即可;需要扩展 Trace/MutationLog 的场景
358    /// 应手动调用 `take_commit_batch()` + 扩展点 + `apply_batch_to_state()`。
359    pub fn commit(&mut self) {
360        let batch = self.take_commit_batch();
361        self.apply_batch_to_state(batch);
362    }
363}
364
365// ─── ExecutionView for ExecutionEngine ───────────────────────
366
367impl<'a, S: WorkflowState> ExecutionView<S> for ExecutionEngine<'a, S> {
368    fn state(&self) -> &S {
369        self.state
370    }
371
372    fn emit(&self, chunk: StreamChunk) {
373        if let Some(ref stream) = self.stream {
374            stream.emit(chunk);
375        }
376    }
377
378    fn is_cancelled(&self) -> bool {
379        self.cancel.is_cancelled()
380    }
381}
382
383// ─── ExecutorState for ExecutionEngine ────────────────────────
384
385impl<'a, S: WorkflowState> ExecutorState<S> for ExecutionEngine<'a, S> {
386    fn build_node_context(&mut self) -> crate::node::node_context::NodeContext<'_, S> {
387        crate::node::node_context::NodeContext {
388            state: self.state,
389            stream: self.stream.as_deref(),
390            cancel: &self.cancel,
391            control: &mut self.control,
392            metadata: &mut self.metadata,
393            mutations: &mut self.mutations,
394        }
395    }
396
397    fn build_leaf_context(&mut self) -> crate::node::node_context::LeafContext<'_, S> {
398        crate::node::node_context::LeafContext {
399            state: self.state,
400            stream: self.stream.as_deref(),
401            cancel: &self.cancel,
402            control: &mut self.control,
403            metadata: &mut self.metadata,
404            mutations: &mut self.mutations,
405        }
406    }
407
408    fn clone_state(&self) -> S {
409        self.state.clone()
410    }
411
412    fn replace_state(&mut self, state: S) {
413        *self.state = state;
414    }
415
416    fn apply_batch(&mut self, mutations: impl IntoIterator<Item = S::Mutation>) {
417        self.state.apply_batch(mutations);
418    }
419
420    fn take_control(&mut self) -> (NextAction, Option<ExecutionSignal>) {
421        self.control.take()
422    }
423
424    fn take_metadata(&mut self) -> NodeMetadata {
425        std::mem::take(&mut self.metadata)
426    }
427}
428
429// ─── Backward Compat Alias ────────────────────────────────────
430
431/// 向后兼容别名 — `ExecutionContext` → `ExecutionEngine`。
432pub type ExecutionContext<'a, S> = ExecutionEngine<'a, S>;
433
434// ─── OwnedExecutionEngine (re-export) ─────────────────────────
435
436/// 拥有 State 所有权的执行引擎 — 用于 Parallel 分支等需要独立 State 的场景。
437///
438/// 与 `ExecutionEngine<'a, S>` 的区别:
439/// - `ExecutionEngine<'a, S>` 借用 `&'a mut S`,用于主执行路径
440/// - `OwnedExecutionEngine<S>` 拥有 `S`,用于需要独立 State 副本的场景(如 Parallel 分支)
441pub use crate::exec::owned_execution_engine::OwnedExecutionEngine;