Skip to main content

agentmux_srv/server/
drone_replay.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `replaydronerun`: start a new run from a step of a finished one
5//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md ยง3.3, "Replay and time travel").
6//!
7//! The new run has its own id and its own checkpoints, starts from the state the earlier run had
8//! at that step, and is on the graph version the earlier run started on. A block that would send,
9//! file, start or write says what it said in the earlier run instead of doing it again, unless the
10//! caller asks for it `do_it_for_real`. A replay that is taken up again after a restart (`resume_runs`)
11//! is still a replay: its checkpoints name the run it came from.
12
13use std::sync::Arc;
14
15use serde::{Deserialize, Serialize};
16
17use crate::backend::storage::drone_store::DroneStore;
18use crate::backend::storage::drone_types::{DroneRun, RunStatus};
19use crate::drone::checkpoint::{Checkpoint, Fork};
20use crate::drone::executor::replay_drone;
21use crate::drone::recorder::{load, Persist};
22use crate::drone::replay::{fork_checkpoint, Replay};
23use crate::server::drone_handlers::spawn_run_drain;
24use crate::server::drone_resume::graph_of;
25use crate::server::AppState;
26use agentmux_common::time::now_ms;
27
28/// What `replaydronerun` is asked to do.
29#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
30#[ts(export, export_to = "../../../frontend/types/rpc/")]
31pub struct ReplayRunReq {
32    /// The run to replay: one that has ended.
33    pub run_id: String,
34    /// The checkpoint to start from: 0 is before its first block, then one more after each block.
35    pub from_step: u32,
36    /// Run the blocks that have effects as they ran before (send again, file again). The default
37    /// is that they say what they said before and do nothing.
38    #[serde(default)]
39    pub do_it_for_real: bool,
40}
41
42#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
43#[ts(export, export_to = "../../../frontend/types/rpc/")]
44pub struct ReplayRunResp {
45    /// The new run.
46    pub run_id: String,
47    pub forked_from: String,
48    pub from_step: u32,
49    pub real: bool,
50}
51
52/// What a replaying run needs besides its checkpoint: the run it came from said what, for the blocks it
53/// stubs. `None` for a checkpoint of a run that is not a replay. A replay whose source run's checkpoints are
54/// gone cannot be taken up again (what its stubs said is not kept anywhere else).
55pub(crate) fn replay_for(state: &AppState, c: &Checkpoint) -> Result<Option<Arc<Replay>>, String> {
56    let Some(fork) = c.fork.clone() else { return Ok(None) };
57    let (original, bits) = if fork.real {
58        Default::default()
59    } else {
60        let rows = state.mstore.drone_checkpoints_for(&fork.run_id).map_err(|e| format!("the run it replays cannot be read: {e}"))?;
61        let newest = load(&rows).map_err(|e| format!("the run it replays is unusable: {e}"))?;
62        let newest = newest.ok_or_else(|| format!("the run it replays ({}) kept no checkpoints any more", fork.run_id))?;
63        (newest.outputs, newest.bits)
64    };
65    Ok(Some(Arc::new(Replay { fork, original, bits })))
66}
67
68/// `replaydronerun`, started by the person's window.
69#[cfg(test)]
70pub(crate) async fn replay_drone_run(state: &AppState, cmd: ReplayRunReq) -> Result<ReplayRunResp, String> {
71    replay_drone_run_as(state, cmd, None).await
72}
73
74/// `replaydronerun`. `by` is who the new run's ledger row says started it, `None` for the person's window (the
75/// operator); the registered handler takes it from the connection, so an agent's replay is shown as that agent's.
76pub(crate) async fn replay_drone_run_as(state: &AppState, cmd: ReplayRunReq, by: Option<&str>) -> Result<ReplayRunResp, String> {
77    let why = |e: String| format!("replaydronerun: {e}");
78    let rows = state.mstore.drone_checkpoints_for(&cmd.run_id).map_err(|e| why(format!("its checkpoints cannot be read: {e}")))?;
79    let newest = load(&rows).map_err(|e| why(format!("its checkpoints are unusable: {e}")))?.ok_or_else(|| why("it kept no checkpoints, so there is nothing to start from".to_string()))?;
80    if cmd.from_step > newest.step {
81        return Err(why(format!("it has checkpoints 0 to {}, not {}", newest.step, cmd.from_step)));
82    }
83    let kept: Vec<_> = rows.into_iter().filter(|r| r.step <= cmd.from_step).collect();
84    let at = load(&kept).map_err(|e| why(format!("checkpoint {} is unusable: {e}", cmd.from_step)))?.ok_or_else(|| why("it kept no checkpoints".to_string()))?;
85    let drone_id = at.drone_id.clone();
86    let row = state
87        .mstore
88        .drone_run_get(&cmd.run_id)
89        .map_err(|e| why(e.to_string()))?
90        .ok_or_else(|| why(format!("there is no run {} of drone {drone_id}", cmd.run_id)))?;
91    ended(&row).map_err(why)?;
92    let graph = graph_of(state, &drone_id, &at.graph).map_err(|e| why(format!("the graph it ran on is not available: {e}")))?;
93    let wf = state.id_store.drone_get(&drone_id).map_err(|e| why(e.to_string()))?.ok_or_else(|| why(format!("drone {drone_id} no longer exists")))?;
94
95    let run_id = uuid::Uuid::new_v4().to_string();
96    let fork = Fork { run_id: cmd.run_id.clone(), step: cmd.from_step, real: cmd.do_it_for_real };
97    let first = fork_checkpoint(&at, &run_id, fork.clone());
98    let (original, bits) = if cmd.do_it_for_real { Default::default() } else { (newest.outputs, newest.bits) };
99    let persist = Persist { sink: state.mstore.clone(), graph: at.graph.clone() };
100    let trigger = first.trigger.clone();
101    let handle = replay_drone(graph, first, persist, Arc::new(Replay { fork, original, bits })).await.map_err(why)?;
102    let started_at = now_ms();
103    crate::server::drone_handlers::insert_run_placeholder(state, &run_id, &drone_id, started_at).map_err(why)?;
104    let ledger = state.cron_scheduler.runs().cloned();
105    let by = by.unwrap_or(crate::backend::jobs::BY_OPERATOR);
106    let ledger_run = ledger.and_then(|l| l.drone_started_by(&run_id, &drone_id, &wf.name, started_at, &trigger, by).map(|id| (l, id)));
107    spawn_run_drain(state, handle, drone_id, started_at, ledger_run);
108    Ok(ReplayRunResp { run_id, forked_from: cmd.run_id, from_step: cmd.from_step, real: cmd.do_it_for_real })
109}
110
111/// A run can be replayed once it is over: not while it runs, waits or needs an answer.
112fn ended(row: &DroneRun) -> Result<(), String> {
113    let live = [RunStatus::Running, RunStatus::Waiting, RunStatus::NeedsAttention].iter().any(|s| s.as_str() == row.status);
114    if live {
115        return Err(format!("run {} is still {}: replay one that has ended", row.id, row.status));
116    }
117    Ok(())
118}
119
120#[cfg(test)]
121#[path = "drone_replay_tests.rs"]
122mod tests;