1use 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
39pub(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
59const HISTORY_LEN: usize = 50;
62
63type States = Arc<tokio::sync::Mutex<HashMap<String, BlockState>>>;
64
65#[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 pub(super) chain: Vec<String>,
74 pub(super) lookup: Option<Arc<dyn DroneLookup>>,
76 pub(super) replay: Option<Arc<Replay>>,
78}
79
80fn 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 BlockKind::Api | BlockKind::Condition | BlockKind::Once | BlockKind::Response | BlockKind::Variables | BlockKind::Transform | BlockKind::ForEach | BlockKind::Wait | BlockKind::Approval | BlockKind::Join => None,
89 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
103async 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
109pub(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
122fn carries_on(edge: &FlowEdge, source: &FlowNode, output: &Value, failed: bool) -> bool {
125 if edge.source_handle.as_deref() == Some("error") {
128 return failed;
129 }
130 if failed {
131 return false;
132 }
133 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 _ => true,
143 }
144}
145
146struct Scheduler<'a> {
147 run_id: &'a str,
148 plan: Plan,
149 node_of: HashMap<&'a str, &'a FlowNode>,
150 incoming: HashMap<&'a str, Vec<&'a FlowEdge>>,
152 outgoing: HashMap<&'a str, Vec<&'a FlowEdge>>,
153 decided: HashMap<&'a str, bool>,
155 finished: HashSet<&'a str>,
157 failed: HashSet<&'a str>,
159 ready: VecDeque<(&'a str, bool)>,
160 queued: HashSet<&'a str>,
161 held: Vec<&'a FlowEdge>,
163 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 cancelled: bool,
175 in_flight: Vec<(&'a str, bool)>,
178 running_ro: Vec<(&'a str, bool)>,
180 waiting: Option<(&'a str, bool)>,
183 deadlines: BTreeMap<String, i64>,
184 resume_on: BTreeMap<String, String>,
185 wait_timeouts: BTreeMap<String, i64>,
187 chain: Vec<String>,
189 lookup: Option<Arc<dyn DroneLookup>>,
190 late_spend: Arc<call::LateSpend>,
192 replay: Option<Arc<Replay>>,
193 recorder: Option<(Recorder, GraphRef)>,
195 started: Instant,
196 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
211pub(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
232pub(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 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
257pub(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
274async 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 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 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 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 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 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 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 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 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 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 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 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 async fn attempt(&mut self, node: &'a FlowNode, kind: BlockKind) -> Result<Value, String> {
528 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 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 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 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 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 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 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 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 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 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 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 BlockKind::Wait if node.data.get("on").is_some() => (true, false),
661 BlockKind::Wait => (false, false),
662 BlockKind::Approval => (false, false),
664 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 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 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 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 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 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 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 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;