Skip to main content

gadk_engine/agents/
parallel_agent.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! A parallel agent: runs its sub-agents concurrently, each in an isolated branch.
17
18use std::sync::Arc;
19
20use futures::StreamExt;
21use gadk_agent::fiber::{self, ERRGROUP_CREATOR};
22use gadk_agent::{
23    Agent, AgentConfig, AgentError, AgentState, AgentType, CancelCause, ContextDelta, EventStream,
24    InvocationContext, go_quote,
25};
26use gadk_session::Event;
27use parking_lot::Mutex;
28use tokio::sync::{mpsc, oneshot};
29use tokio::task::{JoinHandle, JoinSet};
30use tokio_util::sync::CancellationToken;
31use tracing::Instrument;
32
33use crate::agents::graph_resume::graph_resume_indexes;
34
35/// The configuration of a parallel agent.
36#[derive(Clone, Default)]
37pub struct ParallelAgentConfig {
38    /// Basic agent setup; `run` must be `None`.
39    pub agent: AgentConfig,
40}
41
42/// An agent that runs its sub-agents in parallel, each in an isolated branch. Useful when a task
43/// benefits from multiple perspectives or attempts, such as running different algorithms
44/// simultaneously or generating several responses for a later evaluation agent. The base-agent
45/// error is returned unwrapped.
46pub fn new(cfg: ParallelAgentConfig) -> Result<Arc<dyn Agent>, AgentError> {
47    if cfg.agent.run.is_some() {
48        return Err(AgentError::Config(
49            "ParallelAgent doesn't allow custom Run implementations".into(),
50        ));
51    }
52    let mut agent_cfg = cfg.agent.clone();
53    agent_cfg.run = Some(Arc::new(run));
54    gadk_agent::new_with_state(
55        agent_cfg,
56        AgentState {
57            agent_type: AgentType::ParallelAgent,
58            config: Some(Arc::new(cfg)),
59            on_before_agent_callback_event: None,
60            live: None,
61        },
62    )
63}
64
65/// A sub-agent event with its acknowledgement channel, or the group's error. `Panic` carries a
66/// sub-agent task's panic payload to the consumer, which re-raises it: a panicking sub-agent
67/// never ends the run "successfully".
68enum SubResult {
69    Event(Box<Event>, oneshot::Sender<()>),
70    Err(AgentError),
71    Panic(Box<dyn std::any::Any + Send>),
72}
73
74/// A sub-agent's error, displayed as `failed to run sub-agent "<name>": <err>` (the name is
75/// double-quoted and escaped) and carrying the original error as its source.
76#[derive(Debug)]
77struct SubAgentError {
78    name: String,
79    source: AgentError,
80}
81
82impl std::fmt::Display for SubAgentError {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        write!(
85            f,
86            "failed to run sub-agent {}: {}",
87            go_quote(&self.name),
88            self.source
89        )
90    }
91}
92
93impl std::error::Error for SubAgentError {
94    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
95        Some(&self.source)
96    }
97}
98
99/// Cleanup when the run stream is dropped: the funnel task (which ends only after every sub-agent
100/// task has returned, its teardown included) is handed to the invocation's teardown registry
101/// instead of being aborted, so the runner's after-run callbacks wait for every branch. Without
102/// a registry it is detached.
103struct AwaitBranchesOnDrop {
104    ctx: InvocationContext,
105    funnel: Option<JoinHandle<()>>,
106}
107
108impl Drop for AwaitBranchesOnDrop {
109    fn drop(&mut self) {
110        if let Some(funnel) = self.funnel.take() {
111            self.ctx.register_teardown(funnel);
112        }
113    }
114}
115
116/// Acknowledges an event when dropped: the ack is sent when the consumer asks for the next item,
117/// or when it drops the stream at this event.
118struct AckOnDrop(Option<oneshot::Sender<()>>);
119
120impl Drop for AckOnDrop {
121    fn drop(&mut self) {
122        if let Some(ack) = self.0.take() {
123            let _ = ack.send(());
124        }
125    }
126}
127
128/// Runs the sub-agents concurrently and streams their events.
129///
130/// Every sub-agent runs in its own task (on a fresh fiber spawned with [`ERRGROUP_CREATOR`]) on a
131/// context with branch `<parent>.<sub>` (prefixed with the current branch when there is one), the
132/// same invocation, and the group's cancel scope (a cancel-with-cause child of the run context).
133/// Each event is handed to the consumer with an acknowledgement, and the sub-agent does not
134/// continue until the consumer asks for the next item, i.e. after it has processed the event (for
135/// the runner: after plugins and the session append). The first sub-agent error, wrapped as
136/// `failed to run sub-agent "<name>": <err>`, cancels the group with that error as its cause
137/// (`CancelCause::Error`, the same `Arc` the yielded error carries) and is yielded once every
138/// sub-agent has finished; once every sub-agent has returned, the group is cancelled plainly
139/// (the first cause wins). A sub-agent panic cancels the group plainly and is
140/// re-raised on the consumer's poll (`resume_unwind`, as the dynamic scheduler surfaces node
141/// panics) once every sub-agent has finished. Dropping the stream (an early stop)
142/// acknowledges the event the consumer stopped on, cancels the group plainly and hands the
143/// funnel, which waits for every sub-agent task to return, to the invocation's teardown
144/// registry ([`InvocationContext::register_teardown`]): no sub-agent task is aborted, and the
145/// runner's after-run callbacks run once they have all torn down.
146fn run(ctx: InvocationContext) -> EventStream {
147    Box::pin(async_stream::stream! {
148        let cur = ctx.agent();
149        // One cancel scope serves as both the run's and the group's (the early-stop cancel is
150        // plain, so the group reads `Canceled` either way); the guard cancels it plainly on early
151        // stop.
152        let (group_ctx, _cancel_on_drop) = ctx.clone().into_context().with_agent_cancel();
153        let group = group_ctx.cancellation_token().clone();
154        let (tx, mut rx) = mpsc::channel::<SubResult>(1);
155        // The first error, kept once: the shared value the cancel cause carries.
156        let first_err: Arc<Mutex<Option<CancelCause>>> = Arc::new(Mutex::new(None));
157        let mut set = JoinSet::new();
158        // Resuming a nested graph workflow runs only the sub-agents holding the callers.
159        let mut sub_agents: Vec<Arc<dyn Agent>> = cur.sub_agents().to_vec();
160        if let Some(ix) = graph_resume_indexes(&ctx) {
161            sub_agents = ix.iter().filter_map(|&i| sub_agents.get(i).cloned()).collect();
162        }
163        for sa in &sub_agents {
164            let mut branch = format!("{}.{}", cur.name(), sa.name());
165            if !ctx.branch().is_empty() {
166                branch = format!("{}.{}", ctx.branch(), branch);
167            }
168            // Each sub-context is built from only the artifacts, memory, session, branch,
169            // isolation scope, agent, user content, run config and invocation id: a fresh,
170            // not-ended end flag (ending one branch does not end its siblings) and zero path, run
171            // id, resumed inputs and output-for-ancestors. The parent's isolation scope is kept: a
172            // workflow node stamps it on every event the branches emit and the LLM history filter
173            // matches it exactly, so an unscoped branch would lose its own turns.
174            // The context shares the group's cancel scope.
175            let sub_ctx = group_ctx.as_invocation().with_delta(ContextDelta {
176                fresh_invocation: true,
177                agent: Some(Arc::clone(sa)),
178                branch: Some(branch),
179                isolation_scope: Some(ctx.isolation_scope()),
180                ..Default::default()
181            });
182            let (sa, tx, group, first_err) = (Arc::clone(sa), tx.clone(), group.clone(), first_err.clone());
183            // A fiber started here, by the fiber running the agent.
184            let branch_fiber = fiber::spawn_child(ERRGROUP_CREATOR);
185            set.spawn(branch_fiber.scope(async move {
186                if let Err(e) = run_sub_agent(sub_ctx.clone(), sa.clone(), tx, group).await {
187                    let wrapped = CancelCause::Error(Arc::new(SubAgentError {
188                        name: sa.name().to_string(),
189                        source: e,
190                    }));
191                    // The first error is kept and cancels the group with it as the cause (a
192                    // no-op if the group was already cancelled).
193                    let mut first = first_err.lock();
194                    if first.is_none() {
195                        *first = Some(wrapped.clone());
196                        drop(first);
197                        sub_ctx.cancel_with_cause(wrapped);
198                    }
199                }
200            }).in_current_span());
201        }
202        // The funnel: once every sub-agent has finished, report the first error; the channel
203        // closes when the funnel and every sub-agent have dropped their senders.
204        let funnel_group = group_ctx.clone();
205        let funnel = tokio::spawn(async move {
206            let mut panic = None;
207            while let Some(res) = set.join_next().await {
208                if let Err(je) = res
209                    && je.is_panic()
210                {
211                    // Stop the siblings; the panic is re-raised once they have torn down.
212                    funnel_group.cancel_with_cause(CancelCause::Canceled);
213                    panic.get_or_insert(je.into_panic());
214                }
215            }
216            // Once every branch returned the group is cancelled: plainly when no branch failed;
217            // the first cause wins otherwise.
218            funnel_group.cancel_with_cause(CancelCause::Canceled);
219            if let Some(p) = panic {
220                if tx.send(SubResult::Panic(p)).await.is_err() {
221                    // Stopped early: nobody is left to re-raise it.
222                    tracing::warn!("adk: a parallel agent branch panicked after an early stop");
223                }
224                return;
225            }
226            let err = first_err.lock().take();
227            if let Some(e) = err {
228                // The yielded error holds the same `Arc` as the group's cause.
229                let _ = tx.send(SubResult::Err(e.to_agent_error())).await;
230            }
231        }.in_current_span());
232        // Declared after `_cancel_on_drop`, so a drop registers the funnel before the group is
233        // cancelled (locals drop in reverse order; both happen before the runner's guard).
234        let _await_branches = AwaitBranchesOnDrop { ctx: ctx.clone(), funnel: Some(funnel) };
235        while let Some(res) = rx.recv().await {
236            match res {
237                SubResult::Event(ev, ack) => {
238                    // Released when the consumer asks for the next item, i.e. after it has
239                    // processed this one, or when it drops the stream here: the innermost
240                    // local, so the ack is sent before the group is cancelled.
241                    let _ack = AckOnDrop(Some(ack));
242                    yield Ok(*ev);
243                }
244                SubResult::Err(e) => yield Err(e),
245                SubResult::Panic(p) => std::panic::resume_unwind(p),
246            }
247        }
248    })
249}
250
251/// Runs one sub-agent, forwarding its events. `Ok(())` also covers "the consumer went away".
252async fn run_sub_agent(
253    ctx: InvocationContext,
254    agent: Arc<dyn Agent>,
255    tx: mpsc::Sender<SubResult>,
256    group: CancellationToken,
257) -> Result<(), AgentError> {
258    let mut events = agent.run(ctx);
259    while let Some(item) = events.next().await {
260        let event = item?;
261        let (ack_tx, ack_rx) = oneshot::channel();
262        tokio::select! {
263            biased;
264            _ = group.cancelled() => return Err(AgentError::Cancelled),
265            sent = tx.send(SubResult::Event(Box::new(event), ack_tx)) => if sent.is_err() { return Ok(()); },
266        }
267        // Wait for the consumer to finish processing before continuing. A ready ack wins over
268        // the group's cancellation: a consumer that stops on this event acknowledges it before
269        // cancelling the group, and the sub-agent, parked in the select, wakes on the ack.
270        tokio::select! {
271            biased;
272            acked = ack_rx => if acked.is_err() { return Ok(()); },
273            _ = group.cancelled() => return Err(AgentError::Cancelled),
274        }
275    }
276    Ok(())
277}
278
279#[cfg(test)]
280#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
281mod tests {
282    use std::sync::Arc;
283
284    use futures::StreamExt;
285    use gadk_agent::{Agent, AgentConfig, ContextDelta, InvocationContext};
286    use gadk_genai::{Content, ROLE_MODEL};
287    use gadk_session::Event;
288    use parking_lot::Mutex;
289
290    use gadk_agent::fiber::{self, ERRGROUP_CREATOR, Fiber};
291    use gadk_agent::{AgentError, CancelCause, SharedCauseError};
292
293    use super::{ParallelAgentConfig, new, run};
294
295    fn parallel(sub_agents: Vec<Arc<dyn Agent>>) -> Arc<dyn Agent> {
296        new(ParallelAgentConfig {
297            agent: AgentConfig {
298                name: "par".into(),
299                sub_agents,
300                ..Default::default()
301            },
302        })
303        .unwrap()
304    }
305
306    /// What a sub-agent's run observed: (isolation scope, ended, path, branch).
307    type Seen = Arc<Mutex<Option<(String, bool, String, String)>>>;
308
309    #[tokio::test]
310    async fn sub_agent_context_is_a_fresh_invocation() {
311        let seen: Seen = Arc::new(Mutex::new(None));
312        let seen2 = seen.clone();
313        let sub = gadk_agent::new_agent(AgentConfig {
314            name: "sub".into(),
315            run: Some(Arc::new(move |ctx: InvocationContext| {
316                let c = ctx.clone().into_context();
317                *seen2.lock() = Some((ctx.isolation_scope(), ctx.ended(), c.path(), ctx.branch()));
318                let mut ev = Event::default();
319                ev.response.content = Some(Content::from_text("hi", ROLE_MODEL));
320                futures::stream::iter(vec![Ok(ev)]).boxed()
321            })),
322            ..Default::default()
323        })
324        .unwrap();
325        let par = parallel(vec![sub]);
326        // The parent is scoped, ended and carries a node path; Go's parallel child keeps only the
327        // isolation scope (Go 543edd3d).
328        let parent = InvocationContext::builder()
329            .agent(par.clone())
330            .isolation_scope("scope-1")
331            .build()
332            .with_delta(ContextDelta {
333                path: Some("wf@1/par@1".into()),
334                ..Default::default()
335            });
336        parent.end_invocation();
337        // Call the run function directly: the agent wrapper would skip an ended invocation.
338        let items: Vec<_> = run(parent.as_invocation().clone()).collect().await;
339        assert_eq!(items.len(), 1);
340        assert!(items[0].is_ok());
341        assert_eq!(
342            seen.lock().clone(),
343            Some((
344                "scope-1".to_string(),
345                false,
346                String::new(),
347                "par.sub".to_string()
348            ))
349        );
350    }
351
352    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
353    async fn panicking_sub_agent_panics_the_run() {
354        let sub = gadk_agent::new_agent(AgentConfig {
355            name: "boom".into(),
356            run: Some(Arc::new(|_ctx: InvocationContext| {
357                Box::pin(async_stream::stream! {
358                    if true {
359                        panic!("sub-agent exploded");
360                    }
361                    yield Ok(Event::default());
362                })
363            })),
364            ..Default::default()
365        })
366        .unwrap();
367        let par = parallel(vec![sub]);
368        let ictx = InvocationContext::builder()
369            .agent(par.clone())
370            .build_invocation();
371        let handle = tokio::spawn(async move { par.run(ictx).collect::<Vec<_>>().await });
372        let err = handle.await.expect_err("the run must not end successfully");
373        assert!(err.is_panic());
374        let payload = err.into_panic();
375        let msg = payload
376            .downcast_ref::<&str>()
377            .map(|s| s.to_string())
378            .or_else(|| payload.downcast_ref::<String>().cloned())
379            .unwrap_or_default();
380        assert_eq!(msg, "sub-agent exploded");
381    }
382
383    /// A sub-agent that records the fiber and context its run sees, then ends (`fail`: with an
384    /// error) or waits for the group to be cancelled first (`wait`).
385    fn recorder(
386        name: &str,
387        behaviour: &'static str,
388        seen: Arc<Mutex<Vec<(String, Fiber, InvocationContext)>>>,
389    ) -> Arc<dyn Agent> {
390        let name_owned = name.to_string();
391        gadk_agent::new_agent(AgentConfig {
392            name: name.into(),
393            run: Some(Arc::new(move |ctx: InvocationContext| {
394                let (seen, name) = (seen.clone(), name_owned.clone());
395                Box::pin(async_stream::stream! {
396                    seen.lock().push((name, fiber::current(), ctx.clone()));
397                    match behaviour {
398                        "fail" => yield Err(AgentError::other("boom")),
399                        "wait" => ctx.cancellation_token().cancelled().await,
400                        _ => {}
401                    }
402                })
403            })),
404            ..Default::default()
405        })
406        .unwrap()
407    }
408
409    /// R7: a failing branch cancels the group with `CancelCause::Error` carrying the wrapped
410    /// `failed to run sub-agent "<name>": <err>` error — the same value the run yields.
411    #[tokio::test]
412    async fn a_failing_branch_cancels_the_group_with_the_wrapped_error() {
413        let seen = Arc::default();
414        let par = parallel(vec![
415            recorder("waiter", "wait", Arc::clone(&seen)),
416            recorder("failer", "fail", Arc::clone(&seen)),
417        ]);
418        let parent = InvocationContext::builder()
419            .agent(par.clone())
420            .build_invocation();
421        let items: Vec<_> = run(parent.clone()).collect().await;
422        assert_eq!(items.len(), 1);
423        let err = items[0].as_ref().unwrap_err();
424        let want = r#"failed to run sub-agent "failer": boom"#;
425        assert_eq!(err.to_string(), want);
426        let seen = seen.lock();
427        assert_eq!(seen.len(), 2);
428        for (name, _, ctx) in seen.iter() {
429            match ctx.cause() {
430                Some(CancelCause::Error(e)) => {
431                    assert_eq!(e.to_string(), want, "{name}");
432                    let AgentError::Other(yielded) = err else {
433                        panic!("{err:?}");
434                    };
435                    let shared = yielded.downcast_ref::<SharedCauseError>().unwrap();
436                    assert!(
437                        Arc::ptr_eq(&shared.0, &e),
438                        "{name}: the cause is the yielded error"
439                    );
440                }
441                other => panic!("{name}: cause = {other:?}"),
442            }
443        }
444        assert!(parent.cause().is_none(), "the run context stays live");
445    }
446
447    /// R7 (errgroup `Wait`): once every branch returned without error the group reads a plain
448    /// `Canceled`, while the run context stays live.
449    #[tokio::test]
450    async fn the_group_is_cancelled_plainly_after_every_branch_returned() {
451        let seen = Arc::default();
452        let par = parallel(vec![
453            recorder("a", "ok", Arc::clone(&seen)),
454            recorder("b", "ok", Arc::clone(&seen)),
455        ]);
456        let parent = InvocationContext::builder()
457            .agent(par.clone())
458            .build_invocation();
459        let items: Vec<_> = run(parent.clone()).collect().await;
460        assert!(items.is_empty());
461        for (name, _, ctx) in seen.lock().iter() {
462            assert!(matches!(ctx.cause(), Some(CancelCause::Canceled)), "{name}");
463        }
464        assert!(parent.cause().is_none());
465    }
466
467    /// R3: each branch runs on its own fiber started (`ERRGROUP_CREATOR`) by the fiber polling
468    /// the run.
469    #[tokio::test]
470    async fn every_branch_runs_on_an_errgroup_fiber() {
471        let seen = Arc::default();
472        let par = parallel(vec![
473            recorder("a", "ok", Arc::clone(&seen)),
474            recorder("b", "ok", Arc::clone(&seen)),
475        ]);
476        let parent = InvocationContext::builder()
477            .agent(par.clone())
478            .build_invocation();
479        let outer = Fiber::root();
480        let outer_id = outer.id;
481        let _: Vec<_> = outer.scope(run(parent).collect::<Vec<_>>()).await;
482        let seen = seen.lock();
483        assert_eq!(seen.len(), 2);
484        for (name, f, _) in seen.iter() {
485            assert_eq!(f.origin.creator, ERRGROUP_CREATOR, "{name}");
486            assert_eq!(f.origin.parent, outer_id, "{name}");
487        }
488        assert_ne!(seen[0].1.id, seen[1].1.id);
489    }
490}