Skip to main content

agentmux_srv/drone/executor/scheduler/
checkpoint.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The scheduler's side of checkpoints: what it writes after a block
5//! (`snapshot`, `checkpoint`) and how it takes a run up again from one
6//! (`restore`)
7//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md §3.3).
8//!
9//! A checkpoint is written when the scheduler is between blocks, so nothing is
10//! half done: the blocks that are ready, the edges decided, the outputs read
11//! so far, the variables with their taint bits, each block's history
12//! (`{{block.history}}`), and what has been spent.
13
14use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
15use std::time::{Duration, Instant};
16
17use super::{kind_of, Scheduler};
18use crate::drone::checkpoint::{self, Checkpoint, CheckpointError, Frontier, GraphRef, Position};
19use crate::drone::executor::effect::{effect_of, Effect};
20use crate::drone::executor::engine::{mark_state, RunEvent};
21use crate::drone::executor::schedule::foreach_config;
22use crate::drone::recorder::RecordError;
23use crate::drone::state::RunState;
24use crate::drone::types::{BlockKind, BlockState, FlowNode};
25
26impl<'a> Scheduler<'a> {
27    /// Keep the run as it stands as its next checkpoint, `after` the block that
28    /// just finished (none for the first, before any block). A run that cannot
29    /// keep a checkpoint goes on, and the next one is a diff from the last kept;
30    /// a run that has used up its steps (§3.3: at most 1,000) ends, saying so.
31    pub(super) fn checkpoint(&mut self, after: Option<&str>) -> Result<(), String> {
32        self.keep(after, false)
33    }
34
35    /// The checkpoint a run keeps before it stops at `id`: without it a restart could not
36    /// take the wait up again, so a run that cannot keep it ends.
37    pub(super) fn checkpoint_required(&mut self, id: &str) -> Result<(), String> {
38        self.keep(Some(id), true)
39    }
40
41    /// What `node` does to the world. A block a replay stubs does nothing to it.
42    pub(super) fn effect_of_node(&self, node: &FlowNode, kind: BlockKind) -> Effect {
43        if self.stub_of(node, kind).is_some() {
44            return Effect::ReadOnly;
45        }
46        self.real_effect_of_node(node, kind)
47    }
48
49    /// What `node` does to the world, which a for-each takes from its body.
50    pub(super) fn real_effect_of_node(&self, node: &FlowNode, kind: BlockKind) -> Effect {
51        let resolve = |template: &str| self.scope.resolve(template);
52        let body = match kind {
53            BlockKind::ForEach => foreach_config(node)
54                .ok()
55                .and_then(|cfg| self.node_of.get(cfg.body.as_str()).copied())
56                .and_then(|b| kind_of(b).ok().filter(|k| *k != BlockKind::ForEach).map(|k| effect_of(k, b, Effect::ReadOnly, &resolve)))
57                // A key can depend on the item, which is not known here, so a body that
58                // relies on one cannot be told to be safe to run again.
59                .map(|e| if e == Effect::Idempotent { Effect::Effectful } else { e })
60                .unwrap_or(Effect::Effectful),
61            _ => Effect::ReadOnly,
62        };
63        effect_of(kind, node, body, &resolve)
64    }
65
66    /// Before a block with effects starts, keep a checkpoint that says it is
67    /// running. A restart that finds it as the newest knows the block may have
68    /// done its work already. When the run cannot keep it, the block does not
69    /// start: it would be a step no restart could account for.
70    pub(super) fn mark_in_flight(&mut self, node: &'a FlowNode, forced: bool) -> Result<(), String> {
71        if self.recorder.is_none() {
72            return Ok(());
73        }
74        let Ok(kind) = kind_of(node) else { return Ok(()) };
75        if self.effect_of_node(node, kind) != Effect::Effectful {
76            return Ok(());
77        }
78        self.in_flight.push((node.id.as_str(), forced));
79        self.keep(Some(node.id.as_str()), true)
80    }
81
82    /// [`mark_in_flight`](Self::mark_in_flight) for a batch of blocks that start together: the
83    /// ones with effects are listed as running in one checkpoint, kept before any starts, and
84    /// the others are listed as ready until they finish.
85    pub(super) fn mark_batch_in_flight(&mut self, batch: &[(&'a str, bool)]) -> Result<(), String> {
86        let mut effectful = false;
87        for &(id, forced) in batch {
88            let node = self.node_of[id];
89            let effect = kind_of(node).map(|kind| self.effect_of_node(node, kind));
90            if self.recorder.is_some() && effect == Ok(Effect::Effectful) {
91                self.in_flight.push((id, forced));
92                effectful = true;
93            } else {
94                self.running_ro.push((id, forced));
95            }
96        }
97        if effectful {
98            return self.keep(batch.first().map(|(id, _)| *id), true);
99        }
100        Ok(())
101    }
102
103    /// [`checkpoint`](Self::checkpoint), and with `required` a checkpoint that
104    /// could not be kept ends the run.
105    fn keep(&mut self, after: Option<&str>, required: bool) -> Result<(), String> {
106        let Some(step) = self.recorder.as_ref().map(|(r, _)| r.next_step()) else { return Ok(()) };
107        let c = self.snapshot(step);
108        let Some((recorder, _)) = self.recorder.as_mut() else { return Ok(()) };
109        match recorder.write(c) {
110            Ok(()) => {
111                let _ = self.tx.send(RunEvent::StepCheckpointed { run_id: self.run_id.to_string(), step, block_id: after.map(str::to_string) });
112                Ok(())
113            }
114            Err(RecordError::Checkpoint(CheckpointError::TooManySteps { max, .. })) => {
115                let why = format!("stopped: a run keeps at most {max} steps and this one used them all");
116                self.cap_reached(after.unwrap_or_default(), &why);
117                Err(why)
118            }
119            Err(e) if required => {
120                Err(format!("stopped: the run could not keep its place before {}, so it did not start it ({e})", after.unwrap_or_default()))
121            }
122            Err(e) => {
123                tracing::warn!(run_id = %self.run_id, error = %e, "drone: a checkpoint was not kept");
124                Ok(())
125            }
126        }
127    }
128
129    /// The run as it stands, as checkpoint `step`.
130    fn snapshot(&self, step: u32) -> Checkpoint {
131        let ms = |since: &Instant| u64::try_from(since.elapsed().as_millis()).unwrap_or(u64::MAX);
132        let mut finished: Vec<String> = self.finished.iter().map(|id| id.to_string()).collect();
133        finished.sort_unstable();
134        Checkpoint {
135            schema_version: checkpoint::SCHEMA_VERSION,
136            run_id: self.run_id.to_string(),
137            step,
138            state: self.scope.state.snapshot(),
139            frontier: Frontier {
140                ready: self.running_ro.iter().chain(self.ready.iter()).map(|(id, _)| id.to_string()).collect(),
141                forced: self
142                    .running_ro
143                    .iter()
144                    .chain(self.ready.iter())
145                    .filter(|(_, forced)| *forced)
146                    .map(|(id, _)| id.to_string())
147                    .chain(self.in_flight.iter().filter(|(_, forced)| *forced).map(|(id, _)| id.to_string()))
148                    .chain(self.waiting.filter(|(_, forced)| *forced).map(|(id, _)| id.to_string()))
149                    .collect(),
150                running: self.in_flight.iter().map(|(id, _)| id.to_string()).collect(),
151                waiting: self.waiting.iter().map(|(id, _)| id.to_string()).collect(),
152            },
153            loop_counters: self.rounds.iter().map(|(id, n)| (id.to_string(), *n)).collect(),
154            cost_usd: self.spent,
155            elapsed_ms: self.elapsed_before_ms + ms(&self.started),
156            deadlines: self.deadlines.clone(),
157            resume_on: self.resume_on.clone(),
158            wait_timeouts: self.wait_timeouts.clone(),
159            graph: self.recorder.as_ref().map(|(_, g)| g.clone()).unwrap_or(GraphRef { version: 0, hash: String::new() }),
160            drone_id: self.scope.drone_id.clone(),
161            trigger: self.scope.trigger.clone(),
162            run_cap_usd: self.run_cap_usd,
163            outputs: self.scope.outputs.iter().map(|(id, v)| (id.clone(), v.clone())).collect(),
164            bits: self.scope.bits.iter().map(|(id, b)| (id.clone(), *b)).collect(),
165            history: self.history.iter().map(|(id, past)| (id.to_string(), past.iter().cloned().collect())).collect(),
166            position: Position {
167                decided: self.decided.iter().map(|(id, carries)| (id.to_string(), *carries)).collect(),
168                finished,
169                failed: Some({
170                    let mut failed: Vec<String> = self.failed.iter().map(|id| id.to_string()).collect();
171                    failed.sort_unstable();
172                    failed
173                }),
174                held: self.held.iter().map(|e| e.id.clone()).collect(),
175                spent_by: self.spent_by.iter().map(|(id, usd)| (id.to_string(), *usd)).collect(),
176                loop_elapsed_ms: self.loop_started.iter().map(|(id, since)| (id.clone(), ms(since))).collect(),
177                response: self.response.clone(),
178            },
179            fork: self.replay.as_ref().map(|r| r.fork.clone()),
180        }
181    }
182
183    /// Set this scheduler (new, for the graph the checkpoint was written on) to
184    /// where `c` left the run. A checkpoint that names a block or an edge the graph
185    /// does not have was written on another graph, and is refused.
186    pub(super) fn restore(&mut self, c: &Checkpoint) -> Result<(), String> {
187        self.restore_state(c)?;
188        if let Some((recorder, _)) = self.recorder.as_mut() {
189            recorder.resume_from(c.clone());
190        }
191        Ok(())
192    }
193
194    /// [`restore`](Self::restore) but for the run's own place only: its checkpoints go on as they are,
195    /// which a run that starts from `c` (a replay) does not have yet.
196    pub(super) fn restore_state(&mut self, c: &Checkpoint) -> Result<(), String> {
197        let edges: HashMap<&'a str, &'a crate::drone::types::FlowEdge> = self.outgoing.values().flatten().map(|e| (e.id.as_str(), *e)).collect();
198        let node = |id: &str| -> Result<&'a str, String> {
199            self.node_of.get_key_value(id).map(|(k, _)| *k).ok_or_else(|| format!("the saved run does not fit its graph: it has no block {id}"))
200        };
201        let edge = |id: &str| -> Result<&'a crate::drone::types::FlowEdge, String> {
202            edges.get(id).copied().ok_or_else(|| format!("the saved run does not fit its graph: it has no edge {id}"))
203        };
204
205        let mut ready = VecDeque::new();
206        let mut queued = HashSet::new();
207        for id in &c.frontier.ready {
208            let id = node(id)?;
209            ready.push_back((id, c.frontier.forced.iter().any(|f| f == id)));
210            queued.insert(id);
211        }
212        let mut decided = HashMap::new();
213        for (id, carries) in &c.position.decided {
214            decided.insert(edge(id)?.id.as_str(), *carries);
215        }
216        let finished = c.position.finished.iter().map(|id| node(id)).collect::<Result<HashSet<_>, _>>()?;
217        let failed = match &c.position.failed {
218            Some(ids) => ids.iter().map(|id| node(id)).collect::<Result<HashSet<_>, _>>()?,
219            None => self.legacy_failed(c, &finished, &decided),
220        };
221        let held = c.position.held.iter().map(|id| edge(id)).collect::<Result<Vec<_>, _>>()?;
222        let mut rounds = HashMap::new();
223        for (id, n) in &c.loop_counters {
224            rounds.insert(node(id)?, *n);
225        }
226        let mut spent_by = HashMap::new();
227        for (id, usd) in &c.position.spent_by {
228            spent_by.insert(node(id)?, *usd);
229        }
230        let mut history = HashMap::new();
231        for (id, past) in &c.history {
232            history.insert(node(id)?, past.iter().cloned().collect::<VecDeque<_>>());
233        }
234        let now = Instant::now();
235        let loop_started = c
236            .position
237            .loop_elapsed_ms
238            .iter()
239            .map(|(id, ms)| (id.clone(), now.checked_sub(Duration::from_millis(*ms)).unwrap_or(now)))
240            .collect();
241
242        let mut in_flight = Vec::new();
243        for id in &c.frontier.running {
244            in_flight.push((node(id)?, c.frontier.forced.iter().any(|f| f == id)));
245        }
246        // A block that was waiting is run again from its start, and takes the wait it finds.
247        let mut ready = ready;
248        for id in c.frontier.waiting.iter().rev() {
249            let id = node(id)?;
250            if queued.insert(id) {
251                ready.push_front((id, c.frontier.forced.iter().any(|f| f == id)));
252            }
253        }
254        self.deadlines = c.deadlines.clone();
255        self.resume_on = c.resume_on.clone();
256        self.wait_timeouts = c.wait_timeouts.clone();
257        self.in_flight = in_flight;
258        self.ready = ready;
259        self.queued = queued;
260        self.decided = decided;
261        self.finished = finished;
262        self.failed = failed;
263        self.held = held;
264        self.rounds = rounds;
265        self.spent_by = spent_by;
266        self.history = history;
267        self.loop_started = loop_started;
268        self.spent = c.cost_usd;
269        self.response = c.position.response.clone();
270        self.run_cap_usd = c.run_cap_usd;
271        self.elapsed_before_ms = c.elapsed_ms;
272        self.scope.outputs = c.outputs.iter().map(|(id, v)| (id.clone(), v.clone())).collect();
273        self.scope.bits = c.bits.iter().map(|(id, b)| (id.clone(), *b)).collect();
274        self.scope.vars = c.state.vars.iter().map(|(name, tv)| (name.clone(), tv.v.clone())).collect();
275        self.scope.state = RunState::from_snapshot(c.state.clone());
276        Ok(())
277    }
278
279    /// The blocks that failed in this pass, for a checkpoint written before the set was kept. A block that
280    /// finished with a handled failure said so as its output (`failed: true` and the error), but a block that
281    /// failed in one pass of a loop and was skipped in the next keeps that output too. So the output counts
282    /// only for a block that ran this pass: a root, or one an edge into it was taken for, or a Join that a
283    /// branch (found the same way) failed into.
284    fn legacy_failed(&self, c: &Checkpoint, finished: &HashSet<&'a str>, decided: &HashMap<&'a str, bool>) -> HashSet<&'a str> {
285        let says_failed = |id: &str| c.outputs.get(id).is_some_and(|o| o.get("failed").and_then(serde_json::Value::as_bool) == Some(true) && o.get("error").is_some());
286        let ran = |id: &str| {
287            let ins = self.incoming.get(id).map(Vec::as_slice).unwrap_or_default();
288            ins.is_empty() || ins.iter().any(|e| decided.get(e.id.as_str()) == Some(&true))
289        };
290        let is_join = |id: &str| self.node_of.get(id).is_some_and(|n| kind_of(n).is_ok_and(|k| k == BlockKind::Join));
291        let mut failed: HashSet<&'a str> = finished.iter().copied().filter(|id| says_failed(id) && ran(id)).collect();
292        loop {
293            let more: Vec<&'a str> = finished
294                .iter()
295                .copied()
296                .filter(|id| !failed.contains(id) && says_failed(id) && is_join(id))
297                .filter(|id| self.incoming.get(id).is_some_and(|ins| ins.iter().any(|e| failed.contains(e.source.as_str()))))
298                .collect();
299            if more.is_empty() {
300                return failed;
301            }
302            failed.extend(more);
303        }
304    }
305
306    /// Show what the restored blocks did, as the run's own block states, so what
307    /// a person sees of a resumed run is not blank where blocks already ran.
308    pub(super) async fn show_restored(&self) {
309        for id in &self.finished {
310            let mut output = self.scope.outputs.get(*id).cloned();
311            // A Drone block's callee may have spent money the output does not say: a callee that spent and
312            // then failed (the error edge's output is only the error), or one that ended after the call
313            // was given up on. That spend is kept as the position's `spent_by`, and the ledger sums the
314            // blocks' `cost_usd`, so it goes back on the state.
315            let drone = self.node_of.get(*id).is_some_and(|n| kind_of(n).is_ok_and(|k| k == BlockKind::Drone));
316            let spent = self.spent_by.get(*id).copied().unwrap_or(0.0);
317            if let (true, Some(out)) = (drone && spent > 0.0, output.as_mut()) {
318                let counted = out.get("cost_usd").and_then(serde_json::Value::as_f64).unwrap_or(0.0);
319                if spent > counted {
320                    if let Some(map) = out.as_object_mut() {
321                        map.insert("cost_usd".to_string(), serde_json::json!(spent));
322                    }
323                }
324            }
325            let status = if output.is_some() { "done" } else { "skipped" };
326            mark_state(self.states, id, BlockState { status: status.to_string(), output, error: None, started_at: None, completed_at: Some(agentmux_common::time::now_ms()) }).await;
327        }
328    }
329}
330
331#[cfg(test)]
332#[path = "checkpoint_tests.rs"]
333mod tests;