1use std::any::Any;
19use std::sync::Arc;
20
21use futures::StreamExt;
22use gadk_agent::fiber::{self, AttemptSite, PARALLEL_WORKER_CREATOR};
23use gadk_agent::{AgentError, CancelCause, Context, ContextDelta, EventStream};
24use gadk_platform::json_kind_article;
25use gadk_session::Event;
26use parking_lot::Mutex;
27use serde_json::Value;
28use tokio::sync::{OwnedSemaphorePermit, Semaphore};
29use tokio::task::JoinSet;
30use tracing::Instrument;
31
32use crate::error::{WorkflowError, WorkflowErrorKind};
33use crate::llm::flow::context_err;
34use crate::workflow::branch::derive_sub_branch;
35use crate::workflow::nodes::AgentNode;
36use crate::workflow::scheduler::{record_node_error, start_node_span};
37use crate::workflow::{BaseNode, Node, NodeConfig, RetryConfig, calculate_delay, should_retry};
38
39pub struct ParallelWorker {
41 pub(crate) base: BaseNode,
42 pub(crate) wrapped: Arc<dyn Node>,
43 pub(crate) max_concurrency: usize,
44 pub(crate) retry_cfg: Option<RetryConfig>,
45}
46
47impl ParallelWorker {
48 pub fn new(
51 name: &str,
52 wrapped: Arc<dyn Node>,
53 max_concurrency: usize,
54 mut cfg: NodeConfig,
55 ) -> Result<Arc<ParallelWorker>, WorkflowError> {
56 if wrapped.config().retry_config.is_some() {
57 return Err(WorkflowError::new(
58 WorkflowErrorKind::Other,
59 format!(
60 "ParallelWorker {name}: wrapped node {} cannot have RetryConfig",
61 wrapped.name()
62 ),
63 ));
64 }
65 let retry_cfg = cfg.retry_config.take();
66 Ok(Arc::new(ParallelWorker {
67 base: BaseNode::new(name, "", cfg),
68 wrapped,
69 max_concurrency,
70 retry_cfg,
71 }))
72 }
73}
74
75impl Node for ParallelWorker {
76 fn name(&self) -> &str {
77 self.base.name()
78 }
79 fn description(&self) -> &str {
80 self.base.description()
81 }
82 fn config(&self) -> &NodeConfig {
83 self.base.config()
84 }
85 fn input_schema(&self) -> Option<&Value> {
86 self.base.input_schema()
87 }
88 fn output_schema(&self) -> Option<&Value> {
89 self.base.output_schema()
90 }
91 fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
92 self.base.validate_input(v)
93 }
94 fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
95 self.base.validate_output(v)
96 }
97 fn run(&self, ctx: Context, input: Value) -> EventStream {
107 let name = self.base.name().to_string();
108 let wrapped = Arc::clone(&self.wrapped);
109 let max_c = self.max_concurrency;
110 let retry = self.retry_cfg.clone();
111 Box::pin(async_stream::stream! {
112 let (worker_ctx, guard) = ctx.with_agent_cancel();
113 let items = match input {
114 Value::Array(items) => items,
115 other => {
116 yield Err(AgentError::other(format!(
117 "parallel worker {name} expects an array input, found {}",
118 json_kind_article(&other)
119 )));
120 return;
121 }
122 };
123 if items.is_empty() {
124 let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
125 ev.output = Some(Value::Array(Vec::new()));
126 yield Ok(ev);
127 return;
128 }
129 let n = items.len();
130 let sem = (max_c > 0).then(|| Arc::new(Semaphore::new(max_c)));
131 let first_err: Arc<Mutex<Option<AgentError>>> = Arc::default();
132 let token = worker_ctx.cancellation_token().clone();
133 let parent_branch = worker_ctx.branch();
135 let mut set: JoinSet<(usize, Option<Value>)> = JoinSet::new();
136 for (i, item) in items.into_iter().enumerate() {
137 let permit = match &sem {
138 Some(sem) => {
139 let acquired = tokio::select! {
140 biased;
141 () = token.cancelled() => None,
142 p = Arc::clone(sem).acquire_owned() => p.ok(),
143 };
144 match acquired {
146 Some(p) if !token.is_cancelled() => Some(p),
147 _ => continue,
148 }
149 }
150 None => {
151 if token.is_cancelled() {
152 continue;
153 }
154 None
155 }
156 };
157 let item_branch =
158 derive_sub_branch(&parent_branch, &format!("{}@{}", wrapped.name(), i + 1));
159 let item_ctx = worker_ctx.with_delta(ContextDelta {
160 branch: Some(item_branch),
161 ..ContextDelta::default()
162 });
163 let job = Worker {
164 wrapped: Arc::clone(&wrapped),
165 ctx: item_ctx,
166 retry: retry.clone(),
167 first_err: Arc::clone(&first_err),
168 };
169 let worker_fiber = fiber::spawn_child(PARALLEL_WORKER_CREATOR);
171 set.spawn(worker_fiber.scope(job.run(i, item, permit)).in_current_span());
172 }
173 let mut outputs = vec![Value::Null; n];
174 while let Some(res) = set.join_next().await {
175 match res {
176 Ok((i, Some(out))) => {
177 if let Some(slot) = outputs.get_mut(i) {
178 *slot = out;
179 }
180 }
181 Ok((_, None)) => {}
182 Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
185 Err(_) => {}
186 }
187 }
188 drop(guard);
189 let mut err = first_err.lock().take();
190 if err.is_none() && ctx.cancellation_token().is_cancelled() {
194 err = Some(context_err(&ctx));
195 }
196 if let Some(e) = err {
197 yield Err(e);
198 return;
199 }
200 let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
201 ev.output = Some(Value::Array(outputs));
202 yield Ok(ev);
203 })
204 }
205 fn as_any(&self) -> &dyn Any {
206 self
207 }
208}
209
210fn extract_output(ev: &Event) -> Option<Value> {
212 ev.output.clone().filter(|v| !v.is_null())
213}
214
215fn make_worker_output(mut outputs: Vec<Value>) -> Option<Value> {
217 match outputs.len() {
218 0 => None,
219 1 => outputs.pop(),
220 _ => Some(Value::Array(outputs)),
221 }
222}
223
224fn report_failure(first: &Mutex<Option<AgentError>>, ctx: &Context, err: AgentError) {
227 let mut g = first.lock();
228 if g.is_none() {
229 *g = Some(err);
230 ctx.cancel_with_cause(CancelCause::Canceled);
231 }
232}
233
234async fn run_wrapped_once(
238 wrapped: &Arc<dyn Node>,
239 ctx: &Context,
240 item: Value,
241) -> Result<Vec<Value>, AgentError> {
242 if wrapped.as_any().is::<AgentNode>() {
243 fiber::with_attempt(AttemptSite::Worker, run_wrapped_attempt(wrapped, ctx, item)).await
244 } else {
245 run_wrapped_attempt(wrapped, ctx, item).await
246 }
247}
248
249async fn run_wrapped_attempt(
251 wrapped: &Arc<dyn Node>,
252 ctx: &Context,
253 item: Value,
254) -> Result<Vec<Value>, AgentError> {
255 let span = start_node_span(ctx, wrapped);
256 let attempt = async {
257 let mut outputs = Vec::new();
258 let mut s = wrapped.run(ctx.clone(), item);
259 while let Some(r) = s.next().await {
260 match r {
261 Err(e) => return Err(e),
262 Ok(ev) => outputs.extend(extract_output(&ev)),
263 }
264 }
265 Ok(outputs)
266 };
267 let res = match &span {
268 Some(sp) => attempt.instrument(sp.clone()).await,
269 None => attempt.await,
270 };
271 record_node_error(span.as_ref(), res.as_ref().err(), None);
272 res
273}
274
275struct Worker {
277 wrapped: Arc<dyn Node>,
278 ctx: Context,
279 retry: Option<RetryConfig>,
280 first_err: Arc<Mutex<Option<AgentError>>>,
281}
282
283impl Worker {
284 async fn run(
287 self,
288 idx: usize,
289 item: Value,
290 _permit: Option<OwnedSemaphorePermit>,
291 ) -> (usize, Option<Value>) {
292 let mut failed_attempts = 0;
293 loop {
294 match run_wrapped_once(&self.wrapped, &self.ctx, item.clone()).await {
295 Ok(outputs) => return (idx, make_worker_output(outputs)),
296 Err(run_err) => {
297 failed_attempts += 1;
298 if let Some(cfg) = self
299 .retry
300 .as_ref()
301 .filter(|c| should_retry(c, &run_err, failed_attempts))
302 {
303 let delay = calculate_delay(cfg, failed_attempts, self.ctx.platform());
304 tokio::select! {
305 () = tokio::time::sleep(delay) => continue,
306 () = self.ctx.cancellation_token().cancelled() => {
307 report_failure(&self.first_err, &self.ctx, context_err(&self.ctx));
309 return (idx, None);
310 }
311 }
312 }
313 report_failure(&self.first_err, &self.ctx, run_err);
315 return (idx, None);
316 }
317 }
318 }
319 }
320}
321
322#[cfg(test)]
323#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
324mod tests {
325 use std::sync::Arc;
326 use std::sync::atomic::{AtomicUsize, Ordering};
327 use std::time::Duration;
328
329 use futures::StreamExt;
330 use gadk_agent::fiber::{self, AttemptSite, Fiber, PARALLEL_WORKER_CREATOR};
331 use gadk_agent::{
332 AgentConfig, AgentError, BeforeAgentCallback, CancelCause, Context, InvocationContext,
333 };
334 use gadk_session::Event;
335 use parking_lot::Mutex;
336 use serde_json::{Value, json};
337
338 use super::ParallelWorker;
339 use crate::workflow::nodes::AgentNode;
340 use crate::workflow::{Node, NodeConfig, RetryConfig, default_retry_config, function_node};
341
342 fn ctx() -> Context {
343 InvocationContext::builder().build()
344 }
345
346 fn retry(max_attempts: i32, delay: Duration) -> NodeConfig {
347 NodeConfig {
348 retry_config: Some(RetryConfig {
349 max_attempts,
350 initial_delay: delay,
351 max_delay: delay,
352 jitter: 0.0,
353 ..default_retry_config()
354 }),
355 ..NodeConfig::default()
356 }
357 }
358
359 async fn run(
360 node: &Arc<ParallelWorker>,
361 ctx: Context,
362 input: Value,
363 ) -> Vec<Result<Event, AgentError>> {
364 node.run(ctx, input).collect().await
365 }
366
367 #[tokio::test]
371 async fn agent_node_attempts_are_worker_attempts_on_the_item_fiber() {
372 type Seen = Arc<Mutex<Vec<(Fiber, Option<AttemptSite>)>>>;
373 let seen: Seen = Arc::default();
374 let seen_cb = seen.clone();
375 let before: BeforeAgentCallback = Arc::new(move |_ctx: Context| {
376 seen_cb
377 .lock()
378 .push((fiber::current(), fiber::current_attempt()));
379 Box::pin(async { Ok(None) })
380 });
381 let runs = Arc::new(AtomicUsize::new(0));
382 let runs_agent = runs.clone();
383 let agent = gadk_agent::new_agent(AgentConfig {
384 name: "flaky".into(),
385 before_agent_callbacks: vec![before],
386 run: Some(Arc::new(move |_ctx: InvocationContext| {
387 let n = runs_agent.fetch_add(1, Ordering::SeqCst);
388 Box::pin(async_stream::stream! {
389 if n == 0 {
390 yield Err(AgentError::other("flaky"));
391 }
392 })
393 })),
394 ..Default::default()
395 })
396 .unwrap();
397 let wrapped: Arc<dyn Node> = AgentNode::new(agent, NodeConfig::default()).unwrap();
398 let worker = ParallelWorker::new("pw", wrapped, 0, retry(3, Duration::ZERO)).unwrap();
399 let outer = Fiber::root();
400 let outer_id = outer.id;
401 let items = outer.scope(run(&worker, ctx(), json!(["a"]))).await;
402 assert_eq!(items.len(), 1);
403 assert!(items[0].is_ok(), "{:?}", items[0]);
404 let seen = seen.lock().clone();
405 assert_eq!(seen.len(), 2, "one record per attempt");
406 for (f, attempt) in &seen {
407 assert_eq!(*attempt, Some(AttemptSite::Worker));
408 assert_eq!(f.origin.creator, PARALLEL_WORKER_CREATOR);
409 assert_eq!(f.origin.parent, outer_id);
410 assert_ne!(f.id, outer_id);
411 }
412 assert_eq!(
413 seen[0].0.id, seen[1].0.id,
414 "a retry stays on the item's fiber"
415 );
416 }
417
418 #[tokio::test]
420 async fn the_first_failure_cancels_the_siblings_plainly() {
421 let causes: Arc<Mutex<Vec<Option<CancelCause>>>> = Arc::default();
422 let causes_node = causes.clone();
423 let wrapped = function_node::<String, String, _, _>(
424 "item",
425 move |c: Context, input: String| {
426 let causes = causes_node.clone();
427 async move {
428 if input == "fail" {
429 return Err(AgentError::other("boom"));
430 }
431 c.cancellation_token().cancelled().await;
432 causes.lock().push(c.cause());
433 Ok(input)
434 }
435 },
436 NodeConfig::default(),
437 );
438 let worker = ParallelWorker::new("pw", wrapped, 0, NodeConfig::default()).unwrap();
439 let items = run(&worker, ctx(), json!(["wait", "fail"])).await;
440 assert_eq!(items.len(), 1);
441 assert_eq!(items[0].as_ref().unwrap_err().to_string(), "boom");
442 let causes = causes.lock();
443 assert_eq!(causes.len(), 1);
444 assert!(
445 matches!(causes[0], Some(CancelCause::Canceled)),
446 "{causes:?}"
447 );
448 }
449
450 #[tokio::test(start_paused = true)]
453 async fn a_deadline_during_the_retry_delay_is_the_workers_error() {
454 let wrapped = function_node::<String, String, _, _>(
455 "item",
456 |_c: Context, _input: String| async move { Err(AgentError::other("boom")) },
457 NodeConfig::default(),
458 );
459 let worker =
460 ParallelWorker::new("pw", wrapped, 0, retry(5, Duration::from_secs(1))).unwrap();
461 let (tctx, _guard) = ctx().with_agent_timeout(Duration::from_millis(10));
462 let items = run(&worker, tctx, json!(["a"])).await;
463 assert_eq!(items.len(), 1);
464 assert!(
465 matches!(items[0], Err(AgentError::DeadlineExceeded)),
466 "{:?}",
467 items[0]
468 );
469 }
470}