Skip to main content

adk_graph/
graph.rs

1//! StateGraph builder for constructing graphs
2
3use crate::checkpoint::Checkpointer;
4use crate::deferred::DeferredNodeConfig;
5use crate::edge::{END, Edge, EdgeTarget, RouterFn, START};
6use crate::error::{GraphError, Result};
7use crate::node::{FunctionNode, Node, NodeContext, NodeOutput};
8use crate::state::{State, StateSchema};
9use std::collections::{HashMap, HashSet};
10use std::future::Future;
11use std::sync::Arc;
12
13/// Builder for constructing graphs
14pub struct StateGraph {
15    /// State schema
16    pub schema: StateSchema,
17    /// Registered nodes
18    pub nodes: HashMap<String, Arc<dyn Node>>,
19    /// Registered edges
20    pub edges: Vec<Edge>,
21    /// Fan-in (deferred) node configurations, keyed by node name.
22    pub deferred_configs: HashMap<String, DeferredNodeConfig>,
23}
24
25impl StateGraph {
26    /// Create a new graph with the given state schema
27    pub fn new(schema: StateSchema) -> Self {
28        Self { schema, nodes: HashMap::new(), edges: vec![], deferred_configs: HashMap::new() }
29    }
30
31    /// Create with a simple schema (just channel names, all overwrite)
32    pub fn with_channels(channels: &[&str]) -> Self {
33        Self::new(StateSchema::simple(channels))
34    }
35
36    /// Add a node to the graph
37    pub fn add_node<N: Node + 'static>(mut self, node: N) -> Self {
38        self.nodes.insert(node.name().to_string(), Arc::new(node));
39        self
40    }
41
42    /// Add a function as a node
43    pub fn add_node_fn<F, Fut>(self, name: &str, func: F) -> Self
44    where
45        F: Fn(NodeContext) -> Fut + Send + Sync + 'static,
46        Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
47    {
48        self.add_node(FunctionNode::new(name, func))
49    }
50
51    /// Add a **fan-in** (deferred) function node.
52    ///
53    /// Unlike [`add_node_fn`](Self::add_node_fn), a deferred node does not run as
54    /// soon as one upstream edge completes — the scheduler holds it until **all**
55    /// upstream paths that can reach it have finished (or, with a configured
56    /// `fan_in_timeout`, until that deadline). This is what makes a fan-out /
57    /// fan-in pattern correct: several branches run in parallel and a single
58    /// aggregator node runs once, after they all complete.
59    ///
60    /// The [`DeferredNodeConfig`] selects how the upstream outputs are exposed
61    /// (e.g. [`MergeStrategy::Collect`](crate::deferred::MergeStrategy::Collect))
62    /// and an optional fan-in timeout.
63    ///
64    /// # Example
65    /// ```ignore
66    /// use adk_graph::{StateGraph, DeferredNodeConfig, MergeStrategy};
67    /// let graph = StateGraph::with_channels(&["x"])
68    ///     .add_node_fn("a", |_| async { Ok(Default::default()) })
69    ///     .add_node_fn("b", |_| async { Ok(Default::default()) })
70    ///     .add_deferred_node_fn("join", |_| async { Ok(Default::default()) },
71    ///         DeferredNodeConfig { merge_strategy: MergeStrategy::Collect, ..Default::default() })
72    ///     .add_edge("a", "join")
73    ///     .add_edge("b", "join");
74    /// ```
75    pub fn add_deferred_node_fn<F, Fut>(
76        mut self,
77        name: &str,
78        func: F,
79        config: DeferredNodeConfig,
80    ) -> Self
81    where
82        F: Fn(NodeContext) -> Fut + Send + Sync + 'static,
83        Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
84    {
85        self.deferred_configs.insert(name.to_string(), config);
86        self.add_node(FunctionNode::new(name, func))
87    }
88
89    /// Mark an already-added node as a fan-in (deferred) node.
90    ///
91    /// Useful when the node was registered via [`add_node`](Self::add_node) with
92    /// a custom [`Node`] implementation.
93    pub fn mark_deferred(mut self, name: &str, config: DeferredNodeConfig) -> Self {
94        self.deferred_configs.insert(name.to_string(), config);
95        self
96    }
97
98    /// Add a direct edge from source to target
99    pub fn add_edge(mut self, source: &str, target: &str) -> Self {
100        let target = EdgeTarget::from(target);
101
102        if source == START {
103            // Find existing entry or create new one
104            let entry_idx = self.edges.iter().position(|e| matches!(e, Edge::Entry { .. }));
105
106            match entry_idx {
107                Some(idx) => {
108                    if let Edge::Entry { targets } = &mut self.edges[idx]
109                        && let EdgeTarget::Node(node) = &target
110                        && !targets.contains(node)
111                    {
112                        targets.push(node.clone());
113                    }
114                }
115                None => {
116                    if let EdgeTarget::Node(node) = target {
117                        self.edges.push(Edge::Entry { targets: vec![node] });
118                    }
119                }
120            }
121        } else {
122            self.edges.push(Edge::Direct { source: source.to_string(), target });
123        }
124
125        self
126    }
127
128    /// Add a conditional edge with a router function
129    pub fn add_conditional_edges<F, I>(mut self, source: &str, router: F, targets: I) -> Self
130    where
131        F: Fn(&State) -> String + Send + Sync + 'static,
132        I: IntoIterator<Item = (&'static str, &'static str)>,
133    {
134        let targets_map: HashMap<String, EdgeTarget> =
135            targets.into_iter().map(|(k, v)| (k.to_string(), EdgeTarget::from(v))).collect();
136
137        self.edges.push(Edge::Conditional {
138            source: source.to_string(),
139            router: Arc::new(router),
140            targets: targets_map,
141        });
142
143        self
144    }
145
146    /// Add a conditional edge with an Arc router (for pre-built routers)
147    pub fn add_conditional_edges_arc<I>(
148        mut self,
149        source: &str,
150        router: RouterFn,
151        targets: I,
152    ) -> Self
153    where
154        I: IntoIterator<Item = (&'static str, &'static str)>,
155    {
156        let targets_map: HashMap<String, EdgeTarget> =
157            targets.into_iter().map(|(k, v)| (k.to_string(), EdgeTarget::from(v))).collect();
158
159        self.edges.push(Edge::Conditional {
160            source: source.to_string(),
161            router,
162            targets: targets_map,
163        });
164
165        self
166    }
167
168    /// Compile the graph for execution
169    pub fn compile(mut self) -> Result<CompiledGraph> {
170        // A node with requirements on the graph that holds it states them now, so
171        // a mismatch cannot reach a run. `SubgraphNode` checks its channel map here.
172        for node in self.nodes.values() {
173            node.validate_against(&self.schema)?;
174        }
175        self.validate()?;
176        self.defer_unconditional_fan_in();
177
178        Ok(CompiledGraph {
179            schema: self.schema,
180            nodes: self.nodes,
181            edges: self.edges,
182            checkpointer: None,
183            interrupt_before: HashSet::new(),
184            interrupt_after: HashSet::new(),
185            recursion_limit: 100,
186            timeout_policies: HashMap::new(),
187            default_timeout: None,
188            default_retry: None,
189            error_handlers: HashMap::new(),
190            default_error_handler: None,
191            deferred_configs: self.deferred_configs,
192            max_concurrency: None,
193            retry_policies: HashMap::new(),
194            node_effects: HashMap::new(),
195            governed_nodes: HashMap::new(),
196            strict_channels: false,
197            retention: None,
198            #[cfg(feature = "node-cache")]
199            cache_policies: HashMap::new(),
200            #[cfg(feature = "node-cache")]
201            node_caches: HashMap::new(),
202        })
203    }
204
205    /// Mark any node reached by more than one unconditional edge as deferred.
206    ///
207    /// The frontier advances from whichever nodes finished in the last
208    /// super-step, so without this a join becomes eligible as soon as one
209    /// predecessor lands. On branches of unequal length it then runs once per
210    /// arriving predecessor, applying its updates repeatedly and reading a
211    /// half-built state.
212    ///
213    /// Only `Direct` and `Entry` edges count toward making a node deferred. Once
214    /// deferred, a node waits only for the predecessors that can still run in the
215    /// current pass, so a merge after a conditional branch, or a node re-entered by
216    /// a loop's back edge, runs with the arrivals it has.
217    ///
218    /// An explicit configuration always wins, so a caller who wants the earlier
219    /// behaviour keeps it by configuring the node themselves.
220    fn defer_unconditional_fan_in(&mut self) {
221        let mut in_degree: HashMap<&str, usize> = HashMap::new();
222        for edge in &self.edges {
223            match edge {
224                Edge::Direct { target, .. } => {
225                    if let Some(name) = target.node_name() {
226                        *in_degree.entry(name).or_insert(0) += 1;
227                    }
228                }
229                Edge::Entry { targets } => {
230                    for target in targets {
231                        *in_degree.entry(target.as_str()).or_insert(0) += 1;
232                    }
233                }
234                // A conditional edge selects one target at run time, so its
235                // targets are not guaranteed arrivals.
236                Edge::Conditional { .. } => {}
237            }
238        }
239
240        let fan_ins: Vec<String> = in_degree
241            .into_iter()
242            .filter(|(name, degree)| *degree > 1 && self.nodes.contains_key(*name))
243            .map(|(name, _)| name.to_string())
244            .collect();
245
246        for name in fan_ins {
247            self.deferred_configs.entry(name).or_default();
248        }
249    }
250
251    /// Validate the graph structure
252    fn validate(&self) -> Result<()> {
253        // Check for entry point
254        let has_entry = self.edges.iter().any(|e| matches!(e, Edge::Entry { .. }));
255        if !has_entry {
256            return Err(GraphError::NoEntryPoint);
257        }
258
259        // Reject a node that cannot execute. A configuration whose backend is
260        // unavailable should fail here, not part-way through a run when earlier nodes
261        // may already have had side effects.
262        for node in self.nodes.values() {
263            node.validate()?;
264        }
265
266        // Check all node references exist
267        for edge in &self.edges {
268            match edge {
269                Edge::Direct { source, target } => {
270                    if source != START && !self.nodes.contains_key(source) {
271                        return Err(GraphError::NodeNotFound(source.clone()));
272                    }
273                    if let EdgeTarget::Node(name) = target
274                        && !self.nodes.contains_key(name)
275                    {
276                        return Err(GraphError::EdgeTargetNotFound(name.clone()));
277                    }
278                }
279                Edge::Conditional { source, targets, .. } => {
280                    if !self.nodes.contains_key(source) {
281                        return Err(GraphError::NodeNotFound(source.clone()));
282                    }
283                    for target in targets.values() {
284                        if let EdgeTarget::Node(name) = target
285                            && !self.nodes.contains_key(name)
286                        {
287                            return Err(GraphError::EdgeTargetNotFound(name.clone()));
288                        }
289                    }
290                }
291                Edge::Entry { targets } => {
292                    for target in targets {
293                        if !self.nodes.contains_key(target) {
294                            return Err(GraphError::EdgeTargetNotFound(target.clone()));
295                        }
296                    }
297                }
298            }
299        }
300
301        Ok(())
302    }
303}
304
305/// A `(source, target)` pair: an executed node and a node it routed to.
306pub(crate) type Route = (String, String);
307
308/// Turns a node failure into state and a route, instead of ending the run.
309///
310/// Called after the node's retry budget is spent. Returning a
311/// [`crate::node::NodeOutput`] lets the handler record what happened
312/// and name a recovery node with
313/// [`with_goto`](crate::node::NodeOutput::with_goto). Returning `Err` ends the
314/// run as before.
315pub type NodeErrorHandler =
316    Arc<dyn Fn(&str, &GraphError, &State) -> Result<crate::node::NodeOutput> + Send + Sync>;
317
318/// Policies a graph applies to every node that does not set its own.
319///
320/// Repeating the same retry or timeout on twenty nodes is easy to get wrong by
321/// omission. A default states it once; a per-node value always wins.
322///
323/// # Example
324///
325/// ```
326/// use adk_graph::graph::NodeDefaults;
327/// use adk_graph::retry::RetryPolicy;
328/// use adk_graph::timeout::TimeoutPolicy;
329/// use std::time::Duration;
330///
331/// let defaults = NodeDefaults::new().with_retry(RetryPolicy::new(3)).with_timeout(
332///     TimeoutPolicy { run_timeout: Some(Duration::from_secs(30)), ..Default::default() },
333/// );
334/// # let _ = defaults;
335/// ```
336#[derive(Clone, Default)]
337pub struct NodeDefaults {
338    /// Retry policy for a node with none of its own.
339    pub retry: Option<crate::retry::RetryPolicy>,
340    /// Timeout policy for a node with none of its own.
341    pub timeout: Option<crate::timeout::TimeoutPolicy>,
342    /// Failure handler for a node with none of its own.
343    pub error_handler: Option<NodeErrorHandler>,
344}
345
346impl std::fmt::Debug for NodeDefaults {
347    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
348        f.debug_struct("NodeDefaults")
349            .field("retry", &self.retry)
350            .field("timeout", &self.timeout)
351            .field("error_handler", &self.error_handler.as_ref().map(|_| "<handler>"))
352            .finish()
353    }
354}
355
356impl NodeDefaults {
357    /// An empty set of defaults, which changes nothing.
358    pub fn new() -> Self {
359        Self::default()
360    }
361
362    /// Applies this retry policy to every node that sets none.
363    pub fn with_retry(mut self, policy: crate::retry::RetryPolicy) -> Self {
364        self.retry = Some(policy);
365        self
366    }
367
368    /// Applies this timeout policy to every node that sets none.
369    pub fn with_timeout(mut self, policy: crate::timeout::TimeoutPolicy) -> Self {
370        self.timeout = Some(policy);
371        self
372    }
373
374    /// Applies this failure handler to every node that sets none.
375    pub fn with_error_handler<F>(mut self, handler: F) -> Self
376    where
377        F: Fn(&str, &GraphError, &State) -> Result<crate::node::NodeOutput> + Send + Sync + 'static,
378    {
379        self.error_handler = Some(Arc::new(handler));
380        self
381    }
382}
383
384/// A compiled graph ready for execution
385pub struct CompiledGraph {
386    pub(crate) schema: StateSchema,
387    pub(crate) nodes: HashMap<String, Arc<dyn Node>>,
388    pub(crate) edges: Vec<Edge>,
389    pub(crate) checkpointer: Option<Arc<dyn Checkpointer>>,
390    pub(crate) interrupt_before: HashSet<String>,
391    pub(crate) interrupt_after: HashSet<String>,
392    pub(crate) recursion_limit: usize,
393    /// Per-node timeout policies, keyed by node name.
394    pub(crate) timeout_policies: HashMap<String, crate::timeout::TimeoutPolicy>,
395    /// Default timeout policy applied to all nodes without an explicit override.
396    pub(crate) default_timeout: Option<crate::timeout::TimeoutPolicy>,
397    /// Retry policy for every node that sets none of its own.
398    pub(crate) default_retry: Option<crate::retry::RetryPolicy>,
399    /// Per-node failure handlers, keyed by node name.
400    pub(crate) error_handlers: HashMap<String, NodeErrorHandler>,
401    /// Failure handler for every node that sets none of its own.
402    pub(crate) default_error_handler: Option<NodeErrorHandler>,
403    /// Deferred node configurations, keyed by node name.
404    pub(crate) deferred_configs: HashMap<String, crate::deferred::DeferredNodeConfig>,
405    /// Ceiling on how many nodes execute at once. `None` runs the whole frontier.
406    pub(crate) max_concurrency: Option<usize>,
407    /// Per-node retry policies, keyed by node name.
408    pub(crate) retry_policies: HashMap<String, crate::retry::RetryPolicy>,
409    /// Side effects nodes declared, keyed by node name.
410    pub(crate) node_effects: HashMap<String, adk_core::ToolEffect>,
411    /// Nodes whose calls go through the governed path, keyed by node name.
412    pub(crate) governed_nodes: HashMap<String, crate::governed::GovernedNode>,
413    /// Whether a node writing an undeclared channel fails the run.
414    pub(crate) strict_channels: bool,
415    /// How many checkpoints to keep per thread. `None` keeps every one.
416    pub(crate) retention: Option<crate::checkpoint::RetentionPolicy>,
417    /// Per-node cache policies, keyed by node name.
418    #[cfg(feature = "node-cache")]
419    pub(crate) cache_policies: HashMap<String, crate::cache::NodeCachePolicy>,
420    /// Per-node caches built from `cache_policies`, shared by every run of this
421    /// graph so a later run reuses what an earlier one stored.
422    #[cfg(feature = "node-cache")]
423    pub(crate) node_caches: HashMap<String, Arc<crate::cache::NodeCache>>,
424}
425
426impl CompiledGraph {
427    /// Configure checkpointing
428    pub fn with_checkpointer<C: Checkpointer + 'static>(mut self, checkpointer: C) -> Self {
429        self.checkpointer = Some(Arc::new(checkpointer));
430        self
431    }
432
433    /// Configure checkpointing with Arc
434    pub fn with_checkpointer_arc(mut self, checkpointer: Arc<dyn Checkpointer>) -> Self {
435        self.checkpointer = Some(checkpointer);
436        self
437    }
438
439    /// Configure interrupt before specific nodes
440    pub fn with_interrupt_before(mut self, nodes: &[&str]) -> Self {
441        self.interrupt_before = nodes.iter().map(|s| s.to_string()).collect();
442        self
443    }
444
445    /// Configure interrupt after specific nodes
446    pub fn with_interrupt_after(mut self, nodes: &[&str]) -> Self {
447        self.interrupt_after = nodes.iter().map(|s| s.to_string()).collect();
448        self
449    }
450
451    /// Sets how many super-steps one run may take; 100 when unset.
452    ///
453    /// A run that would take more fails with
454    /// [`GraphError::RecursionLimitExceeded`]. An
455    /// [`ExecutionConfig::with_recursion_limit`](crate::node::ExecutionConfig::with_recursion_limit)
456    /// value overrides it for one run.
457    pub fn with_recursion_limit(mut self, limit: usize) -> Self {
458        self.recursion_limit = limit;
459        self
460    }
461
462    /// Cap how many nodes execute concurrently within one super-step.
463    ///
464    /// A wide fan-out otherwise dispatches its whole frontier at once, which can
465    /// exhaust a connection pool or trip a provider rate limit. Nodes beyond the
466    /// cap wait for a slot; the dispatch order is the frontier's, sorted, so it
467    /// does not depend on timing.
468    ///
469    /// Without this the frontier runs unbounded, which stays the default.
470    pub fn with_max_concurrency(mut self, limit: usize) -> Self {
471        self.max_concurrency = Some(limit.max(1));
472        self
473    }
474
475    /// Fail the run when a node writes a channel the schema does not declare.
476    ///
477    /// An undeclared channel otherwise takes the overwrite reducer, because that
478    /// is the fallback for a name the schema does not hold. A graph that declared
479    /// a list channel and then wrote a near-miss name keeps only the last value
480    /// and reports nothing. Enforcement turns that into
481    /// [`crate::error::GraphError::UndeclaredChannel`].
482    ///
483    /// A graph that declares no channels accepts any name even under
484    /// enforcement, because there is nothing to check against.
485    ///
486    /// Off by default: a graph may legitimately declare the channels a caller
487    /// reads and let its nodes pass other values between themselves.
488    ///
489    /// # Example
490    ///
491    /// ```
492    /// use adk_graph::edge::{END, START};
493    /// use adk_graph::graph::StateGraph;
494    /// use adk_graph::node::NodeOutput;
495    /// use serde_json::json;
496    ///
497    /// let graph = StateGraph::with_channels(&["total"])
498    ///     .add_node_fn("sum", |_ctx| async move {
499    ///         Ok(NodeOutput::new().with_update("total", json!(3)))
500    ///     })
501    ///     .add_edge(START, "sum")
502    ///     .add_edge("sum", END)
503    ///     .compile()
504    ///     .unwrap()
505    ///     .with_strict_channels();
506    /// # let _ = graph;
507    /// ```
508    pub fn with_strict_channels(mut self) -> Self {
509        self.strict_channels = true;
510        self
511    }
512
513    /// Discards old checkpoints as the run proceeds.
514    ///
515    /// A thread otherwise accumulates one checkpoint per super-step for as long as
516    /// it lives, which costs storage and slows a `list`. The newest is always kept,
517    /// because it is the one a resume loads.
518    ///
519    /// Off by default, so an existing thread keeps its whole history and time
520    /// travel can still reach every step.
521    ///
522    /// # Example
523    ///
524    /// ```
525    /// use adk_graph::checkpoint::{MemoryCheckpointer, RetentionPolicy};
526    /// use adk_graph::edge::{END, START};
527    /// use adk_graph::graph::StateGraph;
528    /// use adk_graph::node::NodeOutput;
529    ///
530    /// let graph = StateGraph::with_channels(&["value"])
531    ///     .add_node_fn("step", |_ctx| async move { Ok(NodeOutput::new()) })
532    ///     .add_edge(START, "step")
533    ///     .add_edge("step", END)
534    ///     .compile()?
535    ///     .with_checkpointer(MemoryCheckpointer::new())
536    ///     .with_checkpoint_retention(RetentionPolicy::keep_last(20));
537    /// # let _ = graph;
538    /// # Ok::<(), adk_graph::error::GraphError>(())
539    /// ```
540    pub fn with_checkpoint_retention(mut self, policy: crate::checkpoint::RetentionPolicy) -> Self {
541        self.retention = Some(policy);
542        self
543    }
544
545    /// Applies policies to every node that does not set its own.
546    ///
547    /// Repeating the same retry or timeout across twenty nodes is easy to get
548    /// wrong by omission. A per-node value always wins over the default.
549    ///
550    /// # Example
551    ///
552    /// ```
553    /// use adk_graph::edge::{END, START};
554    /// use adk_graph::graph::{NodeDefaults, StateGraph};
555    /// use adk_graph::node::NodeOutput;
556    /// use adk_graph::retry::RetryPolicy;
557    ///
558    /// let graph = StateGraph::with_channels(&["value"])
559    ///     .add_node_fn("fetch", |_ctx| async move { Ok(NodeOutput::new()) })
560    ///     .add_edge(START, "fetch")
561    ///     .add_edge("fetch", END)
562    ///     .compile()?
563    ///     // Every node retries three times, unless it says otherwise.
564    ///     .with_node_defaults(NodeDefaults::new().with_retry(RetryPolicy::new(3)))
565    ///     // And this one gets five.
566    ///     .with_node_retry("fetch", RetryPolicy::new(5));
567    /// # let _ = graph;
568    /// # Ok::<(), adk_graph::error::GraphError>(())
569    /// ```
570    pub fn with_node_defaults(mut self, defaults: NodeDefaults) -> Self {
571        if let Some(retry) = defaults.retry {
572            self.default_retry = Some(retry);
573        }
574        if let Some(timeout) = defaults.timeout {
575            self.default_timeout = Some(timeout);
576        }
577        if let Some(handler) = defaults.error_handler {
578            self.default_error_handler = Some(handler);
579        }
580        self
581    }
582
583    /// Handles one node's failure instead of ending the run.
584    ///
585    /// Called once the node's retry budget is spent. The handler receives the node
586    /// name, the error, and the state as it stands, and returns the updates to
587    /// apply — typically recording what failed and naming a recovery node with
588    /// [`NodeOutput::with_goto`](crate::node::NodeOutput::with_goto). Returning
589    /// `Err` ends the run.
590    ///
591    /// An interrupt is never routed here: a pause is not a failure.
592    pub fn with_node_error_handler<F>(mut self, node: &str, handler: F) -> Self
593    where
594        F: Fn(&str, &GraphError, &State) -> Result<crate::node::NodeOutput> + Send + Sync + 'static,
595    {
596        self.error_handlers.insert(node.to_string(), Arc::new(handler));
597        self
598    }
599
600    /// Whether this graph holds a checkpointer.
601    pub fn has_checkpointer(&self) -> bool {
602        self.checkpointer.is_some()
603    }
604
605    /// Whether this graph declares any static interrupt gate.
606    ///
607    /// A dynamic interrupt cannot be seen from the graph, because a node decides
608    /// at run time, so this reports only the declared gates.
609    pub fn can_pause(&self) -> bool {
610        !self.interrupt_before.is_empty() || !self.interrupt_after.is_empty()
611    }
612
613    /// The failure handler for a node, per-node first, then the graph default.
614    pub(crate) fn error_handler_for(&self, node: &str) -> Option<&NodeErrorHandler> {
615        self.error_handlers.get(node).or(self.default_error_handler.as_ref())
616    }
617
618    /// Attach a retry policy to one node.
619    ///
620    /// A node with no policy is attempted once, which is the behaviour of a graph
621    /// that configures none.
622    pub fn with_node_retry(mut self, node: &str, policy: crate::retry::RetryPolicy) -> Self {
623        self.retry_policies.insert(node.to_string(), policy);
624        self
625    }
626
627    /// Declares the most consequential side effect a node can cause.
628    ///
629    /// Under [`Durability::Async`](crate::checkpoint::Durability::Async) or
630    /// [`Durability::Exit`](crate::checkpoint::Durability::Exit), a super-step that
631    /// runs a [`ToolEffect::NonIdempotent`](adk_core::ToolEffect::NonIdempotent) node
632    /// first writes every earlier checkpoint, as
633    /// [`Durability::Sync`](crate::checkpoint::Durability::Sync) does. A node that
634    /// declares nothing is not treated as having an effect.
635    ///
636    /// # Example
637    ///
638    /// ```
639    /// use adk_core::ToolEffect;
640    /// use adk_graph::edge::{END, START};
641    /// use adk_graph::graph::StateGraph;
642    /// use adk_graph::node::NodeOutput;
643    ///
644    /// # fn build() -> adk_graph::Result<()> {
645    /// let graph = StateGraph::with_channels(&["receipt"])
646    ///     .add_node_fn("charge", |_ctx| async { Ok(NodeOutput::new()) })
647    ///     .add_edge(START, "charge")
648    ///     .add_edge("charge", END)
649    ///     .compile()?
650    ///     .with_node_effect("charge", ToolEffect::NonIdempotent);
651    /// # let _ = graph;
652    /// # Ok(())
653    /// # }
654    /// ```
655    pub fn with_node_effect(mut self, node: &str, effect: adk_core::ToolEffect) -> Self {
656        self.node_effects.insert(node.to_string(), effect);
657        self
658    }
659
660    /// A node by name, for a caller that needs to run one on its own.
661    pub fn node(&self, name: &str) -> Option<Arc<dyn Node>> {
662        self.nodes.get(name).cloned()
663    }
664
665    /// The declared state channel names, sorted.
666    pub fn state_channels(&self) -> Vec<String> {
667        let mut names: Vec<String> = self.schema.channels.keys().cloned().collect();
668        names.sort();
669        names
670    }
671
672    /// The retry policy for a node.
673    ///
674    /// The per-node policy wins; otherwise the graph's default applies. `None`
675    /// when neither is set, which means one attempt.
676    pub(crate) fn retry_policy_for(&self, node: &str) -> Option<&crate::retry::RetryPolicy> {
677        self.retry_policies.get(node).or(self.default_retry.as_ref())
678    }
679
680    /// Get the effective timeout policy for a node.
681    ///
682    /// Returns the per-node policy if one was configured via
683    /// `GraphAgentBuilder::node_timeout`, otherwise falls back to the
684    /// default timeout policy. Returns `None` if neither is set.
685    pub fn timeout_policy_for(&self, node_name: &str) -> Option<&crate::timeout::TimeoutPolicy> {
686        self.timeout_policies.get(node_name).or(self.default_timeout.as_ref())
687    }
688
689    /// Get entry nodes
690    pub fn get_entry_nodes(&self) -> Vec<String> {
691        for edge in &self.edges {
692            if let Edge::Entry { targets } = edge {
693                return targets.clone();
694            }
695        }
696        vec![]
697    }
698
699    /// Get next nodes after executing the given nodes
700    /// # Errors
701    ///
702    /// Returns [`GraphError::UnknownRouteTarget`] when a router answers with a
703    /// key that is not among the declared targets. A route to `END` is declared,
704    /// so it is not an error; a key nobody declared is, because the branch would
705    /// otherwise stop and the run would report success having skipped the work.
706    pub fn get_next_nodes(&self, executed: &[String], state: &State) -> Result<Vec<String>> {
707        let mut next = Vec::new();
708        for (_, target) in self.routes_from(executed, state)? {
709            if !next.contains(&target) {
710                next.push(target);
711            }
712        }
713        Ok(next)
714    }
715
716    /// Each `(source, target)` pair the executed nodes' edges route along, in
717    /// edge declaration order.
718    ///
719    /// A fan-in node counts an arrival only from a source that routed to it, so
720    /// the pairs are kept rather than only the targets. A route to `END` yields
721    /// no pair.
722    ///
723    /// # Errors
724    ///
725    /// Returns [`GraphError::UnknownRouteTarget`] on an undeclared route key, as
726    /// [`Self::get_next_nodes`] does.
727    pub(crate) fn routes_from(&self, executed: &[String], state: &State) -> Result<Vec<Route>> {
728        let mut routes: Vec<Route> = Vec::new();
729        let mut push = |source: &String, target: &String| {
730            if !routes.iter().any(|(s, t)| s == source && t == target) {
731                routes.push((source.clone(), target.clone()));
732            }
733        };
734
735        for edge in &self.edges {
736            match edge {
737                Edge::Direct { source, target: EdgeTarget::Node(n) }
738                    if executed.contains(source) =>
739                {
740                    push(source, n);
741                }
742                Edge::Conditional { source, router, targets } if executed.contains(source) => {
743                    let route = router(state);
744                    match targets.get(&route) {
745                        Some(EdgeTarget::Node(n)) => push(source, n),
746                        // Declared, and the end of this branch.
747                        Some(EdgeTarget::End) => {}
748                        None => {
749                            return Err(GraphError::UnknownRouteTarget(format!(
750                                "node '{source}' routed to '{route}', which is not a declared target. Declared: {declared:?}",
751                                declared = {
752                                    let mut keys: Vec<&str> =
753                                        targets.keys().map(String::as_str).collect();
754                                    keys.sort_unstable();
755                                    keys
756                                }
757                            )));
758                        }
759                    }
760                }
761                _ => {}
762            }
763        }
764
765        Ok(routes)
766    }
767
768    /// Every node one declared edge leads to from each node, counting every
769    /// target of a conditional edge.
770    ///
771    /// Used to decide whether a fan-in predecessor can still run, so a `goto`
772    /// to a node no edge reaches is not anticipated.
773    pub(crate) fn successor_map(&self) -> HashMap<&str, Vec<&str>> {
774        let mut successors: HashMap<&str, Vec<&str>> = HashMap::new();
775        for edge in &self.edges {
776            match edge {
777                Edge::Direct { source, target } => {
778                    if let Some(target) = target.node_name() {
779                        successors.entry(source.as_str()).or_default().push(target);
780                    }
781                }
782                Edge::Conditional { source, targets, .. } => {
783                    let entry = successors.entry(source.as_str()).or_default();
784                    entry.extend(targets.values().filter_map(EdgeTarget::node_name));
785                }
786                Edge::Entry { .. } => {}
787            }
788        }
789        successors
790    }
791
792    /// Reports the conditional dispatches the executed nodes produce.
793    ///
794    /// Only conditional edges appear: a direct edge involves no decision. Used
795    /// for [`StreamEvent::RouteDispatched`](crate::stream::StreamEvent::RouteDispatched),
796    /// and called only when a caller asked for the debug stream, so a router is
797    /// not evaluated again on the common path.
798    ///
799    /// # Errors
800    ///
801    /// Returns [`GraphError::UnknownRouteTarget`] on an undeclared route key,
802    /// matching [`Self::get_next_nodes`].
803    pub fn route_dispatches(
804        &self,
805        executed: &[String],
806        state: &State,
807    ) -> Result<Vec<(String, Vec<String>)>> {
808        let mut dispatches = Vec::new();
809        for edge in &self.edges {
810            if let Edge::Conditional { source, router, targets } = edge
811                && executed.contains(source)
812            {
813                let route = router(state);
814                match targets.get(&route) {
815                    Some(EdgeTarget::Node(n)) => {
816                        dispatches.push((source.clone(), vec![n.clone()]));
817                    }
818                    Some(_) => dispatches.push((source.clone(), Vec::new())),
819                    None => {
820                        return Err(GraphError::UnknownRouteTarget(format!(
821                            "node '{source}' routed to '{route}', which is not a declared target"
822                        )));
823                    }
824                }
825            }
826        }
827        Ok(dispatches)
828    }
829
830    /// Check if any of the executed nodes lead to END
831    pub fn leads_to_end(&self, executed: &[String], state: &State) -> bool {
832        for edge in &self.edges {
833            match edge {
834                Edge::Direct { source, target } if executed.contains(source) && target.is_end() => {
835                    return true;
836                }
837                Edge::Conditional { source, router, targets } if executed.contains(source) => {
838                    let route = router(state);
839                    if route == END {
840                        return true;
841                    }
842                    if let Some(target) = targets.get(&route)
843                        && target.is_end()
844                    {
845                        return true;
846                    }
847                }
848                _ => {}
849            }
850        }
851        false
852    }
853
854    /// Get all upstream source nodes for a given target node.
855    ///
856    /// Returns the names of all nodes that have an edge pointing to the given
857    /// target node. This is used by the deferred node scheduler to determine
858    /// which upstream paths must complete before a fan-in node can execute.
859    ///
860    /// For conditional edges, all possible source nodes are included since any
861    /// of them could route to the target at runtime.
862    pub fn get_upstream_nodes(&self, target_node: &str) -> Vec<String> {
863        let mut sources = Vec::new();
864
865        for edge in &self.edges {
866            match edge {
867                Edge::Direct { source, target } => {
868                    if let EdgeTarget::Node(name) = target
869                        && name == target_node
870                        && !sources.contains(source)
871                    {
872                        sources.push(source.clone());
873                    }
874                }
875                Edge::Conditional { source, targets, .. } => {
876                    for target in targets.values() {
877                        if let EdgeTarget::Node(name) = target
878                            && name == target_node
879                            && !sources.contains(source)
880                        {
881                            sources.push(source.clone());
882                        }
883                    }
884                }
885                Edge::Entry { targets } => {
886                    if targets.contains(&target_node.to_string()) {
887                        // Entry nodes come from START, which is not a real node
888                        // so we don't add it as an upstream source
889                    }
890                }
891            }
892        }
893
894        sources
895    }
896
897    /// Get the state schema
898    pub fn schema(&self) -> &StateSchema {
899        &self.schema
900    }
901
902    /// Get the checkpointer if configured
903    pub fn checkpointer(&self) -> Option<&Arc<dyn Checkpointer>> {
904        self.checkpointer.as_ref()
905    }
906}
907
908#[cfg(test)]
909mod tests {
910    use super::*;
911    use serde_json::json;
912
913    #[test]
914    fn test_basic_graph_construction() {
915        let graph = StateGraph::with_channels(&["input", "output"])
916            .add_node_fn("process", |_ctx| async { Ok(NodeOutput::new()) })
917            .add_edge(START, "process")
918            .add_edge("process", END)
919            .compile();
920
921        assert!(graph.is_ok());
922    }
923
924    #[test]
925    fn test_graph_missing_entry() {
926        let graph = StateGraph::with_channels(&["input"])
927            .add_node_fn("process", |_ctx| async { Ok(NodeOutput::new()) })
928            .add_edge("process", END) // No START -> process edge
929            .compile();
930
931        assert!(matches!(graph, Err(GraphError::NoEntryPoint)));
932    }
933
934    #[test]
935    fn test_graph_missing_node() {
936        let graph = StateGraph::with_channels(&["input"]).add_edge(START, "nonexistent").compile();
937
938        assert!(matches!(graph, Err(GraphError::EdgeTargetNotFound(_))));
939    }
940
941    #[test]
942    fn test_conditional_edges() {
943        let graph = StateGraph::with_channels(&["next"])
944            .add_node_fn("router", |_ctx| async { Ok(NodeOutput::new()) })
945            .add_node_fn("path_a", |_ctx| async { Ok(NodeOutput::new()) })
946            .add_node_fn("path_b", |_ctx| async { Ok(NodeOutput::new()) })
947            .add_edge(START, "router")
948            .add_conditional_edges(
949                "router",
950                |state| state.get("next").and_then(|v| v.as_str()).unwrap_or(END).to_string(),
951                [("path_a", "path_a"), ("path_b", "path_b"), (END, END)],
952            )
953            .compile()
954            .unwrap();
955
956        // Test routing
957        let mut state = State::new();
958        state.insert("next".to_string(), json!("path_a"));
959        let next = graph.get_next_nodes(&["router".to_string()], &state).unwrap();
960        assert_eq!(next, vec!["path_a".to_string()]);
961
962        state.insert("next".to_string(), json!("path_b"));
963        let next = graph.get_next_nodes(&["router".to_string()], &state).unwrap();
964        assert_eq!(next, vec!["path_b".to_string()]);
965    }
966}