agentmux_srv/drone/executor/scheduler/
parallel.rs1use std::future::Future;
23use std::pin::Pin;
24use std::time::Duration;
25
26use serde_json::{json, Value};
27
28use super::{dispatch_scoped, over_run_cap, within, Scheduler};
29use crate::drone::executor::engine::Cancel;
30use crate::drone::executor::{retry, schedule};
31use crate::drone::data_flow::ExecutionScope;
32use crate::drone::types::{BlockKind, FlowNode};
33
34pub(super) const PARALLELISM: usize = 4;
36
37pub(super) const MAX_AGENTS: usize = 1;
40
41fn is_pure(kind: BlockKind) -> bool {
43 matches!(
44 kind,
45 BlockKind::Agent | BlockKind::Api | BlockKind::Message | BlockKind::Task | BlockKind::Notify | BlockKind::AppQuery | BlockKind::Spawn | BlockKind::Transform | BlockKind::Condition
46 )
47}
48
49impl<'a> Scheduler<'a> {
50 pub(super) fn next_batch(&self) -> Vec<(&'a str, bool)> {
53 let mut batch = Vec::new();
54 let mut agents = 0;
55 for &(id, forced) in &self.ready {
56 let kind = super::kind_of(self.node_of[id]).ok().filter(|k| is_pure(*k));
57 let in_loop = self.plan.cycle_of.values().any(|group| group.contains(id));
58 let Some(kind) = kind.filter(|_| !in_loop && self.will_run(id, forced)) else { break };
59 let starts_agent = matches!(kind, BlockKind::Agent | BlockKind::Spawn);
60 if batch.len() >= PARALLELISM || (starts_agent && agents >= MAX_AGENTS) {
61 break;
62 }
63 agents += usize::from(starts_agent);
64 batch.push((id, forced));
65 }
66 batch
67 }
68
69 pub(super) async fn step_batch(&mut self, batch: Vec<(&'a str, bool)>) -> Result<(), String> {
73 if self.cancel.is_cancelled() {
74 self.cancelled = true;
75 return Err(format!("stopped: {}", self.cancel.reason()));
76 }
77 for _ in &batch {
78 if let Some((id, _)) = self.ready.pop_front() {
79 self.queued.remove(id);
80 }
81 }
82 self.settle_late_spend().await;
83 if let Some(stopped) = over_run_cap(self.spent, self.run_cap_usd) {
84 self.cap_reached(batch[0].0, &stopped);
85 return Err(stopped);
86 }
87 self.mark_batch_in_flight(&batch)?;
88 let mut began = Vec::new();
89 for (id, _) in &batch {
90 let node = self.node_of[*id];
91 let kind = super::kind_of(node)?;
92 began.push((node, kind, self.begin_block(node).await));
93 }
94 let spent_before = self.spent;
95 let runs: Vec<Pin<Box<dyn Future<Output = Pure> + Send + '_>>> = began
96 .iter()
97 .map(|(node, kind, _)| match self.stub_of(node, *kind) {
98 Some(said) => Box::pin(async move { Pure { result: said, cancelled: false, bits: None } }) as Pin<Box<dyn Future<Output = Pure> + Send + '_>>,
100 None => Box::pin(run_pure(node, *kind, self.scope.clone(), self.cancel.clone())),
101 })
102 .collect();
103 let results = futures_util::future::join_all(runs).await;
104 let mut first_failure = None;
105 for ((node, kind, started_at), pure) in began.into_iter().zip(results) {
106 self.cancelled |= pure.cancelled;
107 if let Some(bits) = pure.bits {
108 self.scope.bits.insert(node.id.clone(), bits);
109 }
110 let stubbed = self.stub_of(node, kind).is_some();
111 let ran = self.end_block(node, kind, pure.result, (started_at, spent_before)).await;
112 if stubbed && ran.is_ok() {
113 self.keep_stub_bits(&node.id);
114 }
115 if let Err(e) = self.finish_step(node, ran) {
116 first_failure.get_or_insert(e);
117 }
118 }
119 first_failure.map_or(Ok(()), Err)
120 }
121}
122
123pub(super) struct Pure {
125 pub(super) result: Result<Value, String>,
126 pub(super) cancelled: bool,
128 pub(super) bits: Option<(bool, bool)>,
130}
131
132pub(super) async fn run_pure(node: &FlowNode, kind: BlockKind, mut scope: ExecutionScope, cancel: Cancel) -> Pure {
135 let done = |result: Result<Value, String>, cancelled: bool, scope: &ExecutionScope| Pure { result, cancelled, bits: scope.bits.get(&node.id).copied() };
136 let retry = match retry::retry_of(node) {
137 Ok(retry) => retry,
138 Err(e) => return done(Err(e), false, &scope),
139 };
140 let limit = match schedule::timeout_seconds(node) {
141 Ok(Some(secs)) => Some(Duration::from_secs(secs)),
142 Ok(None) => super::default_timeout(kind),
143 Err(e) => return done(Err(e), false, &scope),
144 };
145 let mut ran = 0;
146 loop {
147 let stopped = || Err(format!("stopped: {}", cancel.reason()));
148 let result = tokio::select! {
149 biased;
150 () = cancel.cancelled() => return done(stopped(), true, &scope),
151 result = within(limit, dispatch_scoped(node, kind, &mut scope)) => result,
152 };
153 ran += 1;
154 if !retry::again(retry, kind, &result, ran) {
155 let result = match result {
156 Err(e) if ran > 1 => Err(format!("{e} (after {ran} tries)")),
157 Ok(Value::Object(mut out)) if ran > 1 => {
158 out.insert("tries".to_string(), json!(ran));
159 Ok(Value::Object(out))
160 }
161 other => other,
162 };
163 return done(result, false, &scope);
164 }
165 let wait = retry.map_or(Duration::ZERO, |r| retry::delay(&r, ran));
166 tokio::select! {
167 biased;
168 () = cancel.cancelled() => return done(stopped(), true, &scope),
169 () = tokio::time::sleep(wait) => {}
170 }
171 }
172}
173
174#[cfg(test)]
175#[path = "parallel_tests.rs"]
176mod tests;