adk_graph/child.rs
1//! Invoking a node from inside another node's body.
2//!
3//! Declared edges express a topology decided before the run. A supervisor often
4//! cannot: how many workers to start, and in what order, depends on what the
5//! first one found. Both adk-python and adk-go answer this the same way, and
6//! neither mutates the graph — a node body calls other nodes directly and awaits
7//! their output.
8//!
9//! # Identity and replay
10//!
11//! Each invocation is recorded under a path, `<parent>@<step>/<child>@<run_id>`.
12//! When a parent is re-executed it runs from the top, so without a record every
13//! child would run again. A path already in the ledger returns its recorded output
14//! instead. The parent re-executes the same activation when it is retried, when it
15//! resumes after a pause, or when a failed step resumes.
16//!
17//! Only a successful invocation is recorded. A child that failed or interrupted
18//! has to run again, because its work did not finish.
19//!
20//! Invocations under one identity are single-flight: a second call made while
21//! the first is running waits for it and is served its recorded output, so a
22//! parent that starts the same child twice concurrently, under one explicit run
23//! id, runs it once. A first call that fails records nothing, so the waiting call
24//! then runs the child itself.
25//!
26//! The parent's step is part of the path, and a parent's entries are dropped once
27//! its step completes, so a parent that runs again in a later pass of a loop runs
28//! its children again rather than receiving the earlier pass's output.
29//!
30//! The default `run_id` counts invocations of that child name within one attempt
31//! of the parent, so a retried or resumed parent that asks for its children in
32//! the same order gets the same identities. **A parent whose order of calls can
33//! change between attempts must supply its own `run_id`**, or the counter will
34//! hand the same identity to a different unit of work. adk-go documents the same
35//! trap.
36//!
37//! # Retry
38//!
39//! A child with a policy set by
40//! [`with_node_retry`](crate::graph::CompiledGraph::with_node_retry) is retried
41//! under it, inside its parent's attempt. The graph's default policy is not
42//! applied to children, because the parent's own policy already retries the
43//! parent, and a retried parent is served the children that finished.
44
45use std::collections::HashMap;
46use std::sync::{Arc, Mutex};
47
48use serde_json::Value;
49
50use crate::error::{GraphError, Result};
51use crate::node::{Node, NodeContext};
52use crate::retry::RetryPolicy;
53
54/// How one child invocation behaves.
55#[derive(Debug, Clone, Default)]
56pub struct RunNodeOptions {
57 /// Stable identity for replay.
58 ///
59 /// Defaults to a counter over invocations of this child name within the
60 /// current attempt of the parent. Supply one when the parent's order of calls
61 /// can change between attempts.
62 pub run_id: Option<String>,
63}
64
65impl RunNodeOptions {
66 /// Options with an explicit run id.
67 pub fn with_run_id(run_id: impl Into<String>) -> Self {
68 Self { run_id: Some(run_id.into()) }
69 }
70}
71
72/// The machinery a [`NodeContext`] needs to invoke another node.
73///
74/// Built by the executor for each node it runs, so a node body reaches only the
75/// graph it belongs to.
76pub(crate) struct ChildInvoker {
77 /// Every node in the graph, including any reachable by no edge.
78 nodes: HashMap<String, Arc<dyn Node>>,
79 /// Retry policies set per node, applied when that node runs as a child.
80 retry_policies: HashMap<String, RetryPolicy>,
81 /// Outputs already recorded, keyed by child path. Shared with the executor so
82 /// the run's checkpoint carries them.
83 ledger: Arc<Mutex<HashMap<String, Value>>>,
84 /// The invoking node's activation, which prefixes its children's paths.
85 activation: String,
86 /// Invocations so far per child name in this attempt, for the default run id.
87 counters: Mutex<HashMap<String, u32>>,
88 /// One gate per child path, held while that child runs.
89 running: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
90}
91
92impl ChildInvoker {
93 pub(crate) fn new(
94 nodes: HashMap<String, Arc<dyn Node>>,
95 retry_policies: HashMap<String, RetryPolicy>,
96 ledger: Arc<Mutex<HashMap<String, Value>>>,
97 parent: &str,
98 step: usize,
99 ) -> Self {
100 Self {
101 nodes,
102 retry_policies,
103 ledger,
104 activation: Self::activation_prefix(parent, step),
105 counters: Mutex::new(HashMap::new()),
106 running: Mutex::new(HashMap::new()),
107 }
108 }
109
110 /// The prefix of every ledger path the activation of `parent` at `step` records.
111 pub(crate) fn activation_prefix(parent: &str, step: usize) -> String {
112 format!("{parent}@{step}/")
113 }
114
115 /// Starts a new attempt of the parent, so its children are numbered from one
116 /// again and those that finished are served from the ledger.
117 pub(crate) fn begin_attempt(&self) {
118 self.counters.lock().expect("child counters").clear();
119 }
120
121 /// The path this invocation is recorded under.
122 fn path_for(&self, child: &str, options: &RunNodeOptions) -> String {
123 let run_id = match &options.run_id {
124 Some(id) => id.clone(),
125 None => {
126 let mut counters = self.counters.lock().expect("child counters");
127 let count = counters.entry(child.to_string()).or_insert(0);
128 *count += 1;
129 count.to_string()
130 }
131 };
132 format!("{}{}@{}", self.activation, child, run_id)
133 }
134
135 /// Invoke a child and return its updates as one value.
136 pub(crate) async fn run(
137 &self,
138 child: &str,
139 input: Value,
140 options: RunNodeOptions,
141 parent: &NodeContext,
142 ) -> Result<Value> {
143 let path = self.path_for(child, &options);
144
145 // A call under an identity that is running waits for it, then reads the
146 // ledger like any later call.
147 let gate =
148 Arc::clone(self.running.lock().expect("child gates").entry(path.clone()).or_default());
149 let _running = gate.lock().await;
150
151 // A child that already completed under this identity is not run again.
152 if let Some(recorded) = self.ledger.lock().expect("child ledger").get(&path) {
153 tracing::debug!(path = %path, "child already completed, serving its recorded output");
154 return Ok(recorded.clone());
155 }
156
157 let node = self
158 .nodes
159 .get(child)
160 .ok_or_else(|| GraphError::NodeNotFound(child.to_string()))?
161 .clone();
162
163 // The child sees the parent's state, with its input merged over it.
164 let mut state = parent.state.clone();
165 if let Value::Object(map) = input {
166 for (key, value) in map {
167 state.insert(key, value);
168 }
169 }
170 let mut child_ctx = NodeContext::new(state, parent.config.clone(), parent.step);
171 if let Some(run_config) = parent.run_config() {
172 child_ctx.set_run_config(run_config);
173 }
174 if let Some(schema) = parent.parent_schema() {
175 child_ctx.set_parent_schema(schema);
176 }
177
178 let policy = self.retry_policies.get(child);
179 let mut attempts = 0;
180 let output = loop {
181 let result = node.execute(&child_ctx).await;
182 attempts += 1;
183 let Err(error) = &result else { break result };
184 let Some(policy) = policy else { break result };
185 if !policy.allows_another_attempt(attempts) || !policy.retry_on.should_retry(error) {
186 break result;
187 }
188 let delay = policy.delay_for_attempt(attempts);
189 tracing::warn!(
190 path = %path,
191 attempt = attempts,
192 max_attempts = policy.max_attempts,
193 delay_ms = delay.as_millis(),
194 error = %error,
195 "child failed, retrying after backoff"
196 );
197 tokio::time::sleep(delay).await;
198 }?;
199
200 // An interrupt is not a result: the child has not finished, so nothing is
201 // recorded and it runs again on resume.
202 if let Some(interrupt) = output.interrupt {
203 return Err(GraphError::Interrupted(Box::new(
204 crate::error::InterruptedExecution::new(
205 parent.config.thread_id.clone(),
206 String::new(),
207 interrupt,
208 child_ctx.state.clone(),
209 parent.step,
210 ),
211 )));
212 }
213
214 let value = Value::Object(output.updates.into_iter().collect());
215 self.ledger.lock().expect("child ledger").insert(path.clone(), value.clone());
216 tracing::debug!(path = %path, "child completed");
217 Ok(value)
218 }
219}