Skip to main content

lc_langgraph/compiled/
parallel.rs

1// crates/lc-langgraph/src/compiled/parallel.rs
2//! CompiledGraph invoke_parallel, invoke_dynamic, and merge_parallel_states methods
3
4use super::graph::CompiledGraph;
5use super::types::{
6    DynamicInjection, DynamicPlanner, ExecutionStep, GraphInvocation, ParallelBranch,
7    ParallelInvocation,
8};
9use crate::errors::{GraphError, GraphResult};
10use crate::node::NodeConfig;
11use crate::state::StateSchema;
12use crate::END;
13use std::collections::HashMap;
14
15impl<S: StateSchema> CompiledGraph<S> {
16    /// Run the graph while capturing parallel fan-out branches into a [`ParallelInvocation`].
17    pub async fn invoke_parallel(&self, input: S) -> GraphResult<ParallelInvocation<S>> {
18        let mut state = input;
19        let mut current_node = self.entry_point.clone();
20        let mut steps: Vec<ExecutionStep> = Vec::new();
21        let mut recursion_count = 0;
22        let mut parallel_branches: Vec<ParallelBranch<S>> = Vec::new();
23
24        if let Some(ref checkpointer) = self.checkpointer {
25            let checkpoint_id = checkpointer.lock().await.save(&state, 0).await?;
26            steps.push(ExecutionStep::checkpoint(
27                checkpoint_id,
28                current_node.clone(),
29            ));
30        }
31
32        loop {
33            if current_node == END {
34                break;
35            }
36
37            // Q3: check the limit before executing a step (same guard as `invoke`).
38            if recursion_count >= self.recursion_limit {
39                return Err(GraphError::RecursionLimitReached(self.recursion_limit));
40            }
41
42            if self.interrupt_before.contains(&current_node) {
43                return Err(GraphError::ExecutionInterrupted(current_node.clone()));
44            }
45
46            recursion_count += 1;
47
48            let fan_out_targets = self.find_fan_out_targets(&current_node).await;
49
50            if let Some(targets) = fan_out_targets {
51                let branch_results = self
52                    .execute_parallel_branches(&targets, &state, recursion_count)
53                    .await?;
54
55                for (name, inv) in branch_results {
56                    parallel_branches.push(ParallelBranch {
57                        name: name.clone(),
58                        final_state: inv.final_state.clone(),
59                        steps: inv.steps.clone(),
60                    });
61                    steps.push(ExecutionStep::ParallelNode {
62                        branch: name,
63                        metadata: HashMap::new(),
64                    });
65                }
66
67                let merge_target = self.find_fan_in_target(&targets).await;
68                if let Some(merge_node) = merge_target {
69                    state = self.merge_parallel_states(&parallel_branches)?;
70                    current_node = merge_node;
71                } else {
72                    // H6: 与 invoke.rs 的主路径一致——所有分支结果经 reducer 合并,
73                    // 而不是只保留 `parallel_branches.last()` 一个分支、丢弃其余分支。
74                    state = self.merge_parallel_states(&parallel_branches)?;
75                    current_node = END.to_string();
76                }
77            } else {
78                let node = self.get_node(&current_node).await?;
79
80                let config = NodeConfig {
81                    recursion_limit: self.recursion_limit,
82                    debug: false,
83                    metadata: HashMap::new(),
84                };
85
86                let update = node.execute(&state, Some(config)).await?;
87
88                if let Some(new_state) = update.update {
89                    state = self.default_reducer.reduce(&state, &new_state);
90                }
91
92                steps.push(ExecutionStep::node(
93                    current_node.clone(),
94                    update.metadata.clone(),
95                ));
96
97                if self.interrupt_after.contains(&current_node) {
98                    return Err(GraphError::ExecutionInterrupted(format!(
99                        "after_{}",
100                        current_node
101                    )));
102                }
103
104                current_node = self.find_next_node(&current_node, &state).await?;
105            }
106        }
107
108        Ok(ParallelInvocation {
109            final_state: state,
110            steps,
111            recursion_count,
112            parallel_branches,
113        })
114    }
115
116    /// Execute the graph with dynamic task injection support.
117    ///
118    /// After each node completes, checks the task_inbox for newly submitted tasks.
119    /// If tasks are found, uses the provided `planner` to convert them into new
120    /// nodes/edges and injects them into the runtime registries before continuing.
121    pub async fn invoke_dynamic(
122        &self,
123        input: S,
124        planner: &dyn DynamicPlanner<S>,
125    ) -> GraphResult<GraphInvocation<S>> {
126        let mut state = input;
127        let mut current_node = self.entry_point.clone();
128        let mut steps: Vec<ExecutionStep> = Vec::new();
129        let mut recursion_count = 0;
130
131        if let Some(ref checkpointer) = self.checkpointer {
132            let checkpoint_id = checkpointer.lock().await.save(&state, 0).await?;
133            steps.push(ExecutionStep::checkpoint(
134                checkpoint_id,
135                current_node.clone(),
136            ));
137        }
138
139        loop {
140            if current_node == END {
141                break;
142            }
143
144            // Q3: check the limit before executing a step (same guard as `invoke`).
145            if recursion_count >= self.recursion_limit {
146                return Err(GraphError::RecursionLimitReached(self.recursion_limit));
147            }
148
149            // Check for pending dynamically-submitted tasks
150            let pending = {
151                let mut inbox = self.task_inbox.lock().await;
152                inbox.drain(..).collect::<Vec<_>>()
153            };
154            if !pending.is_empty() {
155                let injection: DynamicInjection<S> = planner
156                    .plan(&pending, &state)
157                    .await
158                    .map_err(|e| GraphError::RuntimeError(e.to_string()))?;
159
160                {
161                    let mut rn = self.runtime_nodes.write().await;
162                    for (name, node) in injection.nodes {
163                        rn.insert(name, node);
164                    }
165                }
166                {
167                    let mut re = self.runtime_edges.write().await;
168                    re.extend(injection.edges);
169                }
170            }
171
172            if self.interrupt_before.contains(&current_node) {
173                return Err(GraphError::ExecutionInterrupted(current_node.clone()));
174            }
175
176            recursion_count += 1;
177
178            let node = self.get_node(&current_node).await?;
179            let config = NodeConfig {
180                recursion_limit: self.recursion_limit,
181                debug: false,
182                metadata: HashMap::new(),
183            };
184            let update = node.execute(&state, Some(config)).await?;
185
186            if let Some(new_state) = update.update {
187                state = self.default_reducer.reduce(&state, &new_state);
188            }
189            steps.push(ExecutionStep::node(
190                current_node.clone(),
191                update.metadata.clone(),
192            ));
193
194            if self.interrupt_after.contains(&current_node) {
195                return Err(GraphError::ExecutionInterrupted(format!(
196                    "after_{}",
197                    current_node
198                )));
199            }
200
201            let next_node = self.find_next_node(&current_node, &state).await?;
202
203            if let Some(ref checkpointer) = self.checkpointer {
204                let checkpoint_id = checkpointer
205                    .lock()
206                    .await
207                    .save(&state, recursion_count)
208                    .await?;
209                steps.push(ExecutionStep::checkpoint(checkpoint_id, next_node.clone()));
210            }
211
212            current_node = next_node;
213        }
214
215        Ok(GraphInvocation {
216            final_state: state,
217            steps,
218            recursion_count,
219        })
220    }
221
222    pub(super) fn merge_parallel_states(&self, branches: &[ParallelBranch<S>]) -> GraphResult<S> {
223        if branches.is_empty() {
224            return Err(GraphError::StateError(
225                "Cannot merge states: no parallel branches completed".to_string(),
226            ));
227        }
228
229        let mut merged = branches[0].final_state.clone();
230        for branch in branches.iter().skip(1) {
231            merged = self.default_reducer.reduce(&merged, &branch.final_state);
232        }
233        Ok(merged)
234    }
235}