1use std::sync::Arc;
13
14use super::checkpoint::{self, Checkpoint, CheckpointDiff, CheckpointError, GraphRef};
15use crate::backend::storage::drone_store::{CheckpointRow, DroneStore};
16use crate::backend::storage::store::Store;
17
18pub const KIND_FULL: &str = "full";
19pub const KIND_DIFF: &str = "diff";
20
21pub trait CheckpointSink: Send + Sync {
23 fn put(&self, run_id: &str, step: u32, kind: &str, body: &[u8]) -> Result<(), String>;
24}
25
26impl CheckpointSink for Store {
27 fn put(&self, run_id: &str, step: u32, kind: &str, body: &[u8]) -> Result<(), String> {
28 self.drone_checkpoint_put(run_id, step, kind, body, agentmux_common::time::now_ms()).map_err(|e| e.to_string())
29 }
30}
31
32#[derive(Clone)]
35pub struct Persist {
36 pub sink: Arc<dyn CheckpointSink>,
37 pub graph: GraphRef,
38}
39
40pub struct Recorder {
42 sink: Arc<dyn CheckpointSink>,
43 run_id: String,
44 last: Option<Checkpoint>,
46}
47
48impl Recorder {
49 pub fn new(sink: Arc<dyn CheckpointSink>, run_id: &str) -> Self {
50 Self { sink, run_id: run_id.to_string(), last: None }
51 }
52
53 pub fn resuming(sink: Arc<dyn CheckpointSink>, last: Checkpoint) -> Self {
55 Self { sink, run_id: last.run_id.clone(), last: Some(last) }
56 }
57
58 pub fn resume_from(&mut self, last: Checkpoint) {
60 self.last = Some(last);
61 }
62
63 pub fn next_step(&self) -> u32 {
65 self.last.as_ref().map_or(0, |c| c.step + 1)
66 }
67
68 pub fn write(&mut self, c: Checkpoint) -> Result<(), RecordError> {
72 let (kind, body) = match &self.last {
73 None => (KIND_FULL, checkpoint::encode(&c)?),
74 Some(prev) => {
75 let d = checkpoint::diff(prev, &c)?;
76 (KIND_DIFF, serde_json::to_vec(&d).map_err(|e| CheckpointError::Unreadable(e.to_string()))?)
77 }
78 };
79 self.sink.put(&self.run_id, c.step, kind, &body).map_err(RecordError::Store)?;
80 self.last = Some(c);
81 Ok(())
82 }
83}
84
85#[derive(Debug, thiserror::Error)]
86pub enum RecordError {
87 #[error("{0}")]
89 Checkpoint(#[from] CheckpointError),
90 #[error("the checkpoint could not be stored: {0}")]
92 Store(String),
93}
94
95pub fn load(rows: &[CheckpointRow]) -> Result<Option<Checkpoint>, CheckpointError> {
100 let mut at: Option<Checkpoint> = None;
101 for row in rows {
102 at = Some(match (&at, row.kind.as_str()) {
103 (None, KIND_FULL) => checkpoint::decode(&row.body)?,
104 (Some(prev), KIND_DIFF) => {
105 let d: CheckpointDiff = serde_json::from_slice(&row.body).map_err(|e| CheckpointError::Unreadable(e.to_string()))?;
106 checkpoint::apply(prev, &d)?
107 }
108 (None, other) => return Err(CheckpointError::Unreadable(format!("the first checkpoint is {other:?}, not whole"))),
109 (Some(_), other) => return Err(CheckpointError::Unreadable(format!("step {} is {other:?}, not a diff", row.step))),
110 });
111 }
112 Ok(at)
113}
114
115#[cfg(test)]
117#[derive(Default)]
118pub(crate) struct MemorySink {
119 pub(crate) rows: std::sync::Mutex<Vec<(String, CheckpointRow)>>,
120 pub(crate) refuse: std::sync::Mutex<std::collections::VecDeque<bool>>,
122}
123
124#[cfg(test)]
125impl MemorySink {
126 pub(crate) fn rows_of(&self, run_id: &str) -> Vec<CheckpointRow> {
127 self.rows.lock().unwrap().iter().filter(|(r, _)| r == run_id).map(|(_, row)| row.clone()).collect()
128 }
129}
130
131#[cfg(test)]
132impl CheckpointSink for MemorySink {
133 fn put(&self, run_id: &str, step: u32, kind: &str, body: &[u8]) -> Result<(), String> {
134 if self.refuse.lock().unwrap().pop_front().unwrap_or(false) {
135 return Err("the disk is full".to_string());
136 }
137 self.rows.lock().unwrap().push((run_id.to_string(), CheckpointRow { step, kind: kind.to_string(), body: body.to_vec() }));
138 Ok(())
139 }
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145 use crate::drone::checkpoint::{sample, MAX_STEPS};
146
147 fn step(n: u32) -> Checkpoint {
148 let mut c = sample(n);
149 c.cost_usd = f64::from(n);
150 c.frontier.ready = vec![format!("n{n}")];
151 c
152 }
153
154 #[test]
155 fn the_first_checkpoint_is_whole_and_the_rest_are_diffs_that_load_back() {
156 let sink = Arc::new(MemorySink::default());
157 let mut r = Recorder::new(sink.clone(), "run-1");
158 assert_eq!(r.next_step(), 0);
159 for n in 0..4 {
160 r.write(step(n)).unwrap();
161 }
162 let rows = sink.rows_of("run-1");
163 assert_eq!(rows.iter().map(|r| (r.step, r.kind.as_str())).collect::<Vec<_>>(), [(0, "full"), (1, "diff"), (2, "diff"), (3, "diff")]);
164 assert!(rows[1].body.len() < rows[0].body.len(), "a diff is smaller than the whole");
165 assert_eq!(load(&rows).unwrap(), Some(step(3)));
166 assert_eq!(load(&rows[..2]).unwrap(), Some(step(1)), "a run can be read as of an earlier step");
167 assert_eq!(r.next_step(), 4);
168 }
169
170 #[test]
171 fn a_refused_write_leaves_the_next_one_a_diff_from_what_was_stored() {
172 let sink = Arc::new(MemorySink::default());
173 let mut r = Recorder::new(sink.clone(), "run-1");
174 r.write(step(0)).unwrap();
175 sink.refuse.lock().unwrap().push_back(true);
176 assert!(matches!(r.write(step(1)), Err(RecordError::Store(_))));
177 assert_eq!(r.next_step(), 1, "the step number is not spent");
178 r.write(step(1)).unwrap();
179 assert_eq!(load(&sink.rows_of("run-1")).unwrap(), Some(step(1)));
180 }
181
182 #[test]
183 fn a_run_stops_at_the_step_ceiling() {
184 let sink = Arc::new(MemorySink::default());
185 let mut r = Recorder::new(sink, "run-1");
186 r.write(step(0)).unwrap();
187 let mut last = step(0);
188 for n in 1..MAX_STEPS {
189 last = step(n);
190 r.write(last.clone()).unwrap();
191 }
192 assert_eq!(last.step, MAX_STEPS - 1);
193 assert!(matches!(
194 r.write(step(MAX_STEPS)),
195 Err(RecordError::Checkpoint(CheckpointError::TooManySteps { .. }))
196 ));
197 }
198
199 #[test]
200 fn rows_that_do_not_chain_are_an_error_not_a_guess() {
201 let sink = Arc::new(MemorySink::default());
202 let mut r = Recorder::new(sink.clone(), "run-1");
203 for n in 0..3 {
204 r.write(step(n)).unwrap();
205 }
206 let rows = sink.rows_of("run-1");
207 assert_eq!(load(&[]).unwrap(), None);
208 assert!(load(&rows[1..]).is_err(), "it must start whole");
209 assert!(load(&[rows[0].clone(), rows[2].clone()]).is_err(), "a step may not be skipped");
210 let mut torn = rows.clone();
211 torn[1].body.truncate(5);
212 assert!(load(&torn).is_err());
213 }
214
215 #[test]
216 fn a_resuming_recorder_goes_on_from_the_last_checkpoint() {
217 let sink = Arc::new(MemorySink::default());
218 let mut first = Recorder::new(sink.clone(), "run-1");
219 for n in 0..3 {
220 first.write(step(n)).unwrap();
221 }
222 let stored = load(&sink.rows_of("run-1")).unwrap().unwrap();
223 let mut again = Recorder::resuming(sink.clone(), stored);
224 assert_eq!(again.next_step(), 3);
225 again.write(step(3)).unwrap();
226 assert_eq!(load(&sink.rows_of("run-1")).unwrap(), Some(step(3)));
227 }
228}