Skip to main content

agentmux_srv/drone/executor/scheduler/
parallel.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Branches that run at the same time
5//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md ยง3.7).
6//!
7//! When a block has several successors they are ready together, and the ones that only
8//! read the run and give an output (an Agent, an API call, a Message, a Task, a Notify, an
9//! App query, a Spawn, a Transform, a Condition) run together as a *batch*: up to
10//! [`PARALLELISM`] blocks, of which at most [`MAX_AGENTS`] start an agent. The fleet's limit of
11//! three unattended agent runs counts a drone run as one run, so a run starts one agent at a
12//! time, as before, until a run can reserve shared agent capacity; the other blocks of a batch
13//! only read, call or send. Each block of a batch reads the run as it
14//! was when the batch began; their outputs are taken up one by one in the order they were
15//! readied, so what the run does next does not depend on which finished first. A block that
16//! writes the run (Variables, Response), waits, calls or loops is not batched: it runs by
17//! itself, as before.
18//!
19//! The run keeps a checkpoint that lists every block of the batch that has effects as
20//! running before any of them starts, so a restart asks about each of them in turn.
21
22use 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
34/// The most blocks that run at once.
35pub(super) const PARALLELISM: usize = 4;
36
37/// The most blocks that start an agent at once in one run. The fleet's limit of unattended agent
38/// runs counts each drone run as one, so a run that started more would exceed it with the others.
39pub(super) const MAX_AGENTS: usize = 1;
40
41/// The kinds that only read the run and give an output.
42fn 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    /// The blocks at the front of the ready list that can run together, in order: none when
51    /// the first cannot, one when only it can.
52    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    /// Run `batch`, which [`next_batch`](Self::next_batch) gave, together. Every block's
70    /// outcome is taken up even when one fails; the first failure the graph does not handle
71    /// is the run's.
72    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                // A replay does not repeat the world: the block says what it said before.
99                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
123/// What a block of a batch came to.
124pub(super) struct Pure {
125    pub(super) result: Result<Value, String>,
126    /// The run was stopped while it ran.
127    pub(super) cancelled: bool,
128    /// The bits the block set on its own output, as a Transform does.
129    pub(super) bits: Option<(bool, bool)>,
130}
131
132/// A block's code on its own copy of the run's scope: the same limit of time, the same
133/// retries and the same stop as [`Scheduler::guarded`] gives a block that runs by itself.
134pub(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;