Skip to main content

agentmux_srv/drone/executor/
scheduler.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The step scheduler: runs a graph one block at a time, in the order its edges
5//! allow, and takes a loop round again when its guard says so
6//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md ยง3.1).
7//!
8//! A block is **ready** when every edge into it, back-edges apart, has been
9//! decided (its source ran and the edge carries the run on, or its source was
10//! skipped, or a Condition took the other branch). It **runs** when it has no
11//! such edge or at least one of them carries the run on; otherwise it is
12//! **skipped**, and so are the blocks that only it led to.
13//!
14//! A back-edge that carries the run on starts the loop's next iteration: the
15//! blocks of the cycle are cleared and its head is ready again. Where a block
16//! leaves a loop by an edge that is not taken, the decision is held until
17//! nothing else can run, because a later iteration may still take it.
18
19use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
20use std::future::Future;
21use std::sync::Arc;
22use std::time::{Duration, Instant};
23
24use serde_json::{json, Value};
25use tokio::sync::mpsc;
26
27use super::blocks;
28use super::engine::{mark_state, Cancel, RunEnd, RunEvent};
29use super::retry;
30use super::schedule::{self, Guard, OnCap, Plan};
31use crate::drone::checkpoint::{Checkpoint, GraphRef};
32use crate::drone::data_flow::ExecutionScope;
33use crate::drone::host::DroneLookup;
34use crate::drone::recorder::{Persist, Recorder};
35use crate::drone::replay::Replay;
36use crate::drone::types::{BlockKind, BlockState, DroneGraph, FlowEdge, FlowNode};
37use agentmux_common::time::now_ms;
38
39/// The code of a block that reads and writes only the run's scope.
40pub(super) async fn dispatch_scoped(node: &FlowNode, kind: BlockKind, scope: &mut ExecutionScope) -> Result<Value, String> {
41    match kind {
42        BlockKind::Variables => blocks::variables::run(node, scope).await,
43        BlockKind::Api => blocks::api::run(node, scope).await,
44        BlockKind::Condition => blocks::condition::run(node, scope).await,
45        BlockKind::Response => blocks::response::run(node, scope).await,
46        BlockKind::Agent => blocks::agent::run(node, scope).await,
47        BlockKind::Message => blocks::message::run(node, scope).await,
48        BlockKind::Task => blocks::task::run(node, scope).await,
49        BlockKind::Notify => blocks::notify::run(node, scope).await,
50        BlockKind::AppQuery => blocks::app_query::run(node, scope).await,
51        BlockKind::Spawn => blocks::spawn::run(node, scope).await,
52        BlockKind::Transform => blocks::transform::run(node, scope).await,
53        BlockKind::Run => blocks::run::run(node, scope).await,
54        BlockKind::Once => blocks::once::run(node, scope).await,
55        BlockKind::ForEach | BlockKind::Wait | BlockKind::Approval | BlockKind::Drone | BlockKind::Join => unreachable!("the scheduler runs these"),
56    }
57}
58
59/// How many earlier outputs of a block a later iteration can read as
60/// `{{block.history}}`.
61const HISTORY_LEN: usize = 50;
62
63type States = Arc<tokio::sync::Mutex<HashMap<String, BlockState>>>;
64
65/// What a run is given besides its graph: its dollar cap, the way to cancel it,
66/// and where to keep its checkpoints (none for a run that is not kept).
67#[derive(Default)]
68pub(super) struct Limits {
69    pub(super) run_cap_usd: Option<f64>,
70    pub(super) cancel: Cancel,
71    pub(super) persist: Option<Persist>,
72    /// The drones above this one when it was called by a Drone block, outermost first.
73    pub(super) chain: Vec<String>,
74    /// Where a Drone block finds the drone it calls.
75    pub(super) lookup: Option<Arc<dyn DroneLookup>>,
76    /// Set on a run that replays an earlier one: what its blocks with effects say instead of doing them.
77    pub(super) replay: Option<Arc<Replay>>,
78}
79
80/// How long a block may run when its graph does not say (`timeout_seconds`): an
81/// Agent block 15 minutes, a block that reaches outside the run 5. An API block
82/// has its own request timeout, and the rest do no waiting.
83fn default_timeout(kind: BlockKind) -> Option<Duration> {
84    match kind {
85        BlockKind::Agent => Some(Duration::from_secs(15 * 60)),
86        BlockKind::Message | BlockKind::Task | BlockKind::Notify | BlockKind::AppQuery | BlockKind::Spawn | BlockKind::Run => Some(Duration::from_secs(5 * 60)),
87        // A wait is for as long as it says, and its own `timeout_seconds` may cut it short.
88        BlockKind::Api | BlockKind::Condition | BlockKind::Once | BlockKind::Response | BlockKind::Variables | BlockKind::Transform | BlockKind::ForEach | BlockKind::Wait | BlockKind::Approval | BlockKind::Join => None,
89        // The callee has the limits of its own blocks, and the caller may set one for the whole call.
90        BlockKind::Drone => None,
91    }
92}
93
94fn plain_duration(d: Duration) -> String {
95    let secs = d.as_secs();
96    match secs {
97        s if s >= 3600 && s % 3600 == 0 => format!("{} hours", s / 3600),
98        s if s >= 60 && s % 60 == 0 => format!("{} minutes", s / 60),
99        s => format!("{s} seconds"),
100    }
101}
102
103/// `work`, or its failure when it takes longer than `limit`.
104async fn within<T>(limit: Option<Duration>, work: impl Future<Output = Result<T, String>>) -> Result<T, String> {
105    let Some(limit) = limit else { return work.await };
106    tokio::time::timeout(limit, work).await.unwrap_or_else(|_| Err(format!("timed out after {}", plain_duration(limit))))
107}
108
109/// Why the run must not start another block: what its Agent blocks have spent
110/// has reached its cap (`caps::reached`: a run that spent nothing has not
111/// reached any cap).
112pub(super) fn over_run_cap(spent: f64, cap: Option<f64>) -> Option<String> {
113    let cap = cap?;
114    crate::backend::jobs::caps::reached(spent, cap).then(|| format!("stopped: the run spent ${spent:.2}, its cap of ${cap:.2}"))
115}
116
117fn kind_of(node: &FlowNode) -> Result<BlockKind, String> {
118    let kind = node.data.get("kind").and_then(|v| v.as_str()).ok_or_else(|| format!("node {} has no `kind` field", node.id))?;
119    BlockKind::parse(kind).ok_or_else(|| format!("unknown block kind: {kind}"))
120}
121
122/// Whether `edge` carries the run on once its source has run: a Condition's
123/// edge only when its handle matches the result.
124fn carries_on(edge: &FlowEdge, source: &FlowNode, output: &Value, failed: bool) -> bool {
125    // An error edge is for a block that failed, and only it: a block that
126    // failed takes no other.
127    if edge.source_handle.as_deref() == Some("error") {
128        return failed;
129    }
130    if failed {
131        return false;
132    }
133    // A Condition and a Once both answer true or false, and their edges carry the run on by that answer.
134    if !matches!(source.data.get("kind").and_then(|v| v.as_str()), Some("condition" | "once")) {
135        return true;
136    }
137    match (edge.source_handle.as_deref(), output.get("result").and_then(|v| v.as_bool())) {
138        (Some("true"), Some(r)) => r,
139        (Some("false"), Some(r)) => !r,
140        // An edge off a Condition with no handle (a graph saved before the
141        // canvas set one) is not pruned.
142        _ => true,
143    }
144}
145
146struct Scheduler<'a> {
147    run_id: &'a str,
148    plan: Plan,
149    node_of: HashMap<&'a str, &'a FlowNode>,
150    /// The edges into a block, back-edges left out.
151    incoming: HashMap<&'a str, Vec<&'a FlowEdge>>,
152    outgoing: HashMap<&'a str, Vec<&'a FlowEdge>>,
153    /// Edges decided this pass of their loop: `true` when they carry the run on.
154    decided: HashMap<&'a str, bool>,
155    /// Blocks that ran or were skipped this pass of their loop.
156    finished: HashSet<&'a str>,
157    /// The blocks that failed this pass of their loop and whose failure the graph handled.
158    failed: HashSet<&'a str>,
159    ready: VecDeque<(&'a str, bool)>,
160    queued: HashSet<&'a str>,
161    /// Edges out of a loop that were not taken, decided when nothing can run.
162    held: Vec<&'a FlowEdge>,
163    /// How many times each guard has sent the run round its loop.
164    rounds: HashMap<&'a str, u32>,
165    loop_started: HashMap<String, Instant>,
166    spent: f64,
167    spent_by: HashMap<&'a str, f64>,
168    history: HashMap<&'a str, VecDeque<Value>>,
169    scope: ExecutionScope,
170    response: Option<Value>,
171    run_cap_usd: Option<f64>,
172    cancel: Cancel,
173    /// Set when the run ended because `cancel` did, so that is not taken for a failure.
174    cancelled: bool,
175    /// The blocks that are running while they have effects, and whether each was forced:
176    /// the ones a restart must not run again on its own.
177    in_flight: Vec<(&'a str, bool)>,
178    /// The blocks of the batch that is running and have no effects: a restart runs them again.
179    running_ro: Vec<(&'a str, bool)>,
180    /// The Wait block the run is stopped at, and whether it was forced, and what
181    /// it waits for: a time, as milliseconds since 1970, or the key of an event.
182    waiting: Option<(&'a str, bool)>,
183    deadlines: BTreeMap<String, i64>,
184    resume_on: BTreeMap<String, String>,
185    /// When the Wait block runs out of its own `timeout_seconds`.
186    wait_timeouts: BTreeMap<String, i64>,
187    /// The drones above this one (a Drone block called it), and where to find a drone to call.
188    chain: Vec<String>,
189    lookup: Option<Arc<dyn DroneLookup>>,
190    /// What callees spent that nobody was waiting for any more, by child run: counted at the next block.
191    late_spend: Arc<call::LateSpend>,
192    replay: Option<Arc<Replay>>,
193    /// Writes the run's checkpoints, with the graph version they say the run is on.
194    recorder: Option<(Recorder, GraphRef)>,
195    started: Instant,
196    /// How long the run had already run before this process took it up, when it is resumed.
197    elapsed_before_ms: u64,
198    tx: &'a mpsc::UnboundedSender<RunEvent>,
199    states: &'a States,
200}
201
202pub(super) async fn execute(
203    run_id: &str,
204    args: (&DroneGraph, Value, Limits, &str),
205    tx: &mpsc::UnboundedSender<RunEvent>,
206    states: &States,
207) -> Result<Value, RunEnd> {
208    execute_costed(run_id, args, tx, states).await.0
209}
210
211/// [`execute`], and with it what the run spent, which a caller counts against its own budget.
212pub(super) async fn execute_costed(
213    run_id: &str,
214    (graph, trigger, limits, drone_id): (&DroneGraph, Value, Limits, &str),
215    tx: &mpsc::UnboundedSender<RunEvent>,
216    states: &States,
217) -> (Result<Value, RunEnd>, f64) {
218    if graph.nodes.is_empty() {
219        return (Err(RunEnd::Failed("drone has no blocks".to_string())), 0.0);
220    }
221    let plan = match schedule::analyze(graph) {
222        Ok(plan) => plan,
223        Err(issues) => return (Err(RunEnd::Failed(issues.iter().map(|i| i.message.as_str()).collect::<Vec<_>>().join("; "))), 0.0),
224    };
225    let mut s = Scheduler::new(run_id, graph, plan, ExecutionScope::for_drone(drone_id, trigger), limits, tx, states);
226    s.seed_roots();
227    let started = s.checkpoint(None);
228    let ended = finish(&mut s, started).await;
229    (ended, s.spent)
230}
231
232/// Take up a run from its newest checkpoint, `c`, and run it to its end: the
233/// blocks that were finished stay finished and what they said is what the rest
234/// read. `graph` must be the graph the checkpoint was written on.
235pub(super) async fn resume(
236    (graph, c, limits): (&DroneGraph, &Checkpoint, Limits),
237    tx: &mpsc::UnboundedSender<RunEvent>,
238    states: &States,
239) -> Result<Value, RunEnd> {
240    let plan = schedule::analyze(graph).map_err(|issues| {
241        RunEnd::Failed(issues.iter().map(|i| i.message.as_str()).collect::<Vec<_>>().join("; "))
242    })?;
243    let mut s = Scheduler::new(&c.run_id, graph, plan, ExecutionScope::for_drone(&c.drone_id, c.trigger.clone()), limits, tx, states);
244    s.restore(c).map_err(RunEnd::Failed)?;
245    s.show_restored().await;
246    // They may have done their work before the machine stopped, and a second time
247    // would repeat it: none is run again on its own, the run waits to be told, one by one.
248    // Each stays listed until it is answered, so a checkpoint kept meanwhile still has it.
249    for (id, forced) in s.in_flight.clone() {
250        if let Err(why) = s.settle_in_flight(id, forced).await {
251            return Err(if s.cancelled { RunEnd::Cancelled(s.cancel.reason()) } else { RunEnd::Failed(why) });
252        }
253    }
254    finish(&mut s, Ok(())).await
255}
256
257/// Run a replay from `first`, the new run's first checkpoint (`replay::fork_checkpoint`), to its end.
258/// `graph` must be the graph the replayed run was on. Its own checkpoints begin at step 0.
259pub(super) async fn replay(
260    (graph, first, limits): (&DroneGraph, &Checkpoint, Limits),
261    tx: &mpsc::UnboundedSender<RunEvent>,
262    states: &States,
263) -> Result<Value, RunEnd> {
264    let plan = schedule::analyze(graph).map_err(|issues| {
265        RunEnd::Failed(issues.iter().map(|i| i.message.as_str()).collect::<Vec<_>>().join("; "))
266    })?;
267    let mut s = Scheduler::new(&first.run_id, graph, plan, ExecutionScope::for_drone(&first.drone_id, first.trigger.clone()), limits, tx, states);
268    s.restore_state(first).map_err(RunEnd::Failed)?;
269    s.show_restored().await;
270    let started = s.checkpoint(None);
271    finish(&mut s, started).await
272}
273
274/// Run what is left of a run that is set up, and say how it ended. `started` is
275/// how setting it up went: a run that could not even keep its first checkpoint
276/// ends before its first block.
277async fn finish(s: &mut Scheduler<'_>, started: Result<(), String>) -> Result<Value, RunEnd> {
278    let ran = match started {
279        Ok(()) => s.drive().await,
280        Err(e) => Err(e),
281    };
282    // However it ended (a stop included), what callees it stopped were spending is its own.
283    s.settle_late_spend().await;
284    match ran {
285        Ok(()) => Ok(s.response.take().unwrap_or(Value::Null)),
286        Err(_) if s.cancelled => Err(RunEnd::Cancelled(s.cancel.reason())),
287        Err(e) => Err(RunEnd::Failed(e)),
288    }
289}
290
291impl<'a> Scheduler<'a> {
292    fn new(
293        run_id: &'a str,
294        graph: &'a DroneGraph,
295        plan: Plan,
296        scope: ExecutionScope,
297        limits: Limits,
298        tx: &'a mpsc::UnboundedSender<RunEvent>,
299        states: &'a States,
300    ) -> Self {
301        let mut incoming: HashMap<&str, Vec<&FlowEdge>> = HashMap::new();
302        let mut outgoing: HashMap<&str, Vec<&FlowEdge>> = HashMap::new();
303        for e in &graph.edges {
304            outgoing.entry(e.source.as_str()).or_default().push(e);
305            if !plan.back_edges.contains(&e.id) {
306                incoming.entry(e.target.as_str()).or_default().push(e);
307            }
308        }
309        Self {
310            run_id,
311            plan,
312            node_of: graph.nodes.iter().map(|n| (n.id.as_str(), n)).collect(),
313            incoming,
314            outgoing,
315            decided: HashMap::new(),
316            finished: HashSet::new(),
317            failed: HashSet::new(),
318            ready: VecDeque::new(),
319            queued: HashSet::new(),
320            held: Vec::new(),
321            rounds: HashMap::new(),
322            loop_started: HashMap::new(),
323            spent: 0.0,
324            spent_by: HashMap::new(),
325            history: HashMap::new(),
326            scope,
327            response: None,
328            run_cap_usd: limits.run_cap_usd,
329            cancel: limits.cancel,
330            cancelled: false,
331            in_flight: Vec::new(),
332            running_ro: Vec::new(),
333            waiting: None,
334            deadlines: BTreeMap::new(),
335            resume_on: BTreeMap::new(),
336            wait_timeouts: BTreeMap::new(),
337            chain: limits.chain,
338            lookup: limits.lookup,
339            late_spend: Arc::default(),
340            replay: limits.replay,
341            recorder: limits.persist.map(|p| (Recorder::new(p.sink, run_id), p.graph)),
342            started: Instant::now(),
343            elapsed_before_ms: 0,
344            tx,
345            states,
346        }
347    }
348
349    /// The blocks nothing leads to are ready first.
350    fn seed_roots(&mut self) {
351        let mut roots: Vec<&str> = self.node_of.keys().copied().filter(|id| !self.plan.owned.contains(*id) && self.incoming.get(id).is_none_or(|v| v.is_empty())).collect();
352        roots.sort_unstable();
353        for id in roots {
354            self.enqueue(id, false);
355        }
356    }
357
358    /// Run blocks until none is ready and no edge is left to decide.
359    async fn drive(&mut self) -> Result<(), String> {
360        loop {
361            while !self.ready.is_empty() {
362                let batch = self.next_batch();
363                if batch.len() > 1 {
364                    self.step_batch(batch).await?;
365                    continue;
366                }
367                let Some((id, forced)) = self.ready.pop_front() else { break };
368                self.queued.remove(id);
369                self.step(id, forced).await?;
370            }
371            if self.held.is_empty() {
372                return Ok(());
373            }
374            // Nothing else can run, so the edges a loop did not take are final.
375            for edge in std::mem::take(&mut self.held) {
376                self.decide(edge, false);
377            }
378        }
379    }
380
381    fn enqueue(&mut self, id: &'a str, forced: bool) {
382        if self.finished.contains(id) || !self.queued.insert(id) {
383            return;
384        }
385        self.ready.push_back((id, forced));
386    }
387
388    /// Record an edge's outcome, and ready its target if that was the last one.
389    fn decide(&mut self, edge: &'a FlowEdge, carries: bool) {
390        self.decided.insert(edge.id.as_str(), carries);
391        if carries {
392            self.held.retain(|h| h.id != edge.id);
393        }
394        let target = edge.target.as_str();
395        if self.incoming.get(target).is_some_and(|ins| ins.iter().all(|e| self.decided.contains_key(e.id.as_str()))) {
396            self.enqueue(target, false);
397        }
398    }
399
400    /// An edge whose source has finished. A edge out of a loop that is not taken
401    /// waits, because another iteration may still take it.
402    fn leave(&mut self, edge: &'a FlowEdge, carries: bool) {
403        let leaves_loop = self.plan.cycle_of.get(edge.source.as_str()).is_some_and(|c| !c.contains(&edge.target));
404        if !carries && leaves_loop {
405            self.held.push(edge);
406        } else {
407            self.decide(edge, carries);
408        }
409    }
410
411    async fn step(&mut self, id: &'a str, forced: bool) -> Result<(), String> {
412        if self.cancel.is_cancelled() {
413            self.cancelled = true;
414            return Err(format!("stopped: {}", self.cancel.reason()));
415        }
416        let node = self.node_of[id];
417        if !self.will_run(id, forced) {
418            self.finished.insert(id);
419            self.failed.remove(id);
420            mark_state(self.states, id, BlockState { status: "skipped".to_string(), output: None, error: None, started_at: None, completed_at: Some(now_ms()) }).await;
421            for edge in self.outgoing.get(id).cloned().unwrap_or_default() {
422                if !self.plan.back_edges.contains(&edge.id) {
423                    self.leave(edge, false);
424                }
425            }
426            return Ok(());
427        }
428        self.settle_late_spend().await;
429        if let Some(stopped) = over_run_cap(self.spent, self.run_cap_usd) {
430            self.cap_reached(id, &stopped);
431            return Err(stopped);
432        }
433        // A loop's time runs from the first block of its cycle, not from the
434        // first time its guard sends the run round.
435        let guards: Vec<String> = self.plan.cycle_of.iter().filter(|(g, group)| self.plan.guards.contains_key(*g) && group.contains(id)).map(|(g, _)| g.clone()).collect();
436        for guard in guards {
437            self.loop_started.entry(guard).or_insert_with(Instant::now);
438        }
439        self.mark_in_flight(node, forced)?;
440        let waits = kind_of(node).is_ok_and(|k| matches!(k, BlockKind::Wait | BlockKind::Approval));
441        if waits {
442            self.waiting = Some((id, forced));
443        }
444        let ran = self.run_block(node).await;
445        if waits {
446            let late = ran.as_ref().is_ok_and(|o| o.get("late").and_then(Value::as_bool).unwrap_or(false));
447            self.end_wait(id, late);
448        }
449        self.finish_step(node, ran)
450    }
451
452    /// What a block came to is taken up: a failure its graph handles becomes its output, the
453    /// block is finished and the run goes on from it.
454    fn finish_step(&mut self, node: &'a FlowNode, ran: Result<Value, String>) -> Result<(), String> {
455        let id = node.id.as_str();
456        let (output, failed) = match ran {
457            Ok(output) => (output, false),
458            Err(e) if !self.cancelled && self.handles_failure(id) => {
459                // The graph has a handler for this block: its output says what
460                // went wrong, as text that came from outside, and the run goes on.
461                let output = json!({ "error": e, "failed": true });
462                self.scope.outputs.insert(id.to_string(), output.clone());
463                self.scope.bits.insert(id.to_string(), (true, false));
464                (output, true)
465            }
466            Err(e) => return Err(e),
467        };
468        self.finished.insert(id);
469        if failed {
470            self.failed.insert(id);
471        } else {
472            self.failed.remove(id);
473        }
474        self.in_flight.retain(|(b, _)| *b != id);
475        self.running_ro.retain(|(b, _)| *b != id);
476        self.route(node, &output, failed)?;
477        self.checkpoint(Some(id))
478    }
479
480    /// Whether a ready block runs: it is a root, or was forced, or an edge into it was taken, or it
481    /// is a Join that a branch failed into. Otherwise it is skipped.
482    fn will_run(&self, id: &str, forced: bool) -> bool {
483        let ins = self.incoming.get(id).map(Vec::as_slice).unwrap_or_default();
484        ins.is_empty() || forced || ins.iter().any(|e| self.decided.get(e.id.as_str()) == Some(&true)) || self.join_has_failed_branch(id)
485    }
486
487    fn has_error_edge(&self, id: &str) -> bool {
488        self.outgoing.get(id).is_some_and(|edges| edges.iter().any(|e| e.source_handle.as_deref() == Some("error")))
489    }
490
491    fn cap_reached(&self, block_id: &str, reason: &str) {
492        let _ = self.tx.send(RunEvent::CapReached { run_id: self.run_id.to_string(), block_id: block_id.to_string(), reason: reason.to_string() });
493    }
494
495    /// A block's code, ended when the run is cancelled (an Agent block's process
496    /// goes with it) or the block passes its timeout.
497    async fn guarded(&mut self, node: &'a FlowNode, kind: BlockKind) -> Result<Value, String> {
498        let retry = retry::retry_of(node)?;
499        let mut ran = 0;
500        loop {
501            let result = self.attempt(node, kind).await;
502            ran += 1;
503            if self.cancelled || !retry::again(retry, kind, &result, ran) {
504                return match result {
505                    Err(e) if ran > 1 => Err(format!("{e} (after {ran} tries)")),
506                    Ok(Value::Object(mut out)) if ran > 1 => {
507                        out.insert("tries".to_string(), json!(ran));
508                        Ok(Value::Object(out))
509                    }
510                    other => other,
511                };
512            }
513            let wait = retry.map_or(Duration::ZERO, |r| retry::delay(&r, ran));
514            let cancel = self.cancel.clone();
515            tokio::select! {
516                biased;
517                () = cancel.cancelled() => {
518                    self.cancelled = true;
519                    return Err(format!("stopped: {}", cancel.reason()));
520                }
521                () = tokio::time::sleep(wait) => {}
522            }
523        }
524    }
525
526    /// One run of a block's code, within its time limit.
527    async fn attempt(&mut self, node: &'a FlowNode, kind: BlockKind) -> Result<Value, String> {
528        // A wait keeps its own time out in the checkpoint, so a restart does not start it over.
529        let limit = match schedule::timeout_seconds(node)? {
530            _ if matches!(kind, BlockKind::Wait | BlockKind::Approval) => None,
531            Some(secs) => Some(Duration::from_secs(secs)),
532            None => default_timeout(kind),
533        };
534        let cancel = self.cancel.clone();
535        tokio::select! {
536            biased;
537            () = cancel.cancelled() => {
538                self.cancelled = true;
539                Err(format!("stopped: {}", cancel.reason()))
540            }
541            result = within(limit, self.dispatch(node, kind)) => result,
542        }
543    }
544
545    /// Hand a block to the code for its kind. A for-each runs its body block
546    /// through [`run_block`](Self::run_block), so it is handled here, not in
547    /// `blocks`.
548    async fn dispatch(&mut self, node: &'a FlowNode, kind: BlockKind) -> Result<Value, String> {
549        if kind == BlockKind::ForEach {
550            return self.run_foreach(node).await;
551        }
552        if kind == BlockKind::Wait {
553            return self.run_wait(node).await;
554        }
555        if kind == BlockKind::Approval {
556            return self.run_approval(node).await;
557        }
558        if kind == BlockKind::Drone {
559            return self.run_call(node).await;
560        }
561        if kind == BlockKind::Join {
562            return self.run_join(node);
563        }
564        dispatch_scoped(node, kind, &mut self.scope).await
565    }
566
567    /// Run one block with its events and its recorded state.
568    async fn run_block(&mut self, node: &'a FlowNode) -> Result<Value, String> {
569        let kind = kind_of(node)?;
570        self.settle_late_spend().await;
571        let started_at = self.begin_block(node).await;
572        let spent_before = self.spent;
573        // A replay does not repeat the world: a block with effects says what it said before.
574        let (stubbed, result) = match self.stub_of(node, kind) {
575            Some(said) => (true, said),
576            None => (false, self.guarded(node, kind).await),
577        };
578        let ended = self.end_block(node, kind, result, (started_at, spent_before)).await;
579        if stubbed && ended.is_ok() {
580            self.keep_stub_bits(&node.id);
581        }
582        ended
583    }
584
585    /// A block starts: its event and its running state. Gives when it started, which the
586    /// states it ends with carry too.
587    async fn begin_block(&mut self, node: &'a FlowNode) -> i64 {
588        let id = node.id.as_str();
589        let _ = self.tx.send(RunEvent::BlockStarted { run_id: self.run_id.to_string(), block_id: id.to_string() });
590        let started_at = now_ms();
591        let running = BlockState { status: "running".to_string(), output: None, error: None, started_at: Some(started_at), completed_at: None };
592        mark_state(self.states, id, running).await;
593        started_at
594    }
595
596    /// A block ends with `result`: its output is kept, its cost counted, its event and its state.
597    async fn end_block(&mut self, node: &'a FlowNode, kind: BlockKind, result: Result<Value, String>, (started_at, spent_before): (i64, f64)) -> Result<Value, String> {
598        let id = node.id.as_str();
599        let state = |status: &str, output: Option<Value>, error: Option<String>, done: bool| BlockState {
600            status: status.to_string(),
601            output,
602            error,
603            started_at: Some(started_at),
604            completed_at: done.then(now_ms),
605        };
606        // What a block spent and then failed (a callee that ran, then failed) was still spent: it
607        // is on the block's state, which is what the ledger sums.
608        // Only a Drone block: a for-each's body has put its own spend on its own state.
609        let failed_cost = (matches!(kind, BlockKind::Drone) && self.spent > spent_before).then(|| json!({ "cost_usd": self.spent - spent_before }));
610        match result {
611            Ok(mut output) => {
612                self.keep_history(id, &mut output);
613                let cost = output.get("cost_usd").and_then(Value::as_f64).unwrap_or(0.0);
614                self.spent += cost;
615                *self.spent_by.entry(id).or_default() += cost;
616                self.scope.outputs.insert(id.to_string(), output.clone());
617                self.mark_bits(node, kind);
618                let _ = self.tx.send(RunEvent::BlockDone { run_id: self.run_id.to_string(), block_id: id.to_string(), output: output.clone() });
619                mark_state(self.states, id, state("done", Some(output.clone()), None, true)).await;
620                if matches!(kind, BlockKind::Response) {
621                    // Response emits `{ "value": <resolved-template> }`; the run's
622                    // output is the bare value, not the wrapper.
623                    self.response = Some(output.get("value").cloned().unwrap_or_else(|| output.clone()));
624                }
625                Ok(output)
626            }
627            Err(e) if self.cancelled => {
628                mark_state(self.states, id, state("cancelled", failed_cost, Some(e.clone()), true)).await;
629                Err(e)
630            }
631            Err(e) => {
632                let _ = self.tx.send(RunEvent::BlockError { run_id: self.run_id.to_string(), block_id: id.to_string(), error: e.clone() });
633                mark_state(self.states, id, state("error", failed_cost, Some(e.clone()), true)).await;
634                Err(format!("block {id} failed: {e}"))
635            }
636        }
637    }
638
639    /// What a block's output is made of, for the taint bits: an Agent's answer, an
640    /// API response and a message reply are outside text; a Condition's result is
641    /// a boolean made from what it read (derived when that was tainted); a
642    /// Response is its template filled in. A Variables block sets its own.
643    fn mark_bits(&mut self, node: &FlowNode, kind: BlockKind) {
644        let read = |key: &str| node.data.get(key).and_then(Value::as_str).map(|t| self.scope.bits_of(t)).unwrap_or((false, false));
645        let bits = match kind {
646            // What a command printed is outside text, as an API response is.
647            BlockKind::Agent | BlockKind::Api | BlockKind::Message | BlockKind::AppQuery | BlockKind::Run => (true, false),
648            BlockKind::Condition => {
649                let (tainted, derived) = read("expr");
650                (false, tainted || derived)
651            }
652            // Whether a key was seen is a boolean made from what the key was read from.
653            BlockKind::Once => {
654                let (tainted, derived) = read("key");
655                (false, tainted || derived)
656            }
657            BlockKind::Response => read("template"),
658            BlockKind::Variables | BlockKind::Transform | BlockKind::ForEach => return,
659            // What an event brought is outside text; a wait for a time brings nothing.
660            BlockKind::Wait if node.data.get("on").is_some() => (true, false),
661            BlockKind::Wait => (false, false),
662            // A yes is the person's: what it gives is not outside text.
663            BlockKind::Approval => (false, false),
664            // What a callee said is outside text: nothing yet promises its outputs are clean.
665            BlockKind::Drone => (true, false),
666            BlockKind::Join => self.join_bits(&node.id),
667            BlockKind::Task | BlockKind::Notify | BlockKind::Spawn => (false, false),
668        };
669        self.scope.bits.insert(node.id.clone(), bits);
670    }
671
672    /// A block that runs again carries its earlier outputs, newest last, as
673    /// `{{block.history}}`.
674    fn keep_history(&mut self, id: &'a str, output: &mut Value) {
675        let past = self.history.entry(id).or_default();
676        if !past.is_empty() {
677            if let Some(map) = output.as_object_mut() {
678                map.insert("history".to_string(), Value::Array(past.iter().cloned().collect()));
679            }
680        }
681        let mut plain = output.clone();
682        if let Some(map) = plain.as_object_mut() {
683            map.remove("history");
684        }
685        past.push_back(plain);
686        if past.len() > HISTORY_LEN {
687            past.pop_front();
688        }
689    }
690
691    /// Send the run along the edges out of a block that ran, and count a loop's
692    /// iteration when a guard takes it round.
693    fn route(&mut self, node: &'a FlowNode, output: &Value, failed: bool) -> Result<(), String> {
694        let id = node.id.as_str();
695        let edges = self.outgoing.get(id).cloned().unwrap_or_default();
696        let mut carry: Vec<bool> = edges.iter().map(|e| carries_on(e, node, output, failed)).collect();
697        if let Some(guard) = self.plan.guards.get(id).cloned() {
698            let goes_round = edges.iter().zip(&carry).any(|(e, c)| *c && guard.loop_edges.contains(&e.id));
699            if goes_round {
700                if let Some(why) = self.loop_cap(id, &guard) {
701                    self.cap_reached(id, &why);
702                    match guard.on_cap {
703                        OnCap::EndRun => return Err(why),
704                        OnCap::ExitLoop => {
705                            // Leaving the loop takes every edge that is not one of its own,
706                            // except that an error edge is for a block that failed, and
707                            // only it (`carries_on`).
708                            for (e, c) in edges.iter().zip(carry.iter_mut()) {
709                                let error_edge = e.source_handle.as_deref() == Some("error");
710                                *c = !guard.loop_edges.contains(&e.id) && error_edge == failed;
711                            }
712                            if let Some(map) = self.scope.outputs.get_mut(id).and_then(Value::as_object_mut) {
713                                map.insert("capped".to_string(), Value::Bool(true));
714                                map.insert("capped_reason".to_string(), Value::String(why));
715                            }
716                        }
717                    }
718                } else {
719                    let rounds = self.rounds.entry(id).or_default();
720                    *rounds += 1;
721                    let _ = self.tx.send(RunEvent::LoopIteration { run_id: self.run_id.to_string(), block_id: id.to_string(), iteration: *rounds + 1 });
722                }
723            }
724        }
725        // Back-edges first: going round clears the decisions inside the loop, so
726        // an edge decided before it would be erased.
727        let (back, forward): (Vec<_>, Vec<_>) = edges.into_iter().zip(carry).partition(|(e, _)| self.plan.back_edges.contains(&e.id));
728        for (edge, carries) in back {
729            if carries {
730                self.go_round(edge);
731            }
732        }
733        for (edge, carries) in forward {
734            self.leave(edge, carries);
735        }
736        Ok(())
737    }
738
739    /// Why a loop may not go round again, in plain words, or `None`.
740    fn loop_cap(&self, id: &str, guard: &Guard) -> Option<String> {
741        let passes = self.rounds.get(id).copied().unwrap_or(0) + 1;
742        if passes >= guard.max_iterations {
743            return Some(format!("stopped after {passes} of at most {} iterations: the loop at {id} did not finish", guard.max_iterations));
744        }
745        let group = self.plan.cycle_of.get(id)?;
746        if let Some(max) = guard.max_cost_usd {
747            let spent: f64 = group.iter().map(|n| self.spent_by.get(n.as_str()).copied().unwrap_or(0.0)).sum();
748            if crate::backend::jobs::caps::reached(spent, max) {
749                return Some(format!("stopped: the loop at {id} spent ${spent:.2}, its cap of ${max:.2}"));
750            }
751        }
752        if let (Some(max), Some(since)) = (guard.max_minutes, self.loop_started.get(id)) {
753            let minutes = since.elapsed().as_secs_f64() / 60.0;
754            if minutes >= max {
755                return Some(format!("stopped: the loop at {id} ran {minutes:.1} minutes, its cap of {max} minutes"));
756            }
757        }
758        None
759    }
760
761    /// A back-edge carried the run on: the loop's blocks run again, from its head.
762    fn go_round(&mut self, back: &'a FlowEdge) {
763        let head = back.target.as_str();
764        let group = self.plan.cycle_of.get(head).cloned().unwrap_or_default();
765        for id in &group {
766            self.finished.remove(id.as_str());
767            self.failed.remove(id.as_str());
768        }
769        let inner: Vec<&'a str> = self
770            .incoming
771            .values()
772            .flatten()
773            .filter(|e| group.contains(&e.source) && group.contains(&e.target))
774            .map(|e| e.id.as_str())
775            .collect();
776        for edge in inner {
777            self.decided.remove(edge);
778        }
779        // What the last iteration did not take is decided again by this one.
780        self.held.retain(|e| !group.contains(&e.source));
781        self.enqueue(head, true);
782    }
783}
784
785mod attention;
786mod call;
787mod checkpoint;
788mod foreach;
789mod join;
790mod parallel;
791mod replay;
792mod wait;
793
794#[cfg(test)]
795#[path = "scheduler_tests.rs"]
796mod tests;