use std::collections::BTreeMap;
use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use thiserror::Error;
use crate::checkpoint::Checkpointer;
use crate::error::{GraphError, Result};
use crate::graph::CompiledGraph;
use crate::node::ExecutionConfig;
use crate::record::{LINEAGE_METADATA_KEY, Lineage};
use crate::state::{Checkpoint, State, StateSchema};
#[derive(Debug, Clone, Serialize)]
pub struct StepInfo {
pub step: usize,
pub checkpoint_id: String,
pub timestamp: Option<String>,
pub pending_nodes: Vec<String>,
pub state_keys: Vec<String>,
}
pub struct TimeTravelHandle<'g> {
pub(crate) graph: &'g CompiledGraph,
pub(crate) thread_id: String,
pub(crate) checkpointer: Arc<dyn Checkpointer>,
}
impl<'g> TimeTravelHandle<'g> {
pub fn new(
graph: &'g CompiledGraph,
thread_id: &str,
checkpointer: Arc<dyn Checkpointer>,
) -> Self {
Self { graph, thread_id: thread_id.to_string(), checkpointer }
}
pub async fn steps(&self) -> Result<Vec<StepInfo>> {
let checkpoints = self.checkpointer.list(&self.thread_id).await?;
let mut steps: Vec<StepInfo> = checkpoints
.into_iter()
.map(|cp| StepInfo {
step: cp.step,
checkpoint_id: cp.checkpoint_id,
timestamp: Some(cp.created_at.to_rfc3339()),
pending_nodes: cp.pending_nodes,
state_keys: cp.state.keys().cloned().collect(),
})
.collect();
steps.sort_by_key(|s| s.step);
Ok(steps)
}
pub async fn resume_from(&self, step: usize, config: ExecutionConfig) -> Result<State> {
let checkpoints = self.checkpointer.list(&self.thread_id).await?;
let checkpoint = checkpoints.into_iter().find(|cp| cp.step == step).ok_or_else(|| {
GraphError::CheckpointError(format!(
"no checkpoint found at step {step} for thread '{}'",
self.thread_id
))
})?;
let mut resume_config =
ExecutionConfig::new(&config.thread_id).with_resume_from(&checkpoint.checkpoint_id);
resume_config.recursion_limit = config.recursion_limit;
self.graph.invoke(State::new(), resume_config).await
}
pub async fn fork_at(&self, step: usize, new_thread_id: &str) -> Result<()> {
let checkpoints = self.checkpointer.list(&self.thread_id).await?;
let checkpoint = checkpoints.into_iter().find(|cp| cp.step == step).ok_or_else(|| {
GraphError::CheckpointError(format!(
"no checkpoint found at step {step} for thread '{}'",
self.thread_id
))
})?;
let version =
self.checkpointer.load(new_thread_id).await?.map_or(1, |newest| newest.version + 1);
let forked =
forked_checkpoint(&checkpoint, new_thread_id, version, &BTreeMap::new(), true)?;
self.checkpointer.save(&forked).await?;
Ok(())
}
pub async fn state_history(
&self,
from_step: usize,
to_step: Option<usize>,
) -> Result<Vec<(usize, State)>> {
let mut checkpoints = self.checkpointer.list(&self.thread_id).await?;
checkpoints.sort_by_key(|cp| cp.step);
let results: Vec<(usize, State)> = checkpoints
.into_iter()
.filter(|cp| cp.step >= from_step && to_step.is_none_or(|end| cp.step <= end))
.map(|cp| (cp.step, cp.state))
.collect();
if results.is_empty() || results[0].0 != from_step {
return Err(GraphError::CheckpointError(format!(
"no checkpoint found at step {from_step} for thread '{}'",
self.thread_id
)));
}
Ok(results)
}
}
impl TimeTravelHandle<'_> {
pub async fn fork(&self, spec: ForkSpec) -> std::result::Result<Checkpoint, ForkError> {
let source = self
.checkpointer
.load_by_id(&spec.from)
.await?
.ok_or_else(|| ForkError::UnknownCheckpoint { id: spec.from.clone() })?;
if source.thread_id != self.thread_id {
return Err(ForkError::OtherThread {
id: spec.from,
thread: source.thread_id,
expected: self.thread_id.clone(),
});
}
fork_thread(self.checkpointer.as_ref(), spec, Some(self.graph.schema())).await
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ForkSpec {
pub from: String,
pub new_thread_id: String,
pub set: BTreeMap<String, Value>,
}
impl ForkSpec {
pub fn new(from: impl Into<String>, new_thread_id: impl Into<String>) -> Self {
Self { from: from.into(), new_thread_id: new_thread_id.into(), set: BTreeMap::new() }
}
#[must_use]
pub fn set(mut self, key: impl Into<String>, value: Value) -> Self {
self.set.insert(key.into(), value);
self
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ForkError {
#[error("fork.unknown_checkpoint: no checkpoint '{id}'")]
UnknownCheckpoint {
id: String,
},
#[error("fork.other_thread: checkpoint '{id}' belongs to thread '{thread}', not '{expected}'")]
OtherThread {
id: String,
thread: String,
expected: String,
},
#[error(
"fork.paused: checkpoint '{id}' is a pause, where a node waits mid-step; fork from the \
completed checkpoint of its step"
)]
Paused {
id: String,
},
#[error(
"fork.nothing_to_run: nothing runs after the last step: checkpoint '{id}' has no pending nodes"
)]
NothingToRun {
id: String,
},
#[error("fork.undeclared_channel: '{key}' is not a channel of this graph")]
UndeclaredChannel {
key: String,
},
#[error(
"fork.unknown_key: '{key}' is not a key of this checkpoint; without the graph's channels \
only existing keys can be edited"
)]
UnknownKey {
key: String,
},
#[error(
"fork.thread_exists: thread '{thread}' already has checkpoints; fork into a new thread"
)]
ThreadExists {
thread: String,
},
#[error(transparent)]
Checkpointer(#[from] GraphError),
}
impl ForkError {
pub fn code(&self) -> &'static str {
match self {
Self::UnknownCheckpoint { .. } => "fork.unknown_checkpoint",
Self::OtherThread { .. } => "fork.other_thread",
Self::Paused { .. } => "fork.paused",
Self::NothingToRun { .. } => "fork.nothing_to_run",
Self::UndeclaredChannel { .. } => "fork.undeclared_channel",
Self::UnknownKey { .. } => "fork.unknown_key",
Self::ThreadExists { .. } => "fork.thread_exists",
Self::Checkpointer(_) => "fork.checkpointer",
}
}
}
impl From<ForkError> for GraphError {
fn from(error: ForkError) -> Self {
match error {
ForkError::Checkpointer(error) => error,
refusal => GraphError::CheckpointError(refusal.to_string()),
}
}
}
pub async fn fork_thread(
checkpointer: &dyn Checkpointer,
spec: ForkSpec,
schema: Option<&StateSchema>,
) -> std::result::Result<Checkpoint, ForkError> {
let source = checkpointer
.load_by_id(&spec.from)
.await?
.ok_or_else(|| ForkError::UnknownCheckpoint { id: spec.from.clone() })?;
if source.is_paused() {
return Err(ForkError::Paused { id: spec.from });
}
if source.pending_nodes.is_empty() {
return Err(ForkError::NothingToRun { id: spec.from });
}
let schema = schema.filter(|schema| !schema.channels.is_empty());
for key in spec.set.keys() {
match schema {
Some(schema) if !schema.channels.contains_key(key) => {
return Err(ForkError::UndeclaredChannel { key: key.clone() });
}
None if !source.state.contains_key(key) => {
return Err(ForkError::UnknownKey { key: key.clone() });
}
_ => {}
}
}
if spec.new_thread_id == source.thread_id
|| checkpointer.load(&spec.new_thread_id).await?.is_some()
{
return Err(ForkError::ThreadExists { thread: spec.new_thread_id });
}
let fork = forked_checkpoint(&source, &spec.new_thread_id, 1, &spec.set, schema.is_some())?;
checkpointer.save(&fork).await?;
tracing::info!(
thread_id = %source.thread_id,
fork.thread_id = %spec.new_thread_id,
fork.edited = spec.set.len(),
"forked a graph thread"
);
Ok(fork)
}
fn forked_checkpoint(
source: &Checkpoint,
thread: &str,
version: u64,
set: &BTreeMap<String, Value>,
checked: bool,
) -> Result<Checkpoint> {
let mut state = source.state.clone();
for (key, value) in set {
state.insert(key.clone(), value.clone());
}
let mut fork = Checkpoint::new(thread, state, source.step, source.pending_nodes.clone())
.with_version(version);
for key in [crate::deferred::FAN_IN_METADATA_KEY, crate::executor::OCCURRENCES_METADATA_KEY] {
if let Some(value) = source.metadata.get(key) {
fork.metadata.insert(key.to_string(), value.clone());
}
}
let root = source.lineage()?.map_or_else(|| source.thread_id.clone(), |lineage| lineage.root);
let lineage = Lineage {
root,
parent: source.thread_id.clone(),
parent_checkpoint: source.checkpoint_id.clone(),
parent_step: source.step_label(),
edited: set.keys().cloned().collect(),
checked,
};
fork.metadata.insert(LINEAGE_METADATA_KEY.to_string(), serde_json::to_value(lineage)?);
Ok(fork)
}
impl CompiledGraph {
pub fn time_travel(&self, thread_id: &str) -> Result<TimeTravelHandle<'_>> {
let checkpointer = self.checkpointer.clone().ok_or_else(|| {
GraphError::CheckpointError(
"time travel needs a checkpointer. Add one with with_checkpointer before calling time_travel"
.to_string(),
)
})?;
Ok(TimeTravelHandle::new(self, thread_id, checkpointer))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::checkpoint::MemoryCheckpointer;
use crate::graph::StateGraph;
use crate::node::{ExecutionConfig, FunctionNode, NodeContext, NodeOutput};
use crate::state::{Checkpoint, State, StateSchema};
use serde_json::json;
fn build_test_graph() -> (CompiledGraph, Arc<MemoryCheckpointer>) {
let checkpointer = Arc::new(MemoryCheckpointer::new());
let node = FunctionNode::new("increment", |ctx: NodeContext| {
let count = ctx.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
Box::pin(async move { Ok(NodeOutput::new().with_update("count", json!(count + 1))) })
});
let graph = StateGraph::new(StateSchema::simple(&["count"]))
.add_node(node)
.add_edge("__start__", "increment")
.add_edge("increment", "__end__")
.compile()
.unwrap()
.with_checkpointer_arc(checkpointer.clone());
(graph, checkpointer)
}
async fn seed_checkpoints(checkpointer: &MemoryCheckpointer, thread_id: &str, count: usize) {
for step in 0..count {
let mut state = State::new();
state.insert("count".to_string(), json!(step));
let cp = Checkpoint::new(thread_id, state, step, vec!["increment".to_string()])
.with_version(step as u64 + 1);
checkpointer.save(&cp).await.unwrap();
}
}
#[tokio::test]
async fn test_fork_at_creates_new_thread() {
let (graph, checkpointer) = build_test_graph();
seed_checkpoints(&checkpointer, "thread_1", 5).await;
let handle = graph.time_travel("thread_1").unwrap();
handle.fork_at(2, "thread_1_fork").await.unwrap();
let forked_checkpoints = checkpointer.list("thread_1_fork").await.unwrap();
assert_eq!(forked_checkpoints.len(), 1);
assert_eq!(forked_checkpoints[0].step, 2);
assert_eq!(forked_checkpoints[0].state.get("count"), Some(&json!(2)));
let original_checkpoints = checkpointer.list("thread_1").await.unwrap();
assert_eq!(original_checkpoints.len(), 5);
}
#[tokio::test]
async fn test_fork_at_nonexistent_step_errors() {
let (graph, checkpointer) = build_test_graph();
seed_checkpoints(&checkpointer, "thread_1", 3).await;
let handle = graph.time_travel("thread_1").unwrap();
let result = handle.fork_at(99, "new_thread").await;
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string();
assert!(err_msg.contains("no checkpoint found at step 99"));
}
#[tokio::test]
async fn test_state_history_returns_states_in_range() {
let (graph, checkpointer) = build_test_graph();
seed_checkpoints(&checkpointer, "thread_1", 5).await;
let handle = graph.time_travel("thread_1").unwrap();
let results = handle.state_history(1, Some(3)).await.unwrap();
assert_eq!(results.len(), 3);
assert_eq!(
results[0],
(1, {
let mut s = State::new();
s.insert("count".to_string(), json!(1));
s
})
);
assert_eq!(results[1].0, 2);
assert_eq!(results[2].0, 3);
}
#[tokio::test]
async fn test_state_history_to_end() {
let (graph, checkpointer) = build_test_graph();
seed_checkpoints(&checkpointer, "thread_1", 5).await;
let handle = graph.time_travel("thread_1").unwrap();
let results = handle.state_history(2, None).await.unwrap();
assert_eq!(results.len(), 3); assert_eq!(results[0].0, 2);
assert_eq!(results[1].0, 3);
assert_eq!(results[2].0, 4);
}
#[tokio::test]
async fn test_replay_nonexistent_from_step_errors() {
let (graph, checkpointer) = build_test_graph();
seed_checkpoints(&checkpointer, "thread_1", 3).await;
let handle = graph.time_travel("thread_1").unwrap();
let result = handle.state_history(99, None).await;
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string();
assert!(err_msg.contains("no checkpoint found at step 99"));
}
#[tokio::test]
async fn test_resume_from_executes_graph() {
let (graph, checkpointer) = build_test_graph();
let mut state = State::new();
state.insert("count".to_string(), json!(5));
let cp =
Checkpoint::new("thread_1", state, 0, vec!["increment".to_string()]).with_version(1);
checkpointer.save(&cp).await.unwrap();
let handle = graph.time_travel("thread_1").unwrap();
let config = ExecutionConfig::new("thread_1");
let final_state = handle.resume_from(0, config).await.unwrap();
assert_eq!(final_state.get("count"), Some(&json!(6)));
}
#[tokio::test]
async fn test_resume_from_nonexistent_step_errors() {
let (graph, checkpointer) = build_test_graph();
seed_checkpoints(&checkpointer, "thread_1", 3).await;
let handle = graph.time_travel("thread_1").unwrap();
let config = ExecutionConfig::new("thread_1");
let result = handle.resume_from(99, config).await;
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string();
assert!(err_msg.contains("no checkpoint found at step 99"));
}
#[tokio::test]
async fn test_fork_independence() {
let (graph, checkpointer) = build_test_graph();
seed_checkpoints(&checkpointer, "thread_1", 5).await;
let handle = graph.time_travel("thread_1").unwrap();
handle.fork_at(2, "forked").await.unwrap();
let mut new_state = State::new();
new_state.insert("count".to_string(), json!(100));
let new_cp = Checkpoint::new("forked", new_state, 3, vec![]).with_version(2);
checkpointer.save(&new_cp).await.unwrap();
let original = checkpointer.list("thread_1").await.unwrap();
assert_eq!(original.len(), 5);
for cp in &original {
assert_ne!(cp.state.get("count"), Some(&json!(100)));
}
}
}