Skip to main content

agentmux_srv/drone/executor/scheduler/
call.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Drone block: a step that is another drone
5//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md ยง3.5).
6//!
7//! The callee runs inside the caller's run, on the caller's remaining budget and
8//! under its cancel, so it cannot spend more than the run that called it and
9//! stopping the run stops it. It is a child run with an id of its own, announced
10//! by `ChildStarted` and `ChildEnded`; it keeps no checkpoints of its own, because
11//! the block is a step with effects (the callee may do anything): a restart that
12//! finds it running asks what to do with it, as for any such step. What the callee's
13//! Response says is the block's `value`, and it is outside text (tainted): the
14//! boundary does not yet promise any value is clean.
15//!
16//! A drone cannot call itself, directly or through the drones it calls, and calls
17//! nest at most [`MAX_DEPTH`] deep.
18
19use std::collections::HashMap;
20use std::future::Future;
21use std::pin::Pin;
22use std::sync::Arc;
23
24use serde_json::{json, Value};
25use tokio::sync::mpsc;
26
27use super::{Limits, Scheduler};
28use crate::drone::executor::blocks::call as config;
29use crate::drone::executor::engine::{Cancel, RunEnd, RunEvent};
30use crate::backend::storage::drone_types::BlockState;
31use crate::drone::types::FlowNode;
32
33/// The deepest a chain of calls may go, the first drone counted.
34pub(crate) const MAX_DEPTH: usize = 4;
35
36/// What the callee may be given, as JSON: the same limit as a run's own input.
37const MAX_INPUT_BYTES: usize = 64 * 1024;
38
39impl<'a> Scheduler<'a> {
40    /// Call the drone `node` names and give what it came to. It is boxed, because a
41    /// callee can call too: a future that runs a run that can run it cannot say it is
42    /// `Send` without help.
43    pub(super) fn run_call<'s>(&'s mut self, node: &'a FlowNode) -> Pin<Box<dyn Future<Output = Result<Value, String>> + Send + 's>>
44    where
45        'a: 's,
46    {
47        Box::pin(self.call(node))
48    }
49
50    async fn call(&mut self, node: &'a FlowNode) -> Result<Value, String> {
51        let id = node.id.as_str();
52        let spec = config::parse(node)?;
53        let lookup = self.lookup.clone().ok_or_else(|| format!("{id}: there are no drones to call from here"))?;
54
55        // The drones above this one, then this one: none may be called again.
56        let mut chain = self.chain.clone();
57        chain.push(self.scope.drone_id.clone());
58        if chain.contains(&spec.drone) {
59            return Err(format!("{id}: drone {} cannot be called from {}: it is already running above it ({})", spec.drone, self.scope.drone_id, chain.join(" > ")));
60        }
61        if chain.len() >= MAX_DEPTH {
62            return Err(format!("{id}: drones call at most {MAX_DEPTH} deep, and this is the {} ({})", chain.len(), chain.join(" > ")));
63        }
64        let (graph, version) = lookup.graph(&spec.drone, spec.version)?;
65
66        let inputs: serde_json::Map<String, Value> = spec.inputs.iter().map(|(name, template)| (name.clone(), self.scope.value_of(template))).collect();
67        let inputs = Value::Object(inputs);
68        let size = inputs.to_string().len();
69        if size > MAX_INPUT_BYTES {
70            return Err(format!("{id}: the inputs are {size} bytes; at most {MAX_INPUT_BYTES}"));
71        }
72
73        // The callee has what the caller has left of its cap. Its cancel is its own, so that it can be
74        // stopped when the call is dropped (the block ran out of its own time), and it follows the caller.
75        let remaining = remaining_cap(self.run_cap_usd, self.spent);
76        let child_cancel = Cancel::default();
77        let _stop = StopWith::new(self.cancel.clone(), child_cancel.clone());
78        let limits = Limits { run_cap_usd: remaining, cancel: child_cancel, persist: None, chain, lookup: Some(Arc::clone(&lookup)), replay: None };
79        let child_id = uuid::Uuid::new_v4().to_string();
80        let _ = self.tx.send(RunEvent::ChildStarted {
81            run_id: self.run_id.to_string(),
82            block_id: id.to_string(),
83            child_run_id: child_id.clone(),
84            drone_id: spec.drone.clone(),
85            version,
86        });
87
88        // The callee runs as a task of its own: its own events and block states are not the
89        // caller's and go nowhere, and a stop (the shared cancel) reaches it wherever it is.
90        // It announces its own end, so that is said even when the caller is stopped first.
91        let (parent_tx, run_id, block_id) = (self.tx.clone(), self.run_id.to_string(), id.to_string());
92        let (drone, callee_run) = (spec.drone.clone(), child_id.clone());
93        let late = Arc::clone(&self.late_spend);
94        late.start(&child_id, id);
95        let task = tokio::spawn(async move {
96            let (tx, rx) = mpsc::unbounded_channel();
97            // Only its waits are said, as the call block's own: the key of a wait on an event is what ends it.
98            let said = tokio::spawn(say_waits(rx, parent_tx.clone(), run_id.clone(), block_id.clone()));
99            let states = Arc::new(tokio::sync::Mutex::new(HashMap::new()));
100            let (ended, spent) = super::execute_costed(&callee_run, (&graph, inputs, limits, &drone), &tx, &states).await;
101            drop(tx);
102            let _ = said.await;
103            let status = match &ended {
104                Ok(_) => "done",
105                Err(RunEnd::Failed(_)) => "failed",
106                Err(RunEnd::Cancelled(_)) => "cancelled",
107            };
108            // What it spent is the caller, and if the caller has gone on without waiting (the call ran out
109            // of its time) it is counted from here, at its next block.
110            let _ = parent_tx.send(RunEvent::ChildEnded { run_id, block_id, child_run_id: callee_run.clone(), status: status.to_string(), cost_usd: spent });
111            late.finish(&callee_run, spent);
112            (ended, spent)
113        });
114        let (ended, spent) = task.await.map_err(|e| format!("{id}: the called drone stopped unexpectedly: {e}"))?;
115        // Counted here, so it is not counted again from the late list.
116        self.late_spend.forget(&child_id);
117        match ended {
118            // The cost of a block that finished is counted from its output, as for any block.
119            Ok(value) => Ok(json!({ "value": value, "run_id": child_id, "version": version, "cost_usd": spent })),
120            Err(RunEnd::Failed(why)) => {
121                // What it spent before it failed was still spent.
122                self.spent += spent;
123                *self.spent_by.entry(id).or_default() += spent;
124                Err(format!("drone {} failed: {why}", spec.drone))
125            }
126            Err(RunEnd::Cancelled(why)) => {
127                self.spent += spent;
128                *self.spent_by.entry(id).or_default() += spent;
129                self.cancelled = self.cancel.is_cancelled();
130                Err(format!("stopped: {why}"))
131            }
132        }
133    }
134}
135
136/// What a callee's events say to its caller: when it waits (and for what, with the key that ends a wait
137/// on an event) and when the wait is over, put on the calling block, so the caller's run shows it waits and
138/// `resumedronewait` can be given the key. Nothing else of the callee's is passed on: its end is
139/// `ChildEnded`, and a `RunDone` of its own would end the caller's stream. A callee stopped in the middle
140/// of a wait never says it ended, so that is said when its events stop.
141async fn say_waits(mut from: mpsc::UnboundedReceiver<RunEvent>, to: mpsc::UnboundedSender<RunEvent>, run_id: String, block_id: String) {
142    let mut open = 0usize;
143    while let Some(ev) = from.recv().await {
144        match ev {
145            RunEvent::Waiting { resume_at, on, key, .. } => {
146                open += 1;
147                let _ = to.send(RunEvent::Waiting { run_id: run_id.clone(), block_id: block_id.clone(), resume_at, on, key });
148            }
149            RunEvent::WaitEnded { late, .. } => {
150                open = open.saturating_sub(1);
151                let _ = to.send(RunEvent::WaitEnded { run_id: run_id.clone(), block_id: block_id.clone(), late });
152            }
153            _ => {}
154        }
155    }
156    for _ in 0..open {
157        let _ = to.send(RunEvent::WaitEnded { run_id: run_id.clone(), block_id: block_id.clone(), late: false });
158    }
159}
160
161/// Callees whose call was given up on: they were stopped, but are still ending, and what
162/// they spent in the meantime is the caller's.
163#[derive(Default)]
164pub(super) struct LateSpend {
165    inner: std::sync::Mutex<LateInner>,
166    ended: tokio::sync::Notify,
167}
168
169#[derive(Default)]
170struct LateInner {
171    /// Callees still running, by child run: the block that called each.
172    running: HashMap<String, String>,
173    /// Callees that ended, by child run: the block and what it spent.
174    spent: HashMap<String, (String, f64)>,
175}
176
177impl LateSpend {
178    fn inner(&self) -> std::sync::MutexGuard<'_, LateInner> {
179        self.inner.lock().unwrap_or_else(|e| e.into_inner())
180    }
181
182    fn start(&self, child: &str, block: &str) {
183        self.inner().running.insert(child.to_string(), block.to_string());
184    }
185
186    fn finish(&self, child: &str, spent: f64) {
187        {
188            let mut inner = self.inner();
189            if let Some(block) = inner.running.remove(child) {
190                inner.spent.insert(child.to_string(), (block, spent));
191            }
192        }
193        self.ended.notify_waiters();
194    }
195
196    /// The caller took what the callee spent itself.
197    fn forget(&self, child: &str) {
198        let mut inner = self.inner();
199        inner.running.remove(child);
200        inner.spent.remove(child);
201    }
202
203    fn idle(&self) -> bool {
204        self.inner().running.is_empty()
205    }
206
207    fn take(&self) -> Vec<(String, f64)> {
208        self.inner().spent.drain().map(|(_, v)| v).collect()
209    }
210}
211
212/// The most the caller waits for callees it stopped to end.
213const SETTLE_LIMIT: std::time::Duration = std::time::Duration::from_secs(30);
214
215impl Scheduler<'_> {
216    /// Before more work starts: wait for the callees that were stopped when their call was
217    /// given up on, and count what they spent, so the cap and the next callee's allowance see it.
218    /// The spend is also put on the calling block's state, which is what the ledger sums.
219    pub(super) async fn settle_late_spend(&mut self) {
220        let late = Arc::clone(&self.late_spend);
221        if !late.idle() {
222            let ended = async {
223                loop {
224                    let notified = late.ended.notified();
225                    tokio::pin!(notified);
226                    notified.as_mut().enable();
227                    if late.idle() {
228                        break;
229                    }
230                    notified.await;
231                }
232            };
233            let _ = tokio::time::timeout(SETTLE_LIMIT, ended).await;
234        }
235        for (block, spent) in late.take() {
236            self.spent += spent;
237            if let Some((id, _)) = self.node_of.get_key_value(block.as_str()) {
238                *self.spent_by.entry(id).or_default() += spent;
239            }
240            add_cost(self.states, &block, spent).await;
241        }
242    }
243}
244
245/// Put `spent` on a block's state as its `cost_usd`, which is what the run's ledger row sums.
246pub(super) async fn add_cost(states: &Arc<tokio::sync::Mutex<HashMap<String, BlockState>>>, block: &str, spent: f64) {
247    if spent <= 0.0 {
248        return;
249    }
250    let mut states = states.lock().await;
251    let Some(state) = states.get_mut(block) else { return };
252    match state.output.as_mut().and_then(Value::as_object_mut) {
253        Some(out) => {
254            let had = out.get("cost_usd").and_then(Value::as_f64).unwrap_or(0.0);
255            out.insert("cost_usd".to_string(), json!(had + spent));
256        }
257        None => state.output = Some(json!({ "cost_usd": spent })),
258    }
259}
260
261/// Stops the callee when the call is dropped, and when the caller is stopped.
262struct StopWith {
263    callee: Cancel,
264    follow: tokio::task::AbortHandle,
265}
266
267impl StopWith {
268    fn new(caller: Cancel, callee: Cancel) -> Self {
269        let (from, to) = (caller, callee.clone());
270        let follow = tokio::spawn(async move {
271            from.cancelled().await;
272            to.cancel(&from.reason());
273        })
274        .abort_handle();
275        Self { callee, follow }
276    }
277}
278
279impl Drop for StopWith {
280    fn drop(&mut self) {
281        self.follow.abort();
282        self.callee.cancel("the call was stopped before it finished");
283    }
284}
285
286/// What a callee may spend: what its caller has left of its cap, none when there is no cap.
287fn remaining_cap(cap: Option<f64>, spent: f64) -> Option<f64> {
288    cap.map(|cap| (cap - spent).max(0.0))
289}
290
291#[cfg(test)]
292#[path = "call_tests.rs"]
293mod tests;