Skip to main content

agentmux_srv/drone/executor/scheduler/
foreach.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The for-each block: runs its body block once per item of a list
5//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md ยง3.1).
6//!
7//! The body is a block of the graph with no edges of its own (`schedule.rs`
8//! checks that), so the scheduler leaves it alone and this runs it with
9//! `{{item}}` and `{{index}}` set. The output is
10//! `{ "results": [..], "errors": [..], "count": n, "capped": bool }`:
11//! `results` holds each finished body's output in order, `errors` the items
12//! that failed when `on_item_error` is `continue`.
13//!
14//! Items run one at a time. Every limit is hard and ends the run with a reason
15//! in plain words (`on_cap: exit_loop` goes on instead, with `capped` set):
16//! `max_items` (100, at most 1,000), the run's dollar cap, and the loop's own
17//! `max_cost_usd` and `max_minutes`.
18
19use std::time::Instant;
20
21use serde_json::{json, Value};
22
23use super::{over_run_cap, Scheduler};
24use crate::drone::executor::schedule::{foreach_config, ForEachConfig, OnCap, OnItemError};
25use crate::drone::types::FlowNode;
26
27fn kind_name(v: &Value) -> &'static str {
28    match v {
29        Value::Null => "nothing",
30        Value::Bool(_) => "a boolean",
31        Value::Number(_) => "a number",
32        Value::String(_) => "text",
33        Value::Array(_) => "a list",
34        Value::Object(_) => "an object",
35    }
36}
37
38impl<'a> Scheduler<'a> {
39    pub(super) async fn run_foreach(&mut self, node: &'a FlowNode) -> Result<Value, String> {
40        let id = node.id.as_str();
41        let cfg = foreach_config(node).map_err(|e| format!("for-each {id}: {e}"))?;
42        let body = self.node_of.get(cfg.body.as_str()).copied().ok_or_else(|| format!("for-each {id}: the body {:?} is not a block", cfg.body))?;
43        let (tainted, derived) = self.scope.bits_of(&cfg.items);
44        let items = match self.scope.value_of(&cfg.items) {
45            Value::Array(items) => items,
46            other => return Err(format!("for-each {id}: items must be a list, but {} is {}", cfg.items, kind_name(&other))),
47        };
48        let total = items.len();
49        let (started, spent_before) = (Instant::now(), self.spent);
50        let mut results = Vec::new();
51        let mut errors = Vec::new();
52        let mut stopped: Option<String> = None;
53        for (index, item) in items.into_iter().enumerate() {
54            self.settle_late_spend().await;
55            if let Some(why) = self.item_limit(&cfg, id, (index, total), (started, spent_before)) {
56                stopped = Some(why);
57                break;
58            }
59            self.scope.locals.insert("item".to_string(), item);
60            self.scope.locals.insert("index".to_string(), json!(index));
61            self.scope.local_bits = (tainted, derived);
62            let outcome = Box::pin(self.run_block(body)).await;
63            self.scope.locals.clear();
64            self.scope.local_bits = (false, false);
65            match outcome {
66                Ok(output) => results.push(output),
67                Err(e) if self.cancelled => return Err(e),
68                Err(e) => match cfg.on_item_error {
69                    OnItemError::Stop => return Err(format!("for-each {id}: item {index}: {e}")),
70                    OnItemError::Continue => errors.push(json!({ "index": index, "error": e })),
71                },
72            }
73        }
74        if let Some(why) = &stopped {
75            self.cap_reached(id, why);
76            if cfg.on_cap == OnCap::EndRun {
77                return Err(why.clone());
78            }
79        }
80        // The body's spend counts as the for-each's own, so a loop that holds the
81        // for-each sees it against its cap (`loop_cap` sums the cycle's blocks).
82        *self.spent_by.entry(id).or_default() += self.spent - spent_before;
83        let (body_tainted, body_derived) = self.scope.bits.get(body.id.as_str()).copied().unwrap_or((false, false));
84        let any_tainted = tainted || body_tainted;
85        self.scope.bits.insert(node.id.clone(), (any_tainted, !any_tainted && (derived || body_derived)));
86        Ok(json!({ "results": results, "errors": errors, "count": results.len() + errors.len(), "capped": stopped.is_some(), "capped_reason": stopped }))
87    }
88
89    /// Why the next item must not run, in plain words, or `None`.
90    fn item_limit(&self, cfg: &ForEachConfig, id: &str, (index, total): (usize, usize), (started, spent_before): (Instant, f64)) -> Option<String> {
91        if index >= cfg.max_items {
92            return Some(format!("stopped after {} of {total} items: the for-each {id} allows at most {}", cfg.max_items, cfg.max_items));
93        }
94        if let Some(stopped) = over_run_cap(self.spent, self.run_cap_usd) {
95            return Some(stopped);
96        }
97        let spent = self.spent - spent_before;
98        if let Some(max) = cfg.max_cost_usd.filter(|max| crate::backend::jobs::caps::reached(spent, *max)) {
99            return Some(format!("stopped: the for-each {id} spent ${spent:.2} after {index} of {total} items, its cap of ${max:.2}"));
100        }
101        let minutes = started.elapsed().as_secs_f64() / 60.0;
102        cfg.max_minutes.filter(|max| minutes >= *max).map(|max| format!("stopped: the for-each {id} ran {minutes:.1} minutes ({index} of {total} items), its cap of {max} minutes"))
103    }
104}