agentmux_srv/drone/executor/scheduler/
call.rs1use 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
33pub(crate) const MAX_DEPTH: usize = 4;
35
36const MAX_INPUT_BYTES: usize = 64 * 1024;
38
39impl<'a> Scheduler<'a> {
40 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 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 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 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 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 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 self.late_spend.forget(&child_id);
117 match ended {
118 Ok(value) => Ok(json!({ "value": value, "run_id": child_id, "version": version, "cost_usd": spent })),
120 Err(RunEnd::Failed(why)) => {
121 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
136async 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#[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 running: HashMap<String, String>,
173 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 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
212const SETTLE_LIMIT: std::time::Duration = std::time::Duration::from_secs(30);
214
215impl Scheduler<'_> {
216 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
245pub(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
261struct 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
286fn 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;