1use 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#[derive(Clone, Default)]
37pub struct ParallelAgentConfig {
38 pub agent: AgentConfig,
40}
41
42pub 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
65enum SubResult {
69 Event(Box<Event>, oneshot::Sender<()>),
70 Err(AgentError),
71 Panic(Box<dyn std::any::Any + Send>),
72}
73
74#[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
99struct 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
116struct 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
128fn run(ctx: InvocationContext) -> EventStream {
147 Box::pin(async_stream::stream! {
148 let cur = ctx.agent();
149 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 let first_err: Arc<Mutex<Option<CancelCause>>> = Arc::new(Mutex::new(None));
157 let mut set = JoinSet::new();
158 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 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 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 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 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 funnel_group.cancel_with_cause(CancelCause::Canceled);
213 panic.get_or_insert(je.into_panic());
214 }
215 }
216 funnel_group.cancel_with_cause(CancelCause::Canceled);
219 if let Some(p) = panic {
220 if tx.send(SubResult::Panic(p)).await.is_err() {
221 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 let _ = tx.send(SubResult::Err(e.to_agent_error())).await;
230 }
231 }.in_current_span());
232 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 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
251async 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 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 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 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 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 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 #[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 #[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 #[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}