Skip to main content

agentmux_srv/server/
drone_resume.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Taking Drone runs up again when AgentMux starts
5//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md ยง3.3, "Resume").
6//!
7//! A run left `running` by the old process is no longer marked interrupted and
8//! forgotten when it has checkpoints: its newest one is loaded, the graph it was
9//! written on is found (the saved version, or the current definition when that is
10//! still the same graph), and the engine carries on from there. A run with no
11//! checkpoint, or none it can go on from, is left for the restart to interrupt,
12//! as before; the reason is in the log.
13
14use std::collections::HashSet;
15use std::sync::Arc;
16
17use crate::backend::jobs::RunLedger;
18use crate::backend::storage::drone_store::DroneStore;
19use crate::drone::checkpoint::{Checkpoint, GraphRef};
20use crate::drone::executor::resume_drone;
21use crate::drone::recorder::{load, Persist};
22use crate::drone::types::{DroneGraph, DroneRun};
23use crate::drone::versions::{graph_hash, DroneVersionStore};
24use crate::server::AppState;
25
26/// Take up again every run the old process left running that can be. Returns
27/// their ids: the restart leaves those rows open (`recover_after_restart_except`).
28/// Call before the ledger recovers, from the state that has the stores. `ledger`
29/// closes the run's job row when it ends; none for a state without one.
30pub(crate) async fn resume_runs(state: &AppState, ledger: Option<&Arc<RunLedger>>) -> HashSet<String> {
31    let mut resumed = HashSet::new();
32    let running = match state.mstore.drone_runs_running() {
33        Ok(rows) => rows,
34        Err(e) => {
35            tracing::warn!(error = %e, "drone: couldn't read the runs left running");
36            return resumed;
37        }
38    };
39    for run in running {
40        match checkpoint_and_graph(state, &run) {
41            Ok(Some(_)) if ledger.is_some_and(|l| l.close_if_past_timeout(&run.id)) => {
42                tracing::info!(run_id = %run.id, "drone: a run is not taken up again: its job's timeout ran out while AgentMux was stopped");
43            }
44            Ok(Some((checkpoint, graph))) => {
45                let persist = Persist { sink: state.mstore.clone(), graph: checkpoint.graph.clone() };
46                let step = checkpoint.step;
47                // A replay goes on as a replay: its blocks with effects still say what they said before.
48                let replay = match crate::server::drone_replay::replay_for(state, &checkpoint) {
49                    Ok(replay) => replay,
50                    Err(why) => {
51                        tracing::warn!(run_id = %run.id, "drone: a replay is not taken up again: {why}");
52                        continue;
53                    }
54                };
55                match resume_drone(graph, checkpoint, persist, replay).await {
56                    Ok(handle) => {
57                        let ledger_run = ledger.and_then(|l| l.open_run_of_drone(&run.id).map(|id| (l.clone(), id)));
58                        tracing::info!(run_id = %run.id, drone_id = %run.drone_id, step, "drone: taking a run up again after the restart");
59                        crate::server::drone_handlers::spawn_run_drain(state, handle, run.drone_id.clone(), run.started_at, ledger_run);
60                        resumed.insert(run.id);
61                    }
62                    Err(e) => tracing::warn!(run_id = %run.id, error = %e, "drone: a run could not be taken up again"),
63                }
64            }
65            Ok(None) => {}
66            Err(why) => tracing::warn!(run_id = %run.id, drone_id = %run.drone_id, "drone: a run is not taken up again: {why}"),
67        }
68    }
69    resumed
70}
71
72/// The newest checkpoint of `run` and the graph it was written on; `None` when
73/// the run kept no checkpoint.
74fn checkpoint_and_graph(state: &AppState, run: &DroneRun) -> Result<Option<(Checkpoint, DroneGraph)>, String> {
75    let rows = state.mstore.drone_checkpoints_for(&run.id).map_err(|e| format!("its checkpoints cannot be read: {e}"))?;
76    let Some(checkpoint) = load(&rows).map_err(|e| format!("its checkpoints are unusable: {e}"))? else { return Ok(None) };
77    let graph = graph_of(state, &run.drone_id, &checkpoint.graph)?;
78    Ok(Some((checkpoint, graph)))
79}
80
81/// The graph a run started on: the saved version it names when that is the same
82/// graph (by hash), else the drone's current graph when that is. A graph that was
83/// edited since, with no saved version to go back to, is no graph the run's
84/// checkpoints fit.
85pub(crate) fn graph_of(state: &AppState, drone_id: &str, graph: &GraphRef) -> Result<DroneGraph, String> {
86    if graph.version > 0 {
87        if let Ok(Some(v)) = state.id_store.version_get(drone_id, graph.version) {
88            if v.hash == graph.hash {
89                return Ok(v.graph);
90            }
91        }
92    }
93    match state.id_store.drone_get(drone_id) {
94        Ok(Some(d)) if graph_hash(&d.graph) == graph.hash => Ok(d.graph),
95        Ok(Some(_)) => Err("the drone was edited since, and the graph the run started on was not kept".to_string()),
96        Ok(None) => Err("the drone no longer exists".to_string()),
97        Err(e) => Err(format!("the drone cannot be read: {e}")),
98    }
99}
100
101#[cfg(test)]
102#[path = "drone_resume_tests.rs"]
103mod tests;