Skip to main content

rig_multiagent/
checkpoint.rs

1//! Saving a run's progress in a rig-memory store, so a run that stopped (the
2//! process restarted, a step failed) carries on from where it was.
3
4use std::io;
5use std::sync::Arc;
6
7use rig_agent::agent::{
8    AgentHook, DispatchAction, DispatchEvent, HookContext, OutcomeAction, OutcomeEvent,
9};
10use rig_core::effect::{Answered, EffectId, EffectKind};
11use rig_core::tool::ToolResult;
12use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
13use rig_memory::AsyncStore;
14use serde::Serialize;
15use serde::de::DeserializeOwned;
16use serde_json::Value;
17
18use crate::swarm::HANDOFF_TOOL;
19
20/// A rig-memory store's files, behind a trait object.
21trait Files: WasmCompatSend + WasmCompatSync {
22    fn read<'a>(&'a self, name: &'a str) -> WasmBoxedFuture<'a, io::Result<Vec<u8>>>;
23    fn write<'a>(&'a self, name: &'a str, bytes: &'a [u8]) -> WasmBoxedFuture<'a, io::Result<()>>;
24}
25
26impl<S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static> Files for S {
27    fn read<'a>(&'a self, name: &'a str) -> WasmBoxedFuture<'a, io::Result<Vec<u8>>> {
28        Box::pin(self.read_file_async(name))
29    }
30
31    fn write<'a>(&'a self, name: &'a str, bytes: &'a [u8]) -> WasmBoxedFuture<'a, io::Result<()>> {
32        Box::pin(self.write_file_async(name, bytes))
33    }
34}
35
36/// Why a run's checkpoint could not be read or written.
37#[derive(Debug, thiserror::Error)]
38#[non_exhaustive]
39pub enum CheckpointError {
40    /// The run id is not 1-128 of `[A-Za-z0-9_-]`.
41    #[error("run id {0:?} must be 1-128 letters, digits, '-' or '_'")]
42    InvalidRunId(String),
43    /// The store could not read the checkpoint.
44    #[error("could not read checkpoint {name}: {source}")]
45    Read {
46        /// The checkpoint's file name in the store.
47        name: String,
48        /// The store's error.
49        #[source]
50        source: io::Error,
51    },
52    /// The checkpoint is not the JSON this version writes.
53    #[error("checkpoint {name} is unreadable: {source}")]
54    Unreadable {
55        /// The checkpoint's file name in the store.
56        name: String,
57        /// Why it does not parse.
58        #[source]
59        source: serde_json::Error,
60    },
61    /// The run's state could not be turned into JSON.
62    #[error("{0}")]
63    Encode(#[source] serde_json::Error),
64    /// The store could not write the checkpoint.
65    #[error("could not write checkpoint {name}: {source}")]
66    Write {
67        /// The checkpoint's file name in the store.
68        name: String,
69        /// The store's error.
70        #[source]
71        source: io::Error,
72    },
73    /// The checkpoint names a graph node the graph does not have.
74    #[error("node {0:?} of the checkpoint is not in the graph")]
75    UnknownNode(String),
76    /// The checkpoint names a swarm agent the swarm does not have.
77    #[error("agent {0:?} of the checkpoint is not in the swarm")]
78    UnknownAgent(String),
79}
80
81/// Where a swarm or graph keeps its runs' checkpoints: one JSON file per
82/// run, `rig-multiagent/<kind>/<run id>.json`, written atomically.
83#[derive(Clone)]
84pub(crate) struct Checkpoints {
85    files: Arc<dyn Files>,
86    kind: &'static str,
87}
88
89impl Checkpoints {
90    pub(crate) fn new(
91        store: impl AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
92        kind: &'static str,
93    ) -> Self {
94        Self {
95            files: Arc::new(store),
96            kind,
97        }
98    }
99
100    fn name(&self, id: &str) -> Result<String, CheckpointError> {
101        let valid = (1..=128).contains(&id.len())
102            && id
103                .bytes()
104                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
105        if !valid {
106            return Err(CheckpointError::InvalidRunId(id.to_owned()));
107        }
108        Ok(format!("rig-multiagent/{}/{id}.json", self.kind))
109    }
110
111    /// The run's last checkpoint, if it has one.
112    pub(crate) async fn load<T: DeserializeOwned>(
113        &self,
114        id: &str,
115    ) -> Result<Option<T>, CheckpointError> {
116        let name = self.name(id)?;
117        match self.files.read(&name).await {
118            Ok(bytes) => serde_json::from_slice(&bytes)
119                .map(Some)
120                .map_err(|source| CheckpointError::Unreadable { name, source }),
121            Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None),
122            Err(source) => Err(CheckpointError::Read { name, source }),
123        }
124    }
125
126    /// Replace the run's checkpoint with `state`.
127    pub(crate) async fn save<T: Serialize>(
128        &self,
129        id: &str,
130        state: &T,
131    ) -> Result<(), CheckpointError> {
132        let name = self.name(id)?;
133        let bytes = serde_json::to_vec(state).map_err(CheckpointError::Encode)?;
134        self.files
135            .write(&name, &bytes)
136            .await
137            .map_err(|source| CheckpointError::Write { name, source })
138    }
139}
140
141impl Checkpoints {
142    /// The same store, for another kind of checkpoint.
143    pub(crate) fn with_kind(&self, kind: &'static str) -> Self {
144        Self {
145            files: self.files.clone(),
146            kind,
147        }
148    }
149}
150
151/// Where one run keeps its progress: a store and a run id. Parts of the run
152/// (an agent's turn, a node's run) get their own, from [`Saving::part`].
153#[derive(Clone)]
154pub(crate) struct Saving {
155    pub(crate) checkpoints: Checkpoints,
156    pub(crate) run_id: String,
157}
158
159impl Saving {
160    pub(crate) fn new(checkpoints: Checkpoints, run_id: impl Into<String>) -> Self {
161        Self {
162            checkpoints,
163            run_id: run_id.into(),
164        }
165    }
166
167    /// This run's id, kept as `kind`: the journal of one agent run, say.
168    pub(crate) fn kind(&self, kind: &'static str) -> Self {
169        Self::new(self.checkpoints.with_kind(kind), self.run_id.clone())
170    }
171
172    /// The `n`th run of the part `name` of this run, kept as `kind`.
173    pub(crate) fn part(&self, kind: &'static str, name: &str, n: usize) -> Self {
174        Self::new(
175            self.checkpoints.with_kind(kind),
176            part_id(&self.run_id, name, n),
177        )
178    }
179}
180
181/// A run id for the `n`th run of `name` inside run `parent`, within the
182/// 128 characters a run id may have: long ones keep a prefix and a hash.
183fn part_id(parent: &str, name: &str, n: usize) -> String {
184    let name: String = name
185        .chars()
186        .map(|c| {
187            if c.is_ascii_alphanumeric() || c == '-' {
188                c
189            } else {
190                '_'
191            }
192        })
193        .collect();
194    let id = format!("{parent}-{name}-{n}");
195    if id.len() <= 128 {
196        return id;
197    }
198    // FNV-1a: stable across processes and versions, unlike the std hasher.
199    let hash = id.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
200        (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
201    });
202    // Run ids are ASCII; a char boundary keeps any other parent from panicking.
203    format!("{}-{hash:016x}", &id[..id.floor_char_boundary(111)])
204}
205
206/// The results of the tools one agent run executed, kept so that running it
207/// again (a resumed turn or node) replays them instead of executing them
208/// twice: a call with the same tool and arguments gets the recorded result.
209/// Only successful results are kept, so a failed call runs again. The swarm's
210/// handoff tool always runs: its effect is on the run itself.
211#[derive(Clone)]
212pub(crate) struct Journal(Arc<JournalInner>);
213
214struct JournalInner {
215    saving: Saving,
216    state: std::sync::Mutex<JournalState>,
217}
218
219#[derive(Default)]
220struct JournalState {
221    recorded: Vec<Entry>,
222    unreplayed: Vec<Entry>,
223    replaying: std::collections::HashMap<EffectId, ToolResult>,
224}
225
226#[derive(Clone, serde::Serialize, serde::Deserialize)]
227struct Entry {
228    tool: String,
229    args: Value,
230    result: ToolResult,
231}
232
233fn arguments(args: &str) -> Value {
234    serde_json::from_str(args).unwrap_or_else(|_| Value::String(args.to_owned()))
235}
236
237impl Journal {
238    /// The journal kept at `saving`, with what it recorded before.
239    pub(crate) async fn open(saving: Saving) -> Result<Self, CheckpointError> {
240        let recorded: Vec<Entry> = saving
241            .checkpoints
242            .load(&saving.run_id)
243            .await?
244            .unwrap_or_default();
245        Ok(Self(Arc::new(JournalInner {
246            saving,
247            state: std::sync::Mutex::new(JournalState {
248                unreplayed: recorded.clone(),
249                recorded,
250                replaying: std::collections::HashMap::new(),
251            }),
252        })))
253    }
254
255    fn state(&self) -> std::sync::MutexGuard<'_, JournalState> {
256        self.0
257            .state
258            .lock()
259            .unwrap_or_else(std::sync::PoisonError::into_inner)
260    }
261}
262
263impl AgentHook for Journal {
264    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
265        let EffectKind::ToolCall { name, args } = event.kind else {
266            return DispatchAction::proceed();
267        };
268        if name == HANDOFF_TOOL {
269            return DispatchAction::proceed();
270        }
271        let args = arguments(args);
272        let mut state = self.state();
273        let Some(at) = state
274            .unreplayed
275            .iter()
276            .position(|entry| &entry.tool == name && entry.args == args)
277        else {
278            return DispatchAction::proceed();
279        };
280        let entry = state.unreplayed.remove(at);
281        state.replaying.insert(event.id, entry.result);
282        tracing::info!(tool = %name, "tool call replayed from the journal");
283        // The call does not reach the tool; on_outcome answers it.
284        DispatchAction::skip("replayed from the run's journal")
285    }
286
287    async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
288        let EffectKind::ToolCall { name, args } = event.kind else {
289            return OutcomeAction::proceed();
290        };
291        let replayed = self.state().replaying.remove(&event.id);
292        if let Some(result) = replayed {
293            return OutcomeAction::replace(Ok(Answered::ToolResult { result }));
294        }
295        let Some(result) = event.tool_result().filter(|result| result.is_success()) else {
296            return OutcomeAction::proceed();
297        };
298        if name == HANDOFF_TOOL {
299            return OutcomeAction::proceed();
300        }
301        let entries = {
302            let mut state = self.state();
303            state.recorded.push(Entry {
304                tool: name.clone(),
305                args: arguments(args),
306                result: result.clone(),
307            });
308            state.recorded.clone()
309        };
310        let Saving {
311            checkpoints,
312            run_id,
313        } = &self.0.saving;
314        if checkpoints.save(run_id, &entries).await.is_err() {
315            tracing::warn!(
316                kind = "checkpoint",
317                "could not record a tool result in the journal"
318            );
319        }
320        OutcomeAction::proceed()
321    }
322}